babylon.no-module.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /** @hidden */
  159. this._bonesComputationForcedToCPU = false;
  160. this._uniformBuffersNames = {};
  161. this._isReady = false;
  162. this._compilationError = "";
  163. this.name = baseName;
  164. if (attributesNamesOrOptions.attributes) {
  165. var options = attributesNamesOrOptions;
  166. this._engine = uniformsNamesOrEngine;
  167. this._attributesNames = options.attributes;
  168. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  169. this._samplers = options.samplers.slice();
  170. this.defines = options.defines;
  171. this.onError = options.onError;
  172. this.onCompiled = options.onCompiled;
  173. this._fallbacks = options.fallbacks;
  174. this._indexParameters = options.indexParameters;
  175. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  176. if (options.uniformBuffersNames) {
  177. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  178. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  179. }
  180. }
  181. }
  182. else {
  183. this._engine = engine;
  184. this.defines = defines;
  185. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  186. this._samplers = samplers ? samplers.slice() : [];
  187. this._attributesNames = attributesNamesOrOptions;
  188. this.onError = onError;
  189. this.onCompiled = onCompiled;
  190. this._indexParameters = indexParameters;
  191. this._fallbacks = fallbacks;
  192. }
  193. this.uniqueId = Effect._uniqueIdSeed++;
  194. var vertexSource;
  195. var fragmentSource;
  196. if (baseName.vertexElement) {
  197. vertexSource = document.getElementById(baseName.vertexElement);
  198. if (!vertexSource) {
  199. vertexSource = baseName.vertexElement;
  200. }
  201. }
  202. else {
  203. vertexSource = baseName.vertex || baseName;
  204. }
  205. if (baseName.fragmentElement) {
  206. fragmentSource = document.getElementById(baseName.fragmentElement);
  207. if (!fragmentSource) {
  208. fragmentSource = baseName.fragmentElement;
  209. }
  210. }
  211. else {
  212. fragmentSource = baseName.fragment || baseName;
  213. }
  214. this._loadVertexShader(vertexSource, function (vertexCode) {
  215. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  216. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  217. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  218. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  219. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  220. if (baseName) {
  221. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  222. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  223. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  224. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  225. }
  226. else {
  227. _this._vertexSourceCode = migratedVertexCode;
  228. _this._fragmentSourceCode = migratedFragmentCode;
  229. }
  230. _this._prepareEffect();
  231. });
  232. });
  233. });
  234. });
  235. });
  236. });
  237. }
  238. Object.defineProperty(Effect.prototype, "onBindObservable", {
  239. /**
  240. * Observable that will be called when effect is bound.
  241. */
  242. get: function () {
  243. if (!this._onBindObservable) {
  244. this._onBindObservable = new BABYLON.Observable();
  245. }
  246. return this._onBindObservable;
  247. },
  248. enumerable: true,
  249. configurable: true
  250. });
  251. Object.defineProperty(Effect.prototype, "key", {
  252. /**
  253. * Unique key for this effect
  254. */
  255. get: function () {
  256. return this._key;
  257. },
  258. enumerable: true,
  259. configurable: true
  260. });
  261. /**
  262. * If the effect has been compiled and prepared.
  263. * @returns if the effect is compiled and prepared.
  264. */
  265. Effect.prototype.isReady = function () {
  266. return this._isReady;
  267. };
  268. /**
  269. * The engine the effect was initialized with.
  270. * @returns the engine.
  271. */
  272. Effect.prototype.getEngine = function () {
  273. return this._engine;
  274. };
  275. /**
  276. * The compiled webGL program for the effect
  277. * @returns the webGL program.
  278. */
  279. Effect.prototype.getProgram = function () {
  280. return this._program;
  281. };
  282. /**
  283. * The set of names of attribute variables for the shader.
  284. * @returns An array of attribute names.
  285. */
  286. Effect.prototype.getAttributesNames = function () {
  287. return this._attributesNames;
  288. };
  289. /**
  290. * Returns the attribute at the given index.
  291. * @param index The index of the attribute.
  292. * @returns The location of the attribute.
  293. */
  294. Effect.prototype.getAttributeLocation = function (index) {
  295. return this._attributes[index];
  296. };
  297. /**
  298. * Returns the attribute based on the name of the variable.
  299. * @param name of the attribute to look up.
  300. * @returns the attribute location.
  301. */
  302. Effect.prototype.getAttributeLocationByName = function (name) {
  303. var index = this._attributesNames.indexOf(name);
  304. return this._attributes[index];
  305. };
  306. /**
  307. * The number of attributes.
  308. * @returns the numnber of attributes.
  309. */
  310. Effect.prototype.getAttributesCount = function () {
  311. return this._attributes.length;
  312. };
  313. /**
  314. * Gets the index of a uniform variable.
  315. * @param uniformName of the uniform to look up.
  316. * @returns the index.
  317. */
  318. Effect.prototype.getUniformIndex = function (uniformName) {
  319. return this._uniformsNames.indexOf(uniformName);
  320. };
  321. /**
  322. * Returns the attribute based on the name of the variable.
  323. * @param uniformName of the uniform to look up.
  324. * @returns the location of the uniform.
  325. */
  326. Effect.prototype.getUniform = function (uniformName) {
  327. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  328. };
  329. /**
  330. * Returns an array of sampler variable names
  331. * @returns The array of sampler variable neames.
  332. */
  333. Effect.prototype.getSamplers = function () {
  334. return this._samplers;
  335. };
  336. /**
  337. * The error from the last compilation.
  338. * @returns the error string.
  339. */
  340. Effect.prototype.getCompilationError = function () {
  341. return this._compilationError;
  342. };
  343. /**
  344. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  345. * @param func The callback to be used.
  346. */
  347. Effect.prototype.executeWhenCompiled = function (func) {
  348. if (this.isReady()) {
  349. func(this);
  350. return;
  351. }
  352. this.onCompileObservable.add(function (effect) {
  353. func(effect);
  354. });
  355. };
  356. /** @hidden */
  357. Effect.prototype._loadVertexShader = function (vertex, callback) {
  358. if (BABYLON.Tools.IsWindowObjectExist()) {
  359. // DOM element ?
  360. if (vertex instanceof HTMLElement) {
  361. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  362. callback(vertexCode);
  363. return;
  364. }
  365. }
  366. // Base64 encoded ?
  367. if (vertex.substr(0, 7) === "base64:") {
  368. var vertexBinary = window.atob(vertex.substr(7));
  369. callback(vertexBinary);
  370. return;
  371. }
  372. // Is in local store ?
  373. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  374. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  375. return;
  376. }
  377. var vertexShaderUrl;
  378. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  379. vertexShaderUrl = vertex;
  380. }
  381. else {
  382. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  383. }
  384. // Vertex shader
  385. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  386. };
  387. /** @hidden */
  388. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  389. if (BABYLON.Tools.IsWindowObjectExist()) {
  390. // DOM element ?
  391. if (fragment instanceof HTMLElement) {
  392. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  393. callback(fragmentCode);
  394. return;
  395. }
  396. }
  397. // Base64 encoded ?
  398. if (fragment.substr(0, 7) === "base64:") {
  399. var fragmentBinary = window.atob(fragment.substr(7));
  400. callback(fragmentBinary);
  401. return;
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  406. return;
  407. }
  408. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  409. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  410. return;
  411. }
  412. var fragmentShaderUrl;
  413. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  414. fragmentShaderUrl = fragment;
  415. }
  416. else {
  417. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  418. }
  419. // Fragment shader
  420. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  421. };
  422. /** @hidden */
  423. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  424. // Rebuild shaders source code
  425. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  426. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  427. vertexCode = prefix + vertexCode;
  428. fragmentCode = prefix + fragmentCode;
  429. // Number lines of shaders source code
  430. var i = 2;
  431. var regex = /\n/gm;
  432. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  433. i = 2;
  434. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  435. // Dump shaders name and formatted source code
  436. if (this.name.vertexElement) {
  437. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  438. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  439. }
  440. else if (this.name.vertex) {
  441. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  442. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  443. }
  444. else {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  447. }
  448. };
  449. ;
  450. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  451. var preparedSourceCode = this._processPrecision(sourceCode);
  452. if (this._engine.webGLVersion == 1) {
  453. callback(preparedSourceCode);
  454. return;
  455. }
  456. // Already converted
  457. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  458. callback(preparedSourceCode.replace("#version 300 es", ""));
  459. return;
  460. }
  461. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  462. // Remove extensions
  463. // #extension GL_OES_standard_derivatives : enable
  464. // #extension GL_EXT_shader_texture_lod : enable
  465. // #extension GL_EXT_frag_depth : enable
  466. // #extension GL_EXT_draw_buffers : require
  467. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  468. var result = preparedSourceCode.replace(regex, "");
  469. // Migrate to GLSL v300
  470. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  471. result = result.replace(/attribute[ \t]/g, "in ");
  472. result = result.replace(/[ \t]attribute/g, " in");
  473. if (isFragment) {
  474. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  475. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  476. result = result.replace(/texture2D\s*\(/g, "texture(");
  477. result = result.replace(/textureCube\s*\(/g, "texture(");
  478. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  479. result = result.replace(/gl_FragColor/g, "glFragColor");
  480. result = result.replace(/gl_FragData/g, "glFragData");
  481. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  482. }
  483. callback(result);
  484. };
  485. Effect.prototype._processIncludes = function (sourceCode, callback) {
  486. var _this = this;
  487. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  488. var match = regex.exec(sourceCode);
  489. var returnValue = new String(sourceCode);
  490. while (match != null) {
  491. var includeFile = match[1];
  492. // Uniform declaration
  493. if (includeFile.indexOf("__decl__") !== -1) {
  494. includeFile = includeFile.replace(/__decl__/, "");
  495. if (this._engine.supportsUniformBuffers) {
  496. includeFile = includeFile.replace(/Vertex/, "Ubo");
  497. includeFile = includeFile.replace(/Fragment/, "Ubo");
  498. }
  499. includeFile = includeFile + "Declaration";
  500. }
  501. if (Effect.IncludesShadersStore[includeFile]) {
  502. // Substitution
  503. var includeContent = Effect.IncludesShadersStore[includeFile];
  504. if (match[2]) {
  505. var splits = match[3].split(",");
  506. for (var index = 0; index < splits.length; index += 2) {
  507. var source = new RegExp(splits[index], "g");
  508. var dest = splits[index + 1];
  509. includeContent = includeContent.replace(source, dest);
  510. }
  511. }
  512. if (match[4]) {
  513. var indexString = match[5];
  514. if (indexString.indexOf("..") !== -1) {
  515. var indexSplits = indexString.split("..");
  516. var minIndex = parseInt(indexSplits[0]);
  517. var maxIndex = parseInt(indexSplits[1]);
  518. var sourceIncludeContent = includeContent.slice(0);
  519. includeContent = "";
  520. if (isNaN(maxIndex)) {
  521. maxIndex = this._indexParameters[indexSplits[1]];
  522. }
  523. for (var i = minIndex; i < maxIndex; i++) {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  531. }
  532. }
  533. else {
  534. if (!this._engine.supportsUniformBuffers) {
  535. // Ubo replacement
  536. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  537. return p1 + "{X}";
  538. });
  539. }
  540. includeContent = includeContent.replace(/\{X\}/g, indexString);
  541. }
  542. }
  543. // Replace
  544. returnValue = returnValue.replace(match[0], includeContent);
  545. }
  546. else {
  547. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  548. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  549. Effect.IncludesShadersStore[includeFile] = fileContent;
  550. _this._processIncludes(returnValue, callback);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. callback(returnValue);
  557. };
  558. Effect.prototype._processPrecision = function (source) {
  559. if (source.indexOf("precision highp float") === -1) {
  560. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  561. source = "precision mediump float;\n" + source;
  562. }
  563. else {
  564. source = "precision highp float;\n" + source;
  565. }
  566. }
  567. else {
  568. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  569. source = source.replace("precision highp float", "precision mediump float");
  570. }
  571. }
  572. return source;
  573. };
  574. /**
  575. * Recompiles the webGL program
  576. * @param vertexSourceCode The source code for the vertex shader.
  577. * @param fragmentSourceCode The source code for the fragment shader.
  578. * @param onCompiled Callback called when completed.
  579. * @param onError Callback called on error.
  580. * @hidden
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. * @hidden
  616. */
  617. Effect.prototype._prepareEffect = function () {
  618. var attributesNames = this._attributesNames;
  619. var defines = this.defines;
  620. var fallbacks = this._fallbacks;
  621. this._valueCache = {};
  622. var previousProgram = this._program;
  623. try {
  624. var engine = this._engine;
  625. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  626. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  627. }
  628. else {
  629. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  630. }
  631. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  632. if (engine.supportsUniformBuffers) {
  633. for (var name in this._uniformBuffersNames) {
  634. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  635. }
  636. }
  637. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  638. this._attributes = engine.getAttributes(this._program, attributesNames);
  639. var index;
  640. for (index = 0; index < this._samplers.length; index++) {
  641. var sampler = this.getUniform(this._samplers[index]);
  642. if (sampler == null) {
  643. this._samplers.splice(index, 1);
  644. index--;
  645. }
  646. }
  647. engine.bindSamplers(this);
  648. this._compilationError = "";
  649. this._isReady = true;
  650. if (this.onCompiled) {
  651. this.onCompiled(this);
  652. }
  653. this.onCompileObservable.notifyObservers(this);
  654. this.onCompileObservable.clear();
  655. // Unbind mesh reference in fallbacks
  656. if (this._fallbacks) {
  657. this._fallbacks.unBindMesh();
  658. }
  659. if (previousProgram) {
  660. this.getEngine()._deleteProgram(previousProgram);
  661. }
  662. }
  663. catch (e) {
  664. this._compilationError = e.message;
  665. // Let's go through fallbacks then
  666. BABYLON.Tools.Error("Unable to compile effect:");
  667. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  668. return " " + uniform;
  669. }));
  670. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  671. return " " + attribute;
  672. }));
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else { // Sorry we did everything we can
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. * @hidden
  715. */
  716. Effect.prototype._bindTexture = function (channel, texture) {
  717. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  718. };
  719. /**
  720. * Sets a texture on the engine to be used in the shader.
  721. * @param channel Name of the sampler variable.
  722. * @param texture Texture to set.
  723. */
  724. Effect.prototype.setTexture = function (channel, texture) {
  725. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  726. };
  727. /**
  728. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  729. * @param channel Name of the sampler variable.
  730. * @param texture Texture to set.
  731. */
  732. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  733. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  734. };
  735. /**
  736. * Sets an array of textures on the engine to be used in the shader.
  737. * @param channel Name of the variable.
  738. * @param textures Textures to set.
  739. */
  740. Effect.prototype.setTextureArray = function (channel, textures) {
  741. if (this._samplers.indexOf(channel + "Ex") === -1) {
  742. var initialPos = this._samplers.indexOf(channel);
  743. for (var index = 1; index < textures.length; index++) {
  744. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  745. }
  746. }
  747. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  748. };
  749. /**
  750. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  751. * @param channel Name of the sampler variable.
  752. * @param postProcess Post process to get the input texture from.
  753. */
  754. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  755. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  756. };
  757. /**
  758. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  759. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  760. * @param channel Name of the sampler variable.
  761. * @param postProcess Post process to get the output texture from.
  762. */
  763. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  764. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  765. };
  766. /** @hidden */
  767. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  768. var cache = this._valueCache[uniformName];
  769. var flag = matrix.updateFlag;
  770. if (cache !== undefined && cache === flag) {
  771. return false;
  772. }
  773. this._valueCache[uniformName] = flag;
  774. return true;
  775. };
  776. /** @hidden */
  777. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  778. var cache = this._valueCache[uniformName];
  779. if (!cache) {
  780. cache = [x, y];
  781. this._valueCache[uniformName] = cache;
  782. return true;
  783. }
  784. var changed = false;
  785. if (cache[0] !== x) {
  786. cache[0] = x;
  787. changed = true;
  788. }
  789. if (cache[1] !== y) {
  790. cache[1] = y;
  791. changed = true;
  792. }
  793. return changed;
  794. };
  795. /** @hidden */
  796. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  797. var cache = this._valueCache[uniformName];
  798. if (!cache) {
  799. cache = [x, y, z];
  800. this._valueCache[uniformName] = cache;
  801. return true;
  802. }
  803. var changed = false;
  804. if (cache[0] !== x) {
  805. cache[0] = x;
  806. changed = true;
  807. }
  808. if (cache[1] !== y) {
  809. cache[1] = y;
  810. changed = true;
  811. }
  812. if (cache[2] !== z) {
  813. cache[2] = z;
  814. changed = true;
  815. }
  816. return changed;
  817. };
  818. /** @hidden */
  819. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  820. var cache = this._valueCache[uniformName];
  821. if (!cache) {
  822. cache = [x, y, z, w];
  823. this._valueCache[uniformName] = cache;
  824. return true;
  825. }
  826. var changed = false;
  827. if (cache[0] !== x) {
  828. cache[0] = x;
  829. changed = true;
  830. }
  831. if (cache[1] !== y) {
  832. cache[1] = y;
  833. changed = true;
  834. }
  835. if (cache[2] !== z) {
  836. cache[2] = z;
  837. changed = true;
  838. }
  839. if (cache[3] !== w) {
  840. cache[3] = w;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /**
  846. * Binds a buffer to a uniform.
  847. * @param buffer Buffer to bind.
  848. * @param name Name of the uniform variable to bind to.
  849. */
  850. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  851. var bufferName = this._uniformBuffersNames[name];
  852. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  853. return;
  854. }
  855. Effect._baseCache[bufferName] = buffer;
  856. this._engine.bindUniformBufferBase(buffer, bufferName);
  857. };
  858. /**
  859. * Binds block to a uniform.
  860. * @param blockName Name of the block to bind.
  861. * @param index Index to bind.
  862. */
  863. Effect.prototype.bindUniformBlock = function (blockName, index) {
  864. this._engine.bindUniformBlock(this._program, blockName, index);
  865. };
  866. /**
  867. * Sets an interger value on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param value Value to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setInt = function (uniformName, value) {
  873. var cache = this._valueCache[uniformName];
  874. if (cache !== undefined && cache === value)
  875. return this;
  876. this._valueCache[uniformName] = value;
  877. this._engine.setInt(this.getUniform(uniformName), value);
  878. return this;
  879. };
  880. /**
  881. * Sets an int array on a uniform variable.
  882. * @param uniformName Name of the variable.
  883. * @param array array to be set.
  884. * @returns this effect.
  885. */
  886. Effect.prototype.setIntArray = function (uniformName, array) {
  887. this._valueCache[uniformName] = null;
  888. this._engine.setIntArray(this.getUniform(uniformName), array);
  889. return this;
  890. };
  891. /**
  892. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  893. * @param uniformName Name of the variable.
  894. * @param array array to be set.
  895. * @returns this effect.
  896. */
  897. Effect.prototype.setIntArray2 = function (uniformName, array) {
  898. this._valueCache[uniformName] = null;
  899. this._engine.setIntArray2(this.getUniform(uniformName), array);
  900. return this;
  901. };
  902. /**
  903. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  904. * @param uniformName Name of the variable.
  905. * @param array array to be set.
  906. * @returns this effect.
  907. */
  908. Effect.prototype.setIntArray3 = function (uniformName, array) {
  909. this._valueCache[uniformName] = null;
  910. this._engine.setIntArray3(this.getUniform(uniformName), array);
  911. return this;
  912. };
  913. /**
  914. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  915. * @param uniformName Name of the variable.
  916. * @param array array to be set.
  917. * @returns this effect.
  918. */
  919. Effect.prototype.setIntArray4 = function (uniformName, array) {
  920. this._valueCache[uniformName] = null;
  921. this._engine.setIntArray4(this.getUniform(uniformName), array);
  922. return this;
  923. };
  924. /**
  925. * Sets an float array on a uniform variable.
  926. * @param uniformName Name of the variable.
  927. * @param array array to be set.
  928. * @returns this effect.
  929. */
  930. Effect.prototype.setFloatArray = function (uniformName, array) {
  931. this._valueCache[uniformName] = null;
  932. this._engine.setFloatArray(this.getUniform(uniformName), array);
  933. return this;
  934. };
  935. /**
  936. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  937. * @param uniformName Name of the variable.
  938. * @param array array to be set.
  939. * @returns this effect.
  940. */
  941. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  942. this._valueCache[uniformName] = null;
  943. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  944. return this;
  945. };
  946. /**
  947. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  948. * @param uniformName Name of the variable.
  949. * @param array array to be set.
  950. * @returns this effect.
  951. */
  952. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  953. this._valueCache[uniformName] = null;
  954. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  955. return this;
  956. };
  957. /**
  958. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  959. * @param uniformName Name of the variable.
  960. * @param array array to be set.
  961. * @returns this effect.
  962. */
  963. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  964. this._valueCache[uniformName] = null;
  965. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  966. return this;
  967. };
  968. /**
  969. * Sets an array on a uniform variable.
  970. * @param uniformName Name of the variable.
  971. * @param array array to be set.
  972. * @returns this effect.
  973. */
  974. Effect.prototype.setArray = function (uniformName, array) {
  975. this._valueCache[uniformName] = null;
  976. this._engine.setArray(this.getUniform(uniformName), array);
  977. return this;
  978. };
  979. /**
  980. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  981. * @param uniformName Name of the variable.
  982. * @param array array to be set.
  983. * @returns this effect.
  984. */
  985. Effect.prototype.setArray2 = function (uniformName, array) {
  986. this._valueCache[uniformName] = null;
  987. this._engine.setArray2(this.getUniform(uniformName), array);
  988. return this;
  989. };
  990. /**
  991. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  992. * @param uniformName Name of the variable.
  993. * @param array array to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setArray3 = function (uniformName, array) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setArray3(this.getUniform(uniformName), array);
  999. return this;
  1000. };
  1001. /**
  1002. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1003. * @param uniformName Name of the variable.
  1004. * @param array array to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setArray4 = function (uniformName, array) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setArray4(this.getUniform(uniformName), array);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrices on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrices matrices to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1019. if (!matrices) {
  1020. return this;
  1021. }
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets matrix on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1033. if (this._cacheMatrix(uniformName, matrix)) {
  1034. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1035. }
  1036. return this;
  1037. };
  1038. /**
  1039. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1045. this._valueCache[uniformName] = null;
  1046. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1047. return this;
  1048. };
  1049. /**
  1050. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1051. * @param uniformName Name of the variable.
  1052. * @param matrix matrix to be set.
  1053. * @returns this effect.
  1054. */
  1055. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1056. this._valueCache[uniformName] = null;
  1057. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a float on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param value value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setFloat = function (uniformName, value) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === value)
  1069. return this;
  1070. this._valueCache[uniformName] = value;
  1071. this._engine.setFloat(this.getUniform(uniformName), value);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a boolean on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param bool value to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setBool = function (uniformName, bool) {
  1081. var cache = this._valueCache[uniformName];
  1082. if (cache !== undefined && cache === bool)
  1083. return this;
  1084. this._valueCache[uniformName] = bool;
  1085. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a Vector2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param vector2 vector2 to be set.
  1092. * @returns this effect.
  1093. */
  1094. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1095. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1096. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1097. }
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a float2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param x First float in float2.
  1104. * @param y Second float in float2.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1108. if (this._cacheFloat2(uniformName, x, y)) {
  1109. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a Vector3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param vector3 Value to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1120. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a float3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param x First float in float3.
  1129. * @param y Second float in float3.
  1130. * @param z Third float in float3.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1134. if (this._cacheFloat3(uniformName, x, y, z)) {
  1135. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a Vector4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param vector4 Value to be set.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1146. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a float4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param x First float in float4.
  1155. * @param y Second float in float4.
  1156. * @param z Third float in float4.
  1157. * @param w Fourth float in float4.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1161. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color3 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setColor3 = function (uniformName, color3) {
  1173. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1174. this._engine.setColor3(this.getUniform(uniformName), color3);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @param alpha Alpha value to be set.
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1186. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1187. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Sets a Color4 on a uniform variable
  1193. * @param uniformName defines the name of the variable
  1194. * @param color4 defines the value to be set
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1198. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1199. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * This function will add a new shader to the shader store
  1205. * @param name the name of the shader
  1206. * @param pixelShader optional pixel shader content
  1207. * @param vertexShader optional vertex shader content
  1208. */
  1209. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1210. if (pixelShader) {
  1211. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1212. }
  1213. if (vertexShader) {
  1214. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1215. }
  1216. };
  1217. /**
  1218. * Resets the cache of effects.
  1219. */
  1220. Effect.ResetCache = function () {
  1221. Effect._baseCache = {};
  1222. };
  1223. Effect._uniqueIdSeed = 0;
  1224. Effect._baseCache = {};
  1225. /**
  1226. * Store of each shader (The can be looked up using effect.key)
  1227. */
  1228. Effect.ShadersStore = {};
  1229. /**
  1230. * Store of each included file for a shader (The can be looked up using effect.key)
  1231. */
  1232. Effect.IncludesShadersStore = {};
  1233. return Effect;
  1234. }());
  1235. BABYLON.Effect = Effect;
  1236. })(BABYLON || (BABYLON = {}));
  1237. //# sourceMappingURL=babylon.effect.js.map
  1238. //# sourceMappingURL=babylon.types.js.map
  1239. var BABYLON;
  1240. (function (BABYLON) {
  1241. var KeyboardEventTypes = /** @class */ (function () {
  1242. function KeyboardEventTypes() {
  1243. }
  1244. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1245. get: function () {
  1246. return KeyboardEventTypes._KEYDOWN;
  1247. },
  1248. enumerable: true,
  1249. configurable: true
  1250. });
  1251. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1252. get: function () {
  1253. return KeyboardEventTypes._KEYUP;
  1254. },
  1255. enumerable: true,
  1256. configurable: true
  1257. });
  1258. KeyboardEventTypes._KEYDOWN = 0x01;
  1259. KeyboardEventTypes._KEYUP = 0x02;
  1260. return KeyboardEventTypes;
  1261. }());
  1262. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1263. var KeyboardInfo = /** @class */ (function () {
  1264. function KeyboardInfo(type, event) {
  1265. this.type = type;
  1266. this.event = event;
  1267. }
  1268. return KeyboardInfo;
  1269. }());
  1270. BABYLON.KeyboardInfo = KeyboardInfo;
  1271. /**
  1272. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1273. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1274. */
  1275. var KeyboardInfoPre = /** @class */ (function (_super) {
  1276. __extends(KeyboardInfoPre, _super);
  1277. function KeyboardInfoPre(type, event) {
  1278. var _this = _super.call(this, type, event) || this;
  1279. _this.skipOnPointerObservable = false;
  1280. return _this;
  1281. }
  1282. return KeyboardInfoPre;
  1283. }(KeyboardInfo));
  1284. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1285. })(BABYLON || (BABYLON = {}));
  1286. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1287. var BABYLON;
  1288. (function (BABYLON) {
  1289. var PointerEventTypes = /** @class */ (function () {
  1290. function PointerEventTypes() {
  1291. }
  1292. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1293. get: function () {
  1294. return PointerEventTypes._POINTERDOWN;
  1295. },
  1296. enumerable: true,
  1297. configurable: true
  1298. });
  1299. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1300. get: function () {
  1301. return PointerEventTypes._POINTERUP;
  1302. },
  1303. enumerable: true,
  1304. configurable: true
  1305. });
  1306. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1307. get: function () {
  1308. return PointerEventTypes._POINTERMOVE;
  1309. },
  1310. enumerable: true,
  1311. configurable: true
  1312. });
  1313. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1314. get: function () {
  1315. return PointerEventTypes._POINTERWHEEL;
  1316. },
  1317. enumerable: true,
  1318. configurable: true
  1319. });
  1320. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1321. get: function () {
  1322. return PointerEventTypes._POINTERPICK;
  1323. },
  1324. enumerable: true,
  1325. configurable: true
  1326. });
  1327. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1328. get: function () {
  1329. return PointerEventTypes._POINTERTAP;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1335. get: function () {
  1336. return PointerEventTypes._POINTERDOUBLETAP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. PointerEventTypes._POINTERDOWN = 0x01;
  1342. PointerEventTypes._POINTERUP = 0x02;
  1343. PointerEventTypes._POINTERMOVE = 0x04;
  1344. PointerEventTypes._POINTERWHEEL = 0x08;
  1345. PointerEventTypes._POINTERPICK = 0x10;
  1346. PointerEventTypes._POINTERTAP = 0x20;
  1347. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1348. return PointerEventTypes;
  1349. }());
  1350. BABYLON.PointerEventTypes = PointerEventTypes;
  1351. var PointerInfoBase = /** @class */ (function () {
  1352. function PointerInfoBase(type, event) {
  1353. this.type = type;
  1354. this.event = event;
  1355. }
  1356. return PointerInfoBase;
  1357. }());
  1358. BABYLON.PointerInfoBase = PointerInfoBase;
  1359. /**
  1360. * This class is used to store pointer related info for the onPrePointerObservable event.
  1361. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1362. */
  1363. var PointerInfoPre = /** @class */ (function (_super) {
  1364. __extends(PointerInfoPre, _super);
  1365. function PointerInfoPre(type, event, localX, localY) {
  1366. var _this = _super.call(this, type, event) || this;
  1367. /**
  1368. * Ray from a pointer if availible (eg. 6dof controller)
  1369. */
  1370. _this.ray = null;
  1371. _this.skipOnPointerObservable = false;
  1372. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1373. return _this;
  1374. }
  1375. return PointerInfoPre;
  1376. }(PointerInfoBase));
  1377. BABYLON.PointerInfoPre = PointerInfoPre;
  1378. /**
  1379. * This type contains all the data related to a pointer event in Babylon.js.
  1380. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1381. */
  1382. var PointerInfo = /** @class */ (function (_super) {
  1383. __extends(PointerInfo, _super);
  1384. function PointerInfo(type, event, pickInfo) {
  1385. var _this = _super.call(this, type, event) || this;
  1386. _this.pickInfo = pickInfo;
  1387. return _this;
  1388. }
  1389. return PointerInfo;
  1390. }(PointerInfoBase));
  1391. BABYLON.PointerInfo = PointerInfo;
  1392. })(BABYLON || (BABYLON = {}));
  1393. //# sourceMappingURL=babylon.pointerEvents.js.map
  1394. var BABYLON;
  1395. (function (BABYLON) {
  1396. BABYLON.ToGammaSpace = 1 / 2.2;
  1397. BABYLON.ToLinearSpace = 2.2;
  1398. BABYLON.Epsilon = 0.001;
  1399. /**
  1400. * Class used to hold a RBG color
  1401. */
  1402. var Color3 = /** @class */ (function () {
  1403. /**
  1404. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1405. * @param r defines the red component (between 0 and 1, default is 0)
  1406. * @param g defines the green component (between 0 and 1, default is 0)
  1407. * @param b defines the blue component (between 0 and 1, default is 0)
  1408. */
  1409. function Color3(
  1410. /**
  1411. * Defines the red component (between 0 and 1, default is 0)
  1412. */
  1413. r,
  1414. /**
  1415. * Defines the green component (between 0 and 1, default is 0)
  1416. */
  1417. g,
  1418. /**
  1419. * Defines the blue component (between 0 and 1, default is 0)
  1420. */
  1421. b) {
  1422. if (r === void 0) { r = 0; }
  1423. if (g === void 0) { g = 0; }
  1424. if (b === void 0) { b = 0; }
  1425. this.r = r;
  1426. this.g = g;
  1427. this.b = b;
  1428. }
  1429. /**
  1430. * Creates a string with the Color3 current values
  1431. * @returns the string representation of the Color3 object
  1432. */
  1433. Color3.prototype.toString = function () {
  1434. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1435. };
  1436. /**
  1437. * Returns the string "Color3"
  1438. * @returns "Color3"
  1439. */
  1440. Color3.prototype.getClassName = function () {
  1441. return "Color3";
  1442. };
  1443. /**
  1444. * Compute the Color3 hash code
  1445. * @returns an unique number that can be used to hash Color3 objects
  1446. */
  1447. Color3.prototype.getHashCode = function () {
  1448. var hash = this.r || 0;
  1449. hash = (hash * 397) ^ (this.g || 0);
  1450. hash = (hash * 397) ^ (this.b || 0);
  1451. return hash;
  1452. };
  1453. // Operators
  1454. /**
  1455. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1456. * @param array defines the array where to store the r,g,b components
  1457. * @param index defines an optional index in the target array to define where to start storing values
  1458. * @returns the current Color3 object
  1459. */
  1460. Color3.prototype.toArray = function (array, index) {
  1461. if (index === undefined) {
  1462. index = 0;
  1463. }
  1464. array[index] = this.r;
  1465. array[index + 1] = this.g;
  1466. array[index + 2] = this.b;
  1467. return this;
  1468. };
  1469. /**
  1470. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1471. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1472. * @returns a new {BABYLON.Color4} object
  1473. */
  1474. Color3.prototype.toColor4 = function (alpha) {
  1475. if (alpha === void 0) { alpha = 1; }
  1476. return new Color4(this.r, this.g, this.b, alpha);
  1477. };
  1478. /**
  1479. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1480. * @returns the new array
  1481. */
  1482. Color3.prototype.asArray = function () {
  1483. var result = new Array();
  1484. this.toArray(result, 0);
  1485. return result;
  1486. };
  1487. /**
  1488. * Returns the luminance value
  1489. * @returns a float value
  1490. */
  1491. Color3.prototype.toLuminance = function () {
  1492. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1493. };
  1494. /**
  1495. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1496. * @param otherColor defines the second operand
  1497. * @returns the new Color3 object
  1498. */
  1499. Color3.prototype.multiply = function (otherColor) {
  1500. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1501. };
  1502. /**
  1503. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1504. * @param otherColor defines the second operand
  1505. * @param result defines the Color3 object where to store the result
  1506. * @returns the current Color3
  1507. */
  1508. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1509. result.r = this.r * otherColor.r;
  1510. result.g = this.g * otherColor.g;
  1511. result.b = this.b * otherColor.b;
  1512. return this;
  1513. };
  1514. /**
  1515. * Determines equality between Color3 objects
  1516. * @param otherColor defines the second operand
  1517. * @returns true if the rgb values are equal to the given ones
  1518. */
  1519. Color3.prototype.equals = function (otherColor) {
  1520. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1521. };
  1522. /**
  1523. * Determines equality between the current Color3 object and a set of r,b,g values
  1524. * @param r defines the red component to check
  1525. * @param g defines the green component to check
  1526. * @param b defines the blue component to check
  1527. * @returns true if the rgb values are equal to the given ones
  1528. */
  1529. Color3.prototype.equalsFloats = function (r, g, b) {
  1530. return this.r === r && this.g === g && this.b === b;
  1531. };
  1532. /**
  1533. * Multiplies in place each rgb value by scale
  1534. * @param scale defines the scaling factor
  1535. * @returns the updated Color3
  1536. */
  1537. Color3.prototype.scale = function (scale) {
  1538. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1539. };
  1540. /**
  1541. * Multiplies the rgb values by scale and stores the result into "result"
  1542. * @param scale defines the scaling factor
  1543. * @param result defines the Color3 object where to store the result
  1544. * @returns the unmodified current Color3
  1545. */
  1546. Color3.prototype.scaleToRef = function (scale, result) {
  1547. result.r = this.r * scale;
  1548. result.g = this.g * scale;
  1549. result.b = this.b * scale;
  1550. return this;
  1551. };
  1552. /**
  1553. * Scale the current Color3 values by a factor and add the result to a given Color3
  1554. * @param scale defines the scale factor
  1555. * @param result defines color to store the result into
  1556. * @returns the unmodified current Color3
  1557. */
  1558. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1559. result.r += this.r * scale;
  1560. result.g += this.g * scale;
  1561. result.b += this.b * scale;
  1562. return this;
  1563. };
  1564. /**
  1565. * Clamps the rgb values by the min and max values and stores the result into "result"
  1566. * @param min defines minimum clamping value (default is 0)
  1567. * @param max defines maximum clamping value (default is 1)
  1568. * @param result defines color to store the result into
  1569. * @returns the original Color3
  1570. */
  1571. Color3.prototype.clampToRef = function (min, max, result) {
  1572. if (min === void 0) { min = 0; }
  1573. if (max === void 0) { max = 1; }
  1574. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1575. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1576. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1577. return this;
  1578. };
  1579. /**
  1580. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1581. * @param otherColor defines the second operand
  1582. * @returns the new Color3
  1583. */
  1584. Color3.prototype.add = function (otherColor) {
  1585. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1586. };
  1587. /**
  1588. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1589. * @param otherColor defines the second operand
  1590. * @param result defines Color3 object to store the result into
  1591. * @returns the unmodified current Color3
  1592. */
  1593. Color3.prototype.addToRef = function (otherColor, result) {
  1594. result.r = this.r + otherColor.r;
  1595. result.g = this.g + otherColor.g;
  1596. result.b = this.b + otherColor.b;
  1597. return this;
  1598. };
  1599. /**
  1600. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1601. * @param otherColor defines the second operand
  1602. * @returns the new Color3
  1603. */
  1604. Color3.prototype.subtract = function (otherColor) {
  1605. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1606. };
  1607. /**
  1608. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1609. * @param otherColor defines the second operand
  1610. * @param result defines Color3 object to store the result into
  1611. * @returns the unmodified current Color3
  1612. */
  1613. Color3.prototype.subtractToRef = function (otherColor, result) {
  1614. result.r = this.r - otherColor.r;
  1615. result.g = this.g - otherColor.g;
  1616. result.b = this.b - otherColor.b;
  1617. return this;
  1618. };
  1619. /**
  1620. * Copy the current object
  1621. * @returns a new Color3 copied the current one
  1622. */
  1623. Color3.prototype.clone = function () {
  1624. return new Color3(this.r, this.g, this.b);
  1625. };
  1626. /**
  1627. * Copies the rgb values from the source in the current Color3
  1628. * @param source defines the source Color3 object
  1629. * @returns the updated Color3 object
  1630. */
  1631. Color3.prototype.copyFrom = function (source) {
  1632. this.r = source.r;
  1633. this.g = source.g;
  1634. this.b = source.b;
  1635. return this;
  1636. };
  1637. /**
  1638. * Updates the Color3 rgb values from the given floats
  1639. * @param r defines the red component to read from
  1640. * @param g defines the green component to read from
  1641. * @param b defines the blue component to read from
  1642. * @returns the current Color3 object
  1643. */
  1644. Color3.prototype.copyFromFloats = function (r, g, b) {
  1645. this.r = r;
  1646. this.g = g;
  1647. this.b = b;
  1648. return this;
  1649. };
  1650. /**
  1651. * Updates the Color3 rgb values from the given floats
  1652. * @param r defines the red component to read from
  1653. * @param g defines the green component to read from
  1654. * @param b defines the blue component to read from
  1655. * @returns the current Color3 object
  1656. */
  1657. Color3.prototype.set = function (r, g, b) {
  1658. return this.copyFromFloats(r, g, b);
  1659. };
  1660. /**
  1661. * Compute the Color3 hexadecimal code as a string
  1662. * @returns a string containing the hexadecimal representation of the Color3 object
  1663. */
  1664. Color3.prototype.toHexString = function () {
  1665. var intR = (this.r * 255) | 0;
  1666. var intG = (this.g * 255) | 0;
  1667. var intB = (this.b * 255) | 0;
  1668. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1669. };
  1670. /**
  1671. * Computes a new Color3 converted from the current one to linear space
  1672. * @returns a new Color3 object
  1673. */
  1674. Color3.prototype.toLinearSpace = function () {
  1675. var convertedColor = new Color3();
  1676. this.toLinearSpaceToRef(convertedColor);
  1677. return convertedColor;
  1678. };
  1679. /**
  1680. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1681. * @param convertedColor defines the Color3 object where to store the linear space version
  1682. * @returns the unmodified Color3
  1683. */
  1684. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1685. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1686. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1687. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1688. return this;
  1689. };
  1690. /**
  1691. * Computes a new Color3 converted from the current one to gamma space
  1692. * @returns a new Color3 object
  1693. */
  1694. Color3.prototype.toGammaSpace = function () {
  1695. var convertedColor = new Color3();
  1696. this.toGammaSpaceToRef(convertedColor);
  1697. return convertedColor;
  1698. };
  1699. /**
  1700. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1701. * @param convertedColor defines the Color3 object where to store the gamma space version
  1702. * @returns the unmodified Color3
  1703. */
  1704. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1705. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1706. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1707. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1708. return this;
  1709. };
  1710. // Statics
  1711. /**
  1712. * Creates a new Color3 from the string containing valid hexadecimal values
  1713. * @param hex defines a string containing valid hexadecimal values
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromHexString = function (hex) {
  1717. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1718. return new Color3(0, 0, 0);
  1719. }
  1720. var r = parseInt(hex.substring(1, 3), 16);
  1721. var g = parseInt(hex.substring(3, 5), 16);
  1722. var b = parseInt(hex.substring(5, 7), 16);
  1723. return Color3.FromInts(r, g, b);
  1724. };
  1725. /**
  1726. * Creates a new Vector3 from the starting index of the given array
  1727. * @param array defines the source array
  1728. * @param offset defines an offset in the source array
  1729. * @returns a new Color3 object
  1730. */
  1731. Color3.FromArray = function (array, offset) {
  1732. if (offset === void 0) { offset = 0; }
  1733. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1734. };
  1735. /**
  1736. * Creates a new Color3 from integer values (< 256)
  1737. * @param r defines the red component to read from (value between 0 and 255)
  1738. * @param g defines the green component to read from (value between 0 and 255)
  1739. * @param b defines the blue component to read from (value between 0 and 255)
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.FromInts = function (r, g, b) {
  1743. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1744. };
  1745. /**
  1746. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1747. * @param start defines the start Color3 value
  1748. * @param end defines the end Color3 value
  1749. * @param amount defines the gradient value between start and end
  1750. * @returns a new Color3 object
  1751. */
  1752. Color3.Lerp = function (start, end, amount) {
  1753. var r = start.r + ((end.r - start.r) * amount);
  1754. var g = start.g + ((end.g - start.g) * amount);
  1755. var b = start.b + ((end.b - start.b) * amount);
  1756. return new Color3(r, g, b);
  1757. };
  1758. /**
  1759. * Returns a Color3 value containing a red color
  1760. * @returns a new Color3 object
  1761. */
  1762. Color3.Red = function () { return new Color3(1, 0, 0); };
  1763. /**
  1764. * Returns a Color3 value containing a green color
  1765. * @returns a new Color3 object
  1766. */
  1767. Color3.Green = function () { return new Color3(0, 1, 0); };
  1768. /**
  1769. * Returns a Color3 value containing a blue color
  1770. * @returns a new Color3 object
  1771. */
  1772. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1773. /**
  1774. * Returns a Color3 value containing a black color
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.Black = function () { return new Color3(0, 0, 0); };
  1778. /**
  1779. * Returns a Color3 value containing a white color
  1780. * @returns a new Color3 object
  1781. */
  1782. Color3.White = function () { return new Color3(1, 1, 1); };
  1783. /**
  1784. * Returns a Color3 value containing a purple color
  1785. * @returns a new Color3 object
  1786. */
  1787. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1788. /**
  1789. * Returns a Color3 value containing a magenta color
  1790. * @returns a new Color3 object
  1791. */
  1792. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1793. /**
  1794. * Returns a Color3 value containing a yellow color
  1795. * @returns a new Color3 object
  1796. */
  1797. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1798. /**
  1799. * Returns a Color3 value containing a gray color
  1800. * @returns a new Color3 object
  1801. */
  1802. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1803. /**
  1804. * Returns a Color3 value containing a teal color
  1805. * @returns a new Color3 object
  1806. */
  1807. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1808. /**
  1809. * Returns a Color3 value containing a random color
  1810. * @returns a new Color3 object
  1811. */
  1812. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1813. return Color3;
  1814. }());
  1815. BABYLON.Color3 = Color3;
  1816. /**
  1817. * Class used to hold a RBGA color
  1818. */
  1819. var Color4 = /** @class */ (function () {
  1820. /**
  1821. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1822. * @param r defines the red component (between 0 and 1, default is 0)
  1823. * @param g defines the green component (between 0 and 1, default is 0)
  1824. * @param b defines the blue component (between 0 and 1, default is 0)
  1825. * @param a defines the alpha component (between 0 and 1, default is 1)
  1826. */
  1827. function Color4(
  1828. /**
  1829. * Defines the red component (between 0 and 1, default is 0)
  1830. */
  1831. r,
  1832. /**
  1833. * Defines the green component (between 0 and 1, default is 0)
  1834. */
  1835. g,
  1836. /**
  1837. * Defines the blue component (between 0 and 1, default is 0)
  1838. */
  1839. b,
  1840. /**
  1841. * Defines the alpha component (between 0 and 1, default is 1)
  1842. */
  1843. a) {
  1844. if (r === void 0) { r = 0; }
  1845. if (g === void 0) { g = 0; }
  1846. if (b === void 0) { b = 0; }
  1847. if (a === void 0) { a = 1; }
  1848. this.r = r;
  1849. this.g = g;
  1850. this.b = b;
  1851. this.a = a;
  1852. }
  1853. // Operators
  1854. /**
  1855. * Adds in place the given Color4 values to the current Color4 object
  1856. * @param right defines the second operand
  1857. * @returns the current updated Color4 object
  1858. */
  1859. Color4.prototype.addInPlace = function (right) {
  1860. this.r += right.r;
  1861. this.g += right.g;
  1862. this.b += right.b;
  1863. this.a += right.a;
  1864. return this;
  1865. };
  1866. /**
  1867. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1868. * @returns the new array
  1869. */
  1870. Color4.prototype.asArray = function () {
  1871. var result = new Array();
  1872. this.toArray(result, 0);
  1873. return result;
  1874. };
  1875. /**
  1876. * Stores from the starting index in the given array the Color4 successive values
  1877. * @param array defines the array where to store the r,g,b components
  1878. * @param index defines an optional index in the target array to define where to start storing values
  1879. * @returns the current Color4 object
  1880. */
  1881. Color4.prototype.toArray = function (array, index) {
  1882. if (index === undefined) {
  1883. index = 0;
  1884. }
  1885. array[index] = this.r;
  1886. array[index + 1] = this.g;
  1887. array[index + 2] = this.b;
  1888. array[index + 3] = this.a;
  1889. return this;
  1890. };
  1891. /**
  1892. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1893. * @param right defines the second operand
  1894. * @returns a new Color4 object
  1895. */
  1896. Color4.prototype.add = function (right) {
  1897. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1898. };
  1899. /**
  1900. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1901. * @param right defines the second operand
  1902. * @returns a new Color4 object
  1903. */
  1904. Color4.prototype.subtract = function (right) {
  1905. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1906. };
  1907. /**
  1908. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1909. * @param right defines the second operand
  1910. * @param result defines the Color4 object where to store the result
  1911. * @returns the current Color4 object
  1912. */
  1913. Color4.prototype.subtractToRef = function (right, result) {
  1914. result.r = this.r - right.r;
  1915. result.g = this.g - right.g;
  1916. result.b = this.b - right.b;
  1917. result.a = this.a - right.a;
  1918. return this;
  1919. };
  1920. /**
  1921. * Creates a new Color4 with the current Color4 values multiplied by scale
  1922. * @param scale defines the scaling factor to apply
  1923. * @returns a new Color4 object
  1924. */
  1925. Color4.prototype.scale = function (scale) {
  1926. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1927. };
  1928. /**
  1929. * Multiplies the current Color4 values by scale and stores the result in "result"
  1930. * @param scale defines the scaling factor to apply
  1931. * @param result defines the Color4 object where to store the result
  1932. * @returns the current unmodified Color4
  1933. */
  1934. Color4.prototype.scaleToRef = function (scale, result) {
  1935. result.r = this.r * scale;
  1936. result.g = this.g * scale;
  1937. result.b = this.b * scale;
  1938. result.a = this.a * scale;
  1939. return this;
  1940. };
  1941. /**
  1942. * Scale the current Color4 values by a factor and add the result to a given Color4
  1943. * @param scale defines the scale factor
  1944. * @param result defines the Color4 object where to store the result
  1945. * @returns the unmodified current Color4
  1946. */
  1947. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1948. result.r += this.r * scale;
  1949. result.g += this.g * scale;
  1950. result.b += this.b * scale;
  1951. result.a += this.a * scale;
  1952. return this;
  1953. };
  1954. /**
  1955. * Clamps the rgb values by the min and max values and stores the result into "result"
  1956. * @param min defines minimum clamping value (default is 0)
  1957. * @param max defines maximum clamping value (default is 1)
  1958. * @param result defines color to store the result into.
  1959. * @returns the cuurent Color4
  1960. */
  1961. Color4.prototype.clampToRef = function (min, max, result) {
  1962. if (min === void 0) { min = 0; }
  1963. if (max === void 0) { max = 1; }
  1964. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1965. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1966. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1967. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1968. return this;
  1969. };
  1970. /**
  1971. * Multipy an Color4 value by another and return a new Color4 object
  1972. * @param color defines the Color4 value to multiply by
  1973. * @returns a new Color4 object
  1974. */
  1975. Color4.prototype.multiply = function (color) {
  1976. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1977. };
  1978. /**
  1979. * Multipy a Color4 value by another and push the result in a reference value
  1980. * @param color defines the Color4 value to multiply by
  1981. * @param result defines the Color4 to fill the result in
  1982. * @returns the result Color4
  1983. */
  1984. Color4.prototype.multiplyToRef = function (color, result) {
  1985. result.r = this.r * color.r;
  1986. result.g = this.g * color.g;
  1987. result.b = this.b * color.b;
  1988. result.a = this.a * color.a;
  1989. return result;
  1990. };
  1991. /**
  1992. * Creates a string with the Color4 current values
  1993. * @returns the string representation of the Color4 object
  1994. */
  1995. Color4.prototype.toString = function () {
  1996. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1997. };
  1998. /**
  1999. * Returns the string "Color4"
  2000. * @returns "Color4"
  2001. */
  2002. Color4.prototype.getClassName = function () {
  2003. return "Color4";
  2004. };
  2005. /**
  2006. * Compute the Color4 hash code
  2007. * @returns an unique number that can be used to hash Color4 objects
  2008. */
  2009. Color4.prototype.getHashCode = function () {
  2010. var hash = this.r || 0;
  2011. hash = (hash * 397) ^ (this.g || 0);
  2012. hash = (hash * 397) ^ (this.b || 0);
  2013. hash = (hash * 397) ^ (this.a || 0);
  2014. return hash;
  2015. };
  2016. /**
  2017. * Creates a new Color4 copied from the current one
  2018. * @returns a new Color4 object
  2019. */
  2020. Color4.prototype.clone = function () {
  2021. return new Color4(this.r, this.g, this.b, this.a);
  2022. };
  2023. /**
  2024. * Copies the given Color4 values into the current one
  2025. * @param source defines the source Color4 object
  2026. * @returns the current updated Color4 object
  2027. */
  2028. Color4.prototype.copyFrom = function (source) {
  2029. this.r = source.r;
  2030. this.g = source.g;
  2031. this.b = source.b;
  2032. this.a = source.a;
  2033. return this;
  2034. };
  2035. /**
  2036. * Copies the given float values into the current one
  2037. * @param r defines the red component to read from
  2038. * @param g defines the green component to read from
  2039. * @param b defines the blue component to read from
  2040. * @param a defines the alpha component to read from
  2041. * @returns the current updated Color4 object
  2042. */
  2043. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2044. this.r = r;
  2045. this.g = g;
  2046. this.b = b;
  2047. this.a = a;
  2048. return this;
  2049. };
  2050. /**
  2051. * Copies the given float values into the current one
  2052. * @param r defines the red component to read from
  2053. * @param g defines the green component to read from
  2054. * @param b defines the blue component to read from
  2055. * @param a defines the alpha component to read from
  2056. * @returns the current updated Color4 object
  2057. */
  2058. Color4.prototype.set = function (r, g, b, a) {
  2059. return this.copyFromFloats(r, g, b, a);
  2060. };
  2061. /**
  2062. * Compute the Color4 hexadecimal code as a string
  2063. * @returns a string containing the hexadecimal representation of the Color4 object
  2064. */
  2065. Color4.prototype.toHexString = function () {
  2066. var intR = (this.r * 255) | 0;
  2067. var intG = (this.g * 255) | 0;
  2068. var intB = (this.b * 255) | 0;
  2069. var intA = (this.a * 255) | 0;
  2070. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2071. };
  2072. /**
  2073. * Computes a new Color4 converted from the current one to linear space
  2074. * @returns a new Color4 object
  2075. */
  2076. Color4.prototype.toLinearSpace = function () {
  2077. var convertedColor = new Color4();
  2078. this.toLinearSpaceToRef(convertedColor);
  2079. return convertedColor;
  2080. };
  2081. /**
  2082. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2083. * @param convertedColor defines the Color4 object where to store the linear space version
  2084. * @returns the unmodified Color4
  2085. */
  2086. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2087. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2088. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2089. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2090. convertedColor.a = this.a;
  2091. return this;
  2092. };
  2093. /**
  2094. * Computes a new Color4 converted from the current one to gamma space
  2095. * @returns a new Color4 object
  2096. */
  2097. Color4.prototype.toGammaSpace = function () {
  2098. var convertedColor = new Color4();
  2099. this.toGammaSpaceToRef(convertedColor);
  2100. return convertedColor;
  2101. };
  2102. /**
  2103. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2104. * @param convertedColor defines the Color4 object where to store the gamma space version
  2105. * @returns the unmodified Color4
  2106. */
  2107. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2108. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2109. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2110. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2111. convertedColor.a = this.a;
  2112. return this;
  2113. };
  2114. // Statics
  2115. /**
  2116. * Creates a new Color4 from the string containing valid hexadecimal values
  2117. * @param hex defines a string containing valid hexadecimal values
  2118. * @returns a new Color4 object
  2119. */
  2120. Color4.FromHexString = function (hex) {
  2121. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2122. return new Color4(0.0, 0.0, 0.0, 0.0);
  2123. }
  2124. var r = parseInt(hex.substring(1, 3), 16);
  2125. var g = parseInt(hex.substring(3, 5), 16);
  2126. var b = parseInt(hex.substring(5, 7), 16);
  2127. var a = parseInt(hex.substring(7, 9), 16);
  2128. return Color4.FromInts(r, g, b, a);
  2129. };
  2130. /**
  2131. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2132. * @param left defines the start value
  2133. * @param right defines the end value
  2134. * @param amount defines the gradient factor
  2135. * @returns a new Color4 object
  2136. */
  2137. Color4.Lerp = function (left, right, amount) {
  2138. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2139. Color4.LerpToRef(left, right, amount, result);
  2140. return result;
  2141. };
  2142. /**
  2143. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2144. * @param left defines the start value
  2145. * @param right defines the end value
  2146. * @param amount defines the gradient factor
  2147. * @param result defines the Color4 object where to store data
  2148. */
  2149. Color4.LerpToRef = function (left, right, amount, result) {
  2150. result.r = left.r + (right.r - left.r) * amount;
  2151. result.g = left.g + (right.g - left.g) * amount;
  2152. result.b = left.b + (right.b - left.b) * amount;
  2153. result.a = left.a + (right.a - left.a) * amount;
  2154. };
  2155. /**
  2156. * Creates a new Color4 from the starting index element of the given array
  2157. * @param array defines the source array to read from
  2158. * @param offset defines the offset in the source array
  2159. * @returns a new Color4 object
  2160. */
  2161. Color4.FromArray = function (array, offset) {
  2162. if (offset === void 0) { offset = 0; }
  2163. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2164. };
  2165. /**
  2166. * Creates a new Color3 from integer values (< 256)
  2167. * @param r defines the red component to read from (value between 0 and 255)
  2168. * @param g defines the green component to read from (value between 0 and 255)
  2169. * @param b defines the blue component to read from (value between 0 and 255)
  2170. * @param a defines the alpha component to read from (value between 0 and 255)
  2171. * @returns a new Color3 object
  2172. */
  2173. Color4.FromInts = function (r, g, b, a) {
  2174. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2175. };
  2176. /**
  2177. * Check the content of a given array and convert it to an array containing RGBA data
  2178. * If the original array was already containing count * 4 values then it is returned directly
  2179. * @param colors defines the array to check
  2180. * @param count defines the number of RGBA data to expect
  2181. * @returns an array containing count * 4 values (RGBA)
  2182. */
  2183. Color4.CheckColors4 = function (colors, count) {
  2184. // Check if color3 was used
  2185. if (colors.length === count * 3) {
  2186. var colors4 = [];
  2187. for (var index = 0; index < colors.length; index += 3) {
  2188. var newIndex = (index / 3) * 4;
  2189. colors4[newIndex] = colors[index];
  2190. colors4[newIndex + 1] = colors[index + 1];
  2191. colors4[newIndex + 2] = colors[index + 2];
  2192. colors4[newIndex + 3] = 1.0;
  2193. }
  2194. return colors4;
  2195. }
  2196. return colors;
  2197. };
  2198. return Color4;
  2199. }());
  2200. BABYLON.Color4 = Color4;
  2201. /**
  2202. * Class representing a vector containing 2 coordinates
  2203. */
  2204. var Vector2 = /** @class */ (function () {
  2205. /**
  2206. * Creates a new Vector2 from the given x and y coordinates
  2207. * @param x defines the first coordinate
  2208. * @param y defines the second coordinate
  2209. */
  2210. function Vector2(
  2211. /** defines the first coordinate */
  2212. x,
  2213. /** defines the second coordinate */
  2214. y) {
  2215. if (x === void 0) { x = 0; }
  2216. if (y === void 0) { y = 0; }
  2217. this.x = x;
  2218. this.y = y;
  2219. }
  2220. /**
  2221. * Gets a string with the Vector2 coordinates
  2222. * @returns a string with the Vector2 coordinates
  2223. */
  2224. Vector2.prototype.toString = function () {
  2225. return "{X: " + this.x + " Y:" + this.y + "}";
  2226. };
  2227. /**
  2228. * Gets class name
  2229. * @returns the string "Vector2"
  2230. */
  2231. Vector2.prototype.getClassName = function () {
  2232. return "Vector2";
  2233. };
  2234. /**
  2235. * Gets current vector hash code
  2236. * @returns the Vector2 hash code as a number
  2237. */
  2238. Vector2.prototype.getHashCode = function () {
  2239. var hash = this.x || 0;
  2240. hash = (hash * 397) ^ (this.y || 0);
  2241. return hash;
  2242. };
  2243. // Operators
  2244. /**
  2245. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2246. * @param array defines the source array
  2247. * @param index defines the offset in source array
  2248. * @returns the current Vector2
  2249. */
  2250. Vector2.prototype.toArray = function (array, index) {
  2251. if (index === void 0) { index = 0; }
  2252. array[index] = this.x;
  2253. array[index + 1] = this.y;
  2254. return this;
  2255. };
  2256. /**
  2257. * Copy the current vector to an array
  2258. * @returns a new array with 2 elements: the Vector2 coordinates.
  2259. */
  2260. Vector2.prototype.asArray = function () {
  2261. var result = new Array();
  2262. this.toArray(result, 0);
  2263. return result;
  2264. };
  2265. /**
  2266. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2267. * @param source defines the source Vector2
  2268. * @returns the current updated Vector2
  2269. */
  2270. Vector2.prototype.copyFrom = function (source) {
  2271. this.x = source.x;
  2272. this.y = source.y;
  2273. return this;
  2274. };
  2275. /**
  2276. * Sets the Vector2 coordinates with the given floats
  2277. * @param x defines the first coordinate
  2278. * @param y defines the second coordinate
  2279. * @returns the current updated Vector2
  2280. */
  2281. Vector2.prototype.copyFromFloats = function (x, y) {
  2282. this.x = x;
  2283. this.y = y;
  2284. return this;
  2285. };
  2286. /**
  2287. * Sets the Vector2 coordinates with the given floats
  2288. * @param x defines the first coordinate
  2289. * @param y defines the second coordinate
  2290. * @returns the current updated Vector2
  2291. */
  2292. Vector2.prototype.set = function (x, y) {
  2293. return this.copyFromFloats(x, y);
  2294. };
  2295. /**
  2296. * Add another vector with the current one
  2297. * @param otherVector defines the other vector
  2298. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2299. */
  2300. Vector2.prototype.add = function (otherVector) {
  2301. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2302. };
  2303. /**
  2304. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2305. * @param otherVector defines the other vector
  2306. * @param result defines the target vector
  2307. * @returns the unmodified current Vector2
  2308. */
  2309. Vector2.prototype.addToRef = function (otherVector, result) {
  2310. result.x = this.x + otherVector.x;
  2311. result.y = this.y + otherVector.y;
  2312. return this;
  2313. };
  2314. /**
  2315. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2316. * @param otherVector defines the other vector
  2317. * @returns the current updated Vector2
  2318. */
  2319. Vector2.prototype.addInPlace = function (otherVector) {
  2320. this.x += otherVector.x;
  2321. this.y += otherVector.y;
  2322. return this;
  2323. };
  2324. /**
  2325. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2326. * @param otherVector defines the other vector
  2327. * @returns a new Vector2
  2328. */
  2329. Vector2.prototype.addVector3 = function (otherVector) {
  2330. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2331. };
  2332. /**
  2333. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2334. * @param otherVector defines the other vector
  2335. * @returns a new Vector2
  2336. */
  2337. Vector2.prototype.subtract = function (otherVector) {
  2338. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2339. };
  2340. /**
  2341. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2342. * @param otherVector defines the other vector
  2343. * @param result defines the target vector
  2344. * @returns the unmodified current Vector2
  2345. */
  2346. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2347. result.x = this.x - otherVector.x;
  2348. result.y = this.y - otherVector.y;
  2349. return this;
  2350. };
  2351. /**
  2352. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2353. * @param otherVector defines the other vector
  2354. * @returns the current updated Vector2
  2355. */
  2356. Vector2.prototype.subtractInPlace = function (otherVector) {
  2357. this.x -= otherVector.x;
  2358. this.y -= otherVector.y;
  2359. return this;
  2360. };
  2361. /**
  2362. * Multiplies in place the current Vector2 coordinates by the given ones
  2363. * @param otherVector defines the other vector
  2364. * @returns the current updated Vector2
  2365. */
  2366. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2367. this.x *= otherVector.x;
  2368. this.y *= otherVector.y;
  2369. return this;
  2370. };
  2371. /**
  2372. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2373. * @param otherVector defines the other vector
  2374. * @returns a new Vector2
  2375. */
  2376. Vector2.prototype.multiply = function (otherVector) {
  2377. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2378. };
  2379. /**
  2380. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2381. * @param otherVector defines the other vector
  2382. * @param result defines the target vector
  2383. * @returns the unmodified current Vector2
  2384. */
  2385. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2386. result.x = this.x * otherVector.x;
  2387. result.y = this.y * otherVector.y;
  2388. return this;
  2389. };
  2390. /**
  2391. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2392. * @param x defines the first coordinate
  2393. * @param y defines the second coordinate
  2394. * @returns a new Vector2
  2395. */
  2396. Vector2.prototype.multiplyByFloats = function (x, y) {
  2397. return new Vector2(this.x * x, this.y * y);
  2398. };
  2399. /**
  2400. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2401. * @param otherVector defines the other vector
  2402. * @returns a new Vector2
  2403. */
  2404. Vector2.prototype.divide = function (otherVector) {
  2405. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2406. };
  2407. /**
  2408. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2409. * @param otherVector defines the other vector
  2410. * @param result defines the target vector
  2411. * @returns the unmodified current Vector2
  2412. */
  2413. Vector2.prototype.divideToRef = function (otherVector, result) {
  2414. result.x = this.x / otherVector.x;
  2415. result.y = this.y / otherVector.y;
  2416. return this;
  2417. };
  2418. /**
  2419. * Divides the current Vector2 coordinates by the given ones
  2420. * @param otherVector defines the other vector
  2421. * @returns the current updated Vector2
  2422. */
  2423. Vector2.prototype.divideInPlace = function (otherVector) {
  2424. return this.divideToRef(otherVector, this);
  2425. };
  2426. /**
  2427. * Gets a new Vector2 with current Vector2 negated coordinates
  2428. * @returns a new Vector2
  2429. */
  2430. Vector2.prototype.negate = function () {
  2431. return new Vector2(-this.x, -this.y);
  2432. };
  2433. /**
  2434. * Multiply the Vector2 coordinates by scale
  2435. * @param scale defines the scaling factor
  2436. * @returns the current updated Vector2
  2437. */
  2438. Vector2.prototype.scaleInPlace = function (scale) {
  2439. this.x *= scale;
  2440. this.y *= scale;
  2441. return this;
  2442. };
  2443. /**
  2444. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2445. * @param scale defines the scaling factor
  2446. * @returns a new Vector2
  2447. */
  2448. Vector2.prototype.scale = function (scale) {
  2449. var result = new Vector2(0, 0);
  2450. this.scaleToRef(scale, result);
  2451. return result;
  2452. };
  2453. /**
  2454. * Scale the current Vector2 values by a factor to a given Vector2
  2455. * @param scale defines the scale factor
  2456. * @param result defines the Vector2 object where to store the result
  2457. * @returns the unmodified current Vector2
  2458. */
  2459. Vector2.prototype.scaleToRef = function (scale, result) {
  2460. result.x = this.x * scale;
  2461. result.y = this.y * scale;
  2462. return this;
  2463. };
  2464. /**
  2465. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2466. * @param scale defines the scale factor
  2467. * @param result defines the Vector2 object where to store the result
  2468. * @returns the unmodified current Vector2
  2469. */
  2470. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2471. result.x += this.x * scale;
  2472. result.y += this.y * scale;
  2473. return this;
  2474. };
  2475. /**
  2476. * Gets a boolean if two vectors are equals
  2477. * @param otherVector defines the other vector
  2478. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2479. */
  2480. Vector2.prototype.equals = function (otherVector) {
  2481. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2482. };
  2483. /**
  2484. * Gets a boolean if two vectors are equals (using an epsilon value)
  2485. * @param otherVector defines the other vector
  2486. * @param epsilon defines the minimal distance to consider equality
  2487. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2488. */
  2489. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2490. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2491. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2492. };
  2493. /**
  2494. * Gets a new Vector2 from current Vector2 floored values
  2495. * @returns a new Vector2
  2496. */
  2497. Vector2.prototype.floor = function () {
  2498. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2499. };
  2500. /**
  2501. * Gets a new Vector2 from current Vector2 floored values
  2502. * @returns a new Vector2
  2503. */
  2504. Vector2.prototype.fract = function () {
  2505. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2506. };
  2507. // Properties
  2508. /**
  2509. * Gets the length of the vector
  2510. * @returns the vector length (float)
  2511. */
  2512. Vector2.prototype.length = function () {
  2513. return Math.sqrt(this.x * this.x + this.y * this.y);
  2514. };
  2515. /**
  2516. * Gets the vector squared length
  2517. * @returns the vector squared length (float)
  2518. */
  2519. Vector2.prototype.lengthSquared = function () {
  2520. return (this.x * this.x + this.y * this.y);
  2521. };
  2522. // Methods
  2523. /**
  2524. * Normalize the vector
  2525. * @returns the current updated Vector2
  2526. */
  2527. Vector2.prototype.normalize = function () {
  2528. var len = this.length();
  2529. if (len === 0)
  2530. return this;
  2531. var num = 1.0 / len;
  2532. this.x *= num;
  2533. this.y *= num;
  2534. return this;
  2535. };
  2536. /**
  2537. * Gets a new Vector2 copied from the Vector2
  2538. * @returns a new Vector2
  2539. */
  2540. Vector2.prototype.clone = function () {
  2541. return new Vector2(this.x, this.y);
  2542. };
  2543. // Statics
  2544. /**
  2545. * Gets a new Vector2(0, 0)
  2546. * @returns a new Vector2
  2547. */
  2548. Vector2.Zero = function () {
  2549. return new Vector2(0, 0);
  2550. };
  2551. /**
  2552. * Gets a new Vector2(1, 1)
  2553. * @returns a new Vector2
  2554. */
  2555. Vector2.One = function () {
  2556. return new Vector2(1, 1);
  2557. };
  2558. /**
  2559. * Gets a new Vector2 set from the given index element of the given array
  2560. * @param array defines the data source
  2561. * @param offset defines the offset in the data source
  2562. * @returns a new Vector2
  2563. */
  2564. Vector2.FromArray = function (array, offset) {
  2565. if (offset === void 0) { offset = 0; }
  2566. return new Vector2(array[offset], array[offset + 1]);
  2567. };
  2568. /**
  2569. * Sets "result" from the given index element of the given array
  2570. * @param array defines the data source
  2571. * @param offset defines the offset in the data source
  2572. * @param result defines the target vector
  2573. */
  2574. Vector2.FromArrayToRef = function (array, offset, result) {
  2575. result.x = array[offset];
  2576. result.y = array[offset + 1];
  2577. };
  2578. /**
  2579. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2580. * @param value1 defines 1st point of control
  2581. * @param value2 defines 2nd point of control
  2582. * @param value3 defines 3rd point of control
  2583. * @param value4 defines 4th point of control
  2584. * @param amount defines the interpolation factor
  2585. * @returns a new Vector2
  2586. */
  2587. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2588. var squared = amount * amount;
  2589. var cubed = amount * squared;
  2590. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2591. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2592. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2593. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2594. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2595. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2596. return new Vector2(x, y);
  2597. };
  2598. /**
  2599. * 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".
  2600. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2601. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2602. * @param value defines the value to clamp
  2603. * @param min defines the lower limit
  2604. * @param max defines the upper limit
  2605. * @returns a new Vector2
  2606. */
  2607. Vector2.Clamp = function (value, min, max) {
  2608. var x = value.x;
  2609. x = (x > max.x) ? max.x : x;
  2610. x = (x < min.x) ? min.x : x;
  2611. var y = value.y;
  2612. y = (y > max.y) ? max.y : y;
  2613. y = (y < min.y) ? min.y : y;
  2614. return new Vector2(x, y);
  2615. };
  2616. /**
  2617. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2618. * @param value1 defines the 1st control point
  2619. * @param tangent1 defines the outgoing tangent
  2620. * @param value2 defines the 2nd control point
  2621. * @param tangent2 defines the incoming tangent
  2622. * @param amount defines the interpolation factor
  2623. * @returns a new Vector2
  2624. */
  2625. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2626. var squared = amount * amount;
  2627. var cubed = amount * squared;
  2628. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2629. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2630. var part3 = (cubed - (2.0 * squared)) + amount;
  2631. var part4 = cubed - squared;
  2632. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2633. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2634. return new Vector2(x, y);
  2635. };
  2636. /**
  2637. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2638. * @param start defines the start vector
  2639. * @param end defines the end vector
  2640. * @param amount defines the interpolation factor
  2641. * @returns a new Vector2
  2642. */
  2643. Vector2.Lerp = function (start, end, amount) {
  2644. var x = start.x + ((end.x - start.x) * amount);
  2645. var y = start.y + ((end.y - start.y) * amount);
  2646. return new Vector2(x, y);
  2647. };
  2648. /**
  2649. * Gets the dot product of the vector "left" and the vector "right"
  2650. * @param left defines first vector
  2651. * @param right defines second vector
  2652. * @returns the dot product (float)
  2653. */
  2654. Vector2.Dot = function (left, right) {
  2655. return left.x * right.x + left.y * right.y;
  2656. };
  2657. /**
  2658. * Returns a new Vector2 equal to the normalized given vector
  2659. * @param vector defines the vector to normalize
  2660. * @returns a new Vector2
  2661. */
  2662. Vector2.Normalize = function (vector) {
  2663. var newVector = vector.clone();
  2664. newVector.normalize();
  2665. return newVector;
  2666. };
  2667. /**
  2668. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2669. * @param left defines 1st vector
  2670. * @param right defines 2nd vector
  2671. * @returns a new Vector2
  2672. */
  2673. Vector2.Minimize = function (left, right) {
  2674. var x = (left.x < right.x) ? left.x : right.x;
  2675. var y = (left.y < right.y) ? left.y : right.y;
  2676. return new Vector2(x, y);
  2677. };
  2678. /**
  2679. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2680. * @param left defines 1st vector
  2681. * @param right defines 2nd vector
  2682. * @returns a new Vector2
  2683. */
  2684. Vector2.Maximize = function (left, right) {
  2685. var x = (left.x > right.x) ? left.x : right.x;
  2686. var y = (left.y > right.y) ? left.y : right.y;
  2687. return new Vector2(x, y);
  2688. };
  2689. /**
  2690. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2691. * @param vector defines the vector to transform
  2692. * @param transformation defines the matrix to apply
  2693. * @returns a new Vector2
  2694. */
  2695. Vector2.Transform = function (vector, transformation) {
  2696. var r = Vector2.Zero();
  2697. Vector2.TransformToRef(vector, transformation, r);
  2698. return r;
  2699. };
  2700. /**
  2701. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2702. * @param vector defines the vector to transform
  2703. * @param transformation defines the matrix to apply
  2704. * @param result defines the target vector
  2705. */
  2706. Vector2.TransformToRef = function (vector, transformation, result) {
  2707. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2708. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2709. result.x = x;
  2710. result.y = y;
  2711. };
  2712. /**
  2713. * Determines if a given vector is included in a triangle
  2714. * @param p defines the vector to test
  2715. * @param p0 defines 1st triangle point
  2716. * @param p1 defines 2nd triangle point
  2717. * @param p2 defines 3rd triangle point
  2718. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2719. */
  2720. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2721. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2722. var sign = a < 0 ? -1 : 1;
  2723. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2724. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2725. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2726. };
  2727. /**
  2728. * Gets the distance between the vectors "value1" and "value2"
  2729. * @param value1 defines first vector
  2730. * @param value2 defines second vector
  2731. * @returns the distance between vectors
  2732. */
  2733. Vector2.Distance = function (value1, value2) {
  2734. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2735. };
  2736. /**
  2737. * Returns the squared distance between the vectors "value1" and "value2"
  2738. * @param value1 defines first vector
  2739. * @param value2 defines second vector
  2740. * @returns the squared distance between vectors
  2741. */
  2742. Vector2.DistanceSquared = function (value1, value2) {
  2743. var x = value1.x - value2.x;
  2744. var y = value1.y - value2.y;
  2745. return (x * x) + (y * y);
  2746. };
  2747. /**
  2748. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2749. * @param value1 defines first vector
  2750. * @param value2 defines second vector
  2751. * @returns a new Vector2
  2752. */
  2753. Vector2.Center = function (value1, value2) {
  2754. var center = value1.add(value2);
  2755. center.scaleInPlace(0.5);
  2756. return center;
  2757. };
  2758. /**
  2759. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2760. * @param p defines the middle point
  2761. * @param segA defines one point of the segment
  2762. * @param segB defines the other point of the segment
  2763. * @returns the shortest distance
  2764. */
  2765. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2766. var l2 = Vector2.DistanceSquared(segA, segB);
  2767. if (l2 === 0.0) {
  2768. return Vector2.Distance(p, segA);
  2769. }
  2770. var v = segB.subtract(segA);
  2771. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2772. var proj = segA.add(v.multiplyByFloats(t, t));
  2773. return Vector2.Distance(p, proj);
  2774. };
  2775. return Vector2;
  2776. }());
  2777. BABYLON.Vector2 = Vector2;
  2778. /**
  2779. * Classed used to store (x,y,z) vector representation
  2780. * A Vector3 is the main object used in 3D geometry
  2781. * It can represent etiher the coordinates of a point the space, either a direction
  2782. * Reminder: Babylon.js uses a left handed forward facing system
  2783. */
  2784. var Vector3 = /** @class */ (function () {
  2785. /**
  2786. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2787. * @param x defines the first coordinates (on X axis)
  2788. * @param y defines the second coordinates (on Y axis)
  2789. * @param z defines the third coordinates (on Z axis)
  2790. */
  2791. function Vector3(
  2792. /**
  2793. * Defines the first coordinates (on X axis)
  2794. */
  2795. x,
  2796. /**
  2797. * Defines the second coordinates (on Y axis)
  2798. */
  2799. y,
  2800. /**
  2801. * Defines the third coordinates (on Z axis)
  2802. */
  2803. z) {
  2804. if (x === void 0) { x = 0; }
  2805. if (y === void 0) { y = 0; }
  2806. if (z === void 0) { z = 0; }
  2807. this.x = x;
  2808. this.y = y;
  2809. this.z = z;
  2810. }
  2811. /**
  2812. * Creates a string representation of the Vector3
  2813. * @returns a string with the Vector3 coordinates.
  2814. */
  2815. Vector3.prototype.toString = function () {
  2816. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2817. };
  2818. /**
  2819. * Gets the class name
  2820. * @returns the string "Vector3"
  2821. */
  2822. Vector3.prototype.getClassName = function () {
  2823. return "Vector3";
  2824. };
  2825. /**
  2826. * Creates the Vector3 hash code
  2827. * @returns a number which tends to be unique between Vector3 instances
  2828. */
  2829. Vector3.prototype.getHashCode = function () {
  2830. var hash = this.x || 0;
  2831. hash = (hash * 397) ^ (this.y || 0);
  2832. hash = (hash * 397) ^ (this.z || 0);
  2833. return hash;
  2834. };
  2835. // Operators
  2836. /**
  2837. * Creates an array containing three elements : the coordinates of the Vector3
  2838. * @returns a new array of numbers
  2839. */
  2840. Vector3.prototype.asArray = function () {
  2841. var result = [];
  2842. this.toArray(result, 0);
  2843. return result;
  2844. };
  2845. /**
  2846. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2847. * @param array defines the destination array
  2848. * @param index defines the offset in the destination array
  2849. * @returns the current Vector3
  2850. */
  2851. Vector3.prototype.toArray = function (array, index) {
  2852. if (index === void 0) { index = 0; }
  2853. array[index] = this.x;
  2854. array[index + 1] = this.y;
  2855. array[index + 2] = this.z;
  2856. return this;
  2857. };
  2858. /**
  2859. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2860. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2861. */
  2862. Vector3.prototype.toQuaternion = function () {
  2863. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2864. };
  2865. /**
  2866. * Adds the given vector to the current Vector3
  2867. * @param otherVector defines the second operand
  2868. * @returns the current updated Vector3
  2869. */
  2870. Vector3.prototype.addInPlace = function (otherVector) {
  2871. this.x += otherVector.x;
  2872. this.y += otherVector.y;
  2873. this.z += otherVector.z;
  2874. return this;
  2875. };
  2876. /**
  2877. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2878. * @param otherVector defines the second operand
  2879. * @returns the resulting Vector3
  2880. */
  2881. Vector3.prototype.add = function (otherVector) {
  2882. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2883. };
  2884. /**
  2885. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2886. * @param otherVector defines the second operand
  2887. * @param result defines the Vector3 object where to store the result
  2888. * @returns the current Vector3
  2889. */
  2890. Vector3.prototype.addToRef = function (otherVector, result) {
  2891. result.x = this.x + otherVector.x;
  2892. result.y = this.y + otherVector.y;
  2893. result.z = this.z + otherVector.z;
  2894. return this;
  2895. };
  2896. /**
  2897. * Subtract the given vector from the current Vector3
  2898. * @param otherVector defines the second operand
  2899. * @returns the current updated Vector3
  2900. */
  2901. Vector3.prototype.subtractInPlace = function (otherVector) {
  2902. this.x -= otherVector.x;
  2903. this.y -= otherVector.y;
  2904. this.z -= otherVector.z;
  2905. return this;
  2906. };
  2907. /**
  2908. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2909. * @param otherVector defines the second operand
  2910. * @returns the resulting Vector3
  2911. */
  2912. Vector3.prototype.subtract = function (otherVector) {
  2913. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2914. };
  2915. /**
  2916. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2917. * @param otherVector defines the second operand
  2918. * @param result defines the Vector3 object where to store the result
  2919. * @returns the current Vector3
  2920. */
  2921. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2922. result.x = this.x - otherVector.x;
  2923. result.y = this.y - otherVector.y;
  2924. result.z = this.z - otherVector.z;
  2925. return this;
  2926. };
  2927. /**
  2928. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2929. * @param x defines the x coordinate of the operand
  2930. * @param y defines the y coordinate of the operand
  2931. * @param z defines the z coordinate of the operand
  2932. * @returns the resulting Vector3
  2933. */
  2934. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2935. return new Vector3(this.x - x, this.y - y, this.z - z);
  2936. };
  2937. /**
  2938. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2939. * @param x defines the x coordinate of the operand
  2940. * @param y defines the y coordinate of the operand
  2941. * @param z defines the z coordinate of the operand
  2942. * @param result defines the Vector3 object where to store the result
  2943. * @returns the current Vector3
  2944. */
  2945. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2946. result.x = this.x - x;
  2947. result.y = this.y - y;
  2948. result.z = this.z - z;
  2949. return this;
  2950. };
  2951. /**
  2952. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2953. * @returns a new Vector3
  2954. */
  2955. Vector3.prototype.negate = function () {
  2956. return new Vector3(-this.x, -this.y, -this.z);
  2957. };
  2958. /**
  2959. * Multiplies the Vector3 coordinates by the float "scale"
  2960. * @param scale defines the multiplier factor
  2961. * @returns the current updated Vector3
  2962. */
  2963. Vector3.prototype.scaleInPlace = function (scale) {
  2964. this.x *= scale;
  2965. this.y *= scale;
  2966. this.z *= scale;
  2967. return this;
  2968. };
  2969. /**
  2970. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2971. * @param scale defines the multiplier factor
  2972. * @returns a new Vector3
  2973. */
  2974. Vector3.prototype.scale = function (scale) {
  2975. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2976. };
  2977. /**
  2978. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2979. * @param scale defines the multiplier factor
  2980. * @param result defines the Vector3 object where to store the result
  2981. * @returns the current Vector3
  2982. */
  2983. Vector3.prototype.scaleToRef = function (scale, result) {
  2984. result.x = this.x * scale;
  2985. result.y = this.y * scale;
  2986. result.z = this.z * scale;
  2987. return this;
  2988. };
  2989. /**
  2990. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2991. * @param scale defines the scale factor
  2992. * @param result defines the Vector3 object where to store the result
  2993. * @returns the unmodified current Vector3
  2994. */
  2995. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2996. result.x += this.x * scale;
  2997. result.y += this.y * scale;
  2998. result.z += this.z * scale;
  2999. return this;
  3000. };
  3001. /**
  3002. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3003. * @param otherVector defines the second operand
  3004. * @returns true if both vectors are equals
  3005. */
  3006. Vector3.prototype.equals = function (otherVector) {
  3007. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3008. };
  3009. /**
  3010. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3011. * @param otherVector defines the second operand
  3012. * @param epsilon defines the minimal distance to define values as equals
  3013. * @returns true if both vectors are distant less than epsilon
  3014. */
  3015. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3016. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3017. 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);
  3018. };
  3019. /**
  3020. * Returns true if the current Vector3 coordinates equals the given floats
  3021. * @param x defines the x coordinate of the operand
  3022. * @param y defines the y coordinate of the operand
  3023. * @param z defines the z coordinate of the operand
  3024. * @returns true if both vectors are equals
  3025. */
  3026. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3027. return this.x === x && this.y === y && this.z === z;
  3028. };
  3029. /**
  3030. * Multiplies the current Vector3 coordinates by the given ones
  3031. * @param otherVector defines the second operand
  3032. * @returns the current updated Vector3
  3033. */
  3034. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3035. this.x *= otherVector.x;
  3036. this.y *= otherVector.y;
  3037. this.z *= otherVector.z;
  3038. return this;
  3039. };
  3040. /**
  3041. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3042. * @param otherVector defines the second operand
  3043. * @returns the new Vector3
  3044. */
  3045. Vector3.prototype.multiply = function (otherVector) {
  3046. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3047. };
  3048. /**
  3049. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3050. * @param otherVector defines the second operand
  3051. * @param result defines the Vector3 object where to store the result
  3052. * @returns the current Vector3
  3053. */
  3054. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3055. result.x = this.x * otherVector.x;
  3056. result.y = this.y * otherVector.y;
  3057. result.z = this.z * otherVector.z;
  3058. return this;
  3059. };
  3060. /**
  3061. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3062. * @param x defines the x coordinate of the operand
  3063. * @param y defines the y coordinate of the operand
  3064. * @param z defines the z coordinate of the operand
  3065. * @returns the new Vector3
  3066. */
  3067. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3068. return new Vector3(this.x * x, this.y * y, this.z * z);
  3069. };
  3070. /**
  3071. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3072. * @param otherVector defines the second operand
  3073. * @returns the new Vector3
  3074. */
  3075. Vector3.prototype.divide = function (otherVector) {
  3076. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3077. };
  3078. /**
  3079. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3080. * @param otherVector defines the second operand
  3081. * @param result defines the Vector3 object where to store the result
  3082. * @returns the current Vector3
  3083. */
  3084. Vector3.prototype.divideToRef = function (otherVector, result) {
  3085. result.x = this.x / otherVector.x;
  3086. result.y = this.y / otherVector.y;
  3087. result.z = this.z / otherVector.z;
  3088. return this;
  3089. };
  3090. /**
  3091. * Divides the current Vector3 coordinates by the given ones.
  3092. * @param otherVector defines the second operand
  3093. * @returns the current updated Vector3
  3094. */
  3095. Vector3.prototype.divideInPlace = function (otherVector) {
  3096. return this.divideToRef(otherVector, this);
  3097. };
  3098. /**
  3099. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3100. * @param other defines the second operand
  3101. * @returns the current updated Vector3
  3102. */
  3103. Vector3.prototype.minimizeInPlace = function (other) {
  3104. if (other.x < this.x)
  3105. this.x = other.x;
  3106. if (other.y < this.y)
  3107. this.y = other.y;
  3108. if (other.z < this.z)
  3109. this.z = other.z;
  3110. return this;
  3111. };
  3112. /**
  3113. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3114. * @param other defines the second operand
  3115. * @returns the current updated Vector3
  3116. */
  3117. Vector3.prototype.maximizeInPlace = function (other) {
  3118. if (other.x > this.x)
  3119. this.x = other.x;
  3120. if (other.y > this.y)
  3121. this.y = other.y;
  3122. if (other.z > this.z)
  3123. this.z = other.z;
  3124. return this;
  3125. };
  3126. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3127. /**
  3128. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3129. */
  3130. get: function () {
  3131. var absX = Math.abs(this.x);
  3132. var absY = Math.abs(this.y);
  3133. if (absX !== absY) {
  3134. return true;
  3135. }
  3136. var absZ = Math.abs(this.z);
  3137. if (absX !== absZ) {
  3138. return true;
  3139. }
  3140. if (absY !== absZ) {
  3141. return true;
  3142. }
  3143. return false;
  3144. },
  3145. enumerable: true,
  3146. configurable: true
  3147. });
  3148. /**
  3149. * Gets a new Vector3 from current Vector3 floored values
  3150. * @returns a new Vector3
  3151. */
  3152. Vector3.prototype.floor = function () {
  3153. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3154. };
  3155. /**
  3156. * Gets a new Vector3 from current Vector3 floored values
  3157. * @returns a new Vector3
  3158. */
  3159. Vector3.prototype.fract = function () {
  3160. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3161. };
  3162. // Properties
  3163. /**
  3164. * Gets the length of the Vector3
  3165. * @returns the length of the Vecto3
  3166. */
  3167. Vector3.prototype.length = function () {
  3168. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3169. };
  3170. /**
  3171. * Gets the squared length of the Vector3
  3172. * @returns squared length of the Vector3
  3173. */
  3174. Vector3.prototype.lengthSquared = function () {
  3175. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3176. };
  3177. /**
  3178. * Normalize the current Vector3.
  3179. * Please note that this is an in place operation.
  3180. * @returns the current updated Vector3
  3181. */
  3182. Vector3.prototype.normalize = function () {
  3183. var len = this.length();
  3184. if (len === 0 || len === 1.0)
  3185. return this;
  3186. var num = 1.0 / len;
  3187. this.x *= num;
  3188. this.y *= num;
  3189. this.z *= num;
  3190. return this;
  3191. };
  3192. /**
  3193. * Normalize the current Vector3 to a new vector
  3194. * @returns the new Vector3
  3195. */
  3196. Vector3.prototype.normalizeToNew = function () {
  3197. var normalized = new Vector3(0, 0, 0);
  3198. this.normalizeToRef(normalized);
  3199. return normalized;
  3200. };
  3201. /**
  3202. * Normalize the current Vector3 to the reference
  3203. * @param reference define the Vector3 to update
  3204. * @returns the updated Vector3
  3205. */
  3206. Vector3.prototype.normalizeToRef = function (reference) {
  3207. var len = this.length();
  3208. if (len === 0 || len === 1.0) {
  3209. reference.set(this.x, this.y, this.z);
  3210. return reference;
  3211. }
  3212. var scale = 1.0 / len;
  3213. this.scaleToRef(scale, reference);
  3214. return reference;
  3215. };
  3216. /**
  3217. * Creates a new Vector3 copied from the current Vector3
  3218. * @returns the new Vector3
  3219. */
  3220. Vector3.prototype.clone = function () {
  3221. return new Vector3(this.x, this.y, this.z);
  3222. };
  3223. /**
  3224. * Copies the given vector coordinates to the current Vector3 ones
  3225. * @param source defines the source Vector3
  3226. * @returns the current updated Vector3
  3227. */
  3228. Vector3.prototype.copyFrom = function (source) {
  3229. this.x = source.x;
  3230. this.y = source.y;
  3231. this.z = source.z;
  3232. return this;
  3233. };
  3234. /**
  3235. * Copies the given floats to the current Vector3 coordinates
  3236. * @param x defines the x coordinate of the operand
  3237. * @param y defines the y coordinate of the operand
  3238. * @param z defines the z coordinate of the operand
  3239. * @returns the current updated Vector3
  3240. */
  3241. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3242. this.x = x;
  3243. this.y = y;
  3244. this.z = z;
  3245. return this;
  3246. };
  3247. /**
  3248. * Copies the given floats to the current Vector3 coordinates
  3249. * @param x defines the x coordinate of the operand
  3250. * @param y defines the y coordinate of the operand
  3251. * @param z defines the z coordinate of the operand
  3252. * @returns the current updated Vector3
  3253. */
  3254. Vector3.prototype.set = function (x, y, z) {
  3255. return this.copyFromFloats(x, y, z);
  3256. };
  3257. // Statics
  3258. /**
  3259. * Get the clip factor between two vectors
  3260. * @param vector0 defines the first operand
  3261. * @param vector1 defines the second operand
  3262. * @param axis defines the axis to use
  3263. * @param size defines the size along the axis
  3264. * @returns the clip factor
  3265. */
  3266. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3267. var d0 = Vector3.Dot(vector0, axis) - size;
  3268. var d1 = Vector3.Dot(vector1, axis) - size;
  3269. var s = d0 / (d0 - d1);
  3270. return s;
  3271. };
  3272. /**
  3273. * Get angle between two vectors
  3274. * @param vector0 angle between vector0 and vector1
  3275. * @param vector1 angle between vector0 and vector1
  3276. * @param normal direction of the normal
  3277. * @return the angle between vector0 and vector1
  3278. */
  3279. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3280. var v0 = vector0.clone().normalize();
  3281. var v1 = vector1.clone().normalize();
  3282. var dot = Vector3.Dot(v0, v1);
  3283. var n = Vector3.Cross(v0, v1);
  3284. if (Vector3.Dot(n, normal) > 0) {
  3285. return Math.acos(dot);
  3286. }
  3287. return -Math.acos(dot);
  3288. };
  3289. /**
  3290. * Returns a new Vector3 set from the index "offset" of the given array
  3291. * @param array defines the source array
  3292. * @param offset defines the offset in the source array
  3293. * @returns the new Vector3
  3294. */
  3295. Vector3.FromArray = function (array, offset) {
  3296. if (!offset) {
  3297. offset = 0;
  3298. }
  3299. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3300. };
  3301. /**
  3302. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3303. * This function is deprecated. Use FromArray instead
  3304. * @param array defines the source array
  3305. * @param offset defines the offset in the source array
  3306. * @returns the new Vector3
  3307. */
  3308. Vector3.FromFloatArray = function (array, offset) {
  3309. return Vector3.FromArray(array, offset);
  3310. };
  3311. /**
  3312. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3313. * @param array defines the source array
  3314. * @param offset defines the offset in the source array
  3315. * @param result defines the Vector3 where to store the result
  3316. */
  3317. Vector3.FromArrayToRef = function (array, offset, result) {
  3318. result.x = array[offset];
  3319. result.y = array[offset + 1];
  3320. result.z = array[offset + 2];
  3321. };
  3322. /**
  3323. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3324. * This function is deprecated. Use FromArrayToRef instead.
  3325. * @param array defines the source array
  3326. * @param offset defines the offset in the source array
  3327. * @param result defines the Vector3 where to store the result
  3328. */
  3329. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3330. return Vector3.FromArrayToRef(array, offset, result);
  3331. };
  3332. /**
  3333. * Sets the given vector "result" with the given floats.
  3334. * @param x defines the x coordinate of the source
  3335. * @param y defines the y coordinate of the source
  3336. * @param z defines the z coordinate of the source
  3337. * @param result defines the Vector3 where to store the result
  3338. */
  3339. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3340. result.x = x;
  3341. result.y = y;
  3342. result.z = z;
  3343. };
  3344. /**
  3345. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3346. * @returns a new empty Vector3
  3347. */
  3348. Vector3.Zero = function () {
  3349. return new Vector3(0.0, 0.0, 0.0);
  3350. };
  3351. /**
  3352. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3353. * @returns a new unit Vector3
  3354. */
  3355. Vector3.One = function () {
  3356. return new Vector3(1.0, 1.0, 1.0);
  3357. };
  3358. /**
  3359. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3360. * @returns a new up Vector3
  3361. */
  3362. Vector3.Up = function () {
  3363. return new Vector3(0.0, 1.0, 0.0);
  3364. };
  3365. /**
  3366. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3367. * @returns a new down Vector3
  3368. */
  3369. Vector3.Down = function () {
  3370. return new Vector3(0.0, -1.0, 0.0);
  3371. };
  3372. /**
  3373. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3374. * @returns a new forward Vector3
  3375. */
  3376. Vector3.Forward = function () {
  3377. return new Vector3(0.0, 0.0, 1.0);
  3378. };
  3379. /**
  3380. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3381. * @returns a new right Vector3
  3382. */
  3383. Vector3.Right = function () {
  3384. return new Vector3(1.0, 0.0, 0.0);
  3385. };
  3386. /**
  3387. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3388. * @returns a new left Vector3
  3389. */
  3390. Vector3.Left = function () {
  3391. return new Vector3(-1.0, 0.0, 0.0);
  3392. };
  3393. /**
  3394. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3395. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3396. * @param vector defines the Vector3 to transform
  3397. * @param transformation defines the transformation matrix
  3398. * @returns the transformed Vector3
  3399. */
  3400. Vector3.TransformCoordinates = function (vector, transformation) {
  3401. var result = Vector3.Zero();
  3402. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3403. return result;
  3404. };
  3405. /**
  3406. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3407. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3408. * @param vector defines the Vector3 to transform
  3409. * @param transformation defines the transformation matrix
  3410. * @param result defines the Vector3 where to store the result
  3411. */
  3412. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3413. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3414. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3415. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3416. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3417. result.x = x / w;
  3418. result.y = y / w;
  3419. result.z = z / w;
  3420. };
  3421. /**
  3422. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3423. * This method computes tranformed coordinates only, not transformed direction vectors
  3424. * @param x define the x coordinate of the source vector
  3425. * @param y define the y coordinate of the source vector
  3426. * @param z define the z coordinate of the source vector
  3427. * @param transformation defines the transformation matrix
  3428. * @param result defines the Vector3 where to store the result
  3429. */
  3430. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3431. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3432. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3433. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3434. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3435. result.x = rx / rw;
  3436. result.y = ry / rw;
  3437. result.z = rz / rw;
  3438. };
  3439. /**
  3440. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3441. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3442. * @param vector defines the Vector3 to transform
  3443. * @param transformation defines the transformation matrix
  3444. * @returns the new Vector3
  3445. */
  3446. Vector3.TransformNormal = function (vector, transformation) {
  3447. var result = Vector3.Zero();
  3448. Vector3.TransformNormalToRef(vector, transformation, result);
  3449. return result;
  3450. };
  3451. /**
  3452. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3453. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3454. * @param vector defines the Vector3 to transform
  3455. * @param transformation defines the transformation matrix
  3456. * @param result defines the Vector3 where to store the result
  3457. */
  3458. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3459. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3460. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3461. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3462. result.x = x;
  3463. result.y = y;
  3464. result.z = z;
  3465. };
  3466. /**
  3467. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3468. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3469. * @param x define the x coordinate of the source vector
  3470. * @param y define the y coordinate of the source vector
  3471. * @param z define the z coordinate of the source vector
  3472. * @param transformation defines the transformation matrix
  3473. * @param result defines the Vector3 where to store the result
  3474. */
  3475. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3476. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3477. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3478. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3479. };
  3480. /**
  3481. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3482. * @param value1 defines the first control point
  3483. * @param value2 defines the second control point
  3484. * @param value3 defines the third control point
  3485. * @param value4 defines the fourth control point
  3486. * @param amount defines the amount on the spline to use
  3487. * @returns the new Vector3
  3488. */
  3489. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3490. var squared = amount * amount;
  3491. var cubed = amount * squared;
  3492. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3493. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3494. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3495. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3496. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3497. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3498. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3499. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3500. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3501. return new Vector3(x, y, z);
  3502. };
  3503. /**
  3504. * 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"
  3505. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3506. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3507. * @param value defines the current value
  3508. * @param min defines the lower range value
  3509. * @param max defines the upper range value
  3510. * @returns the new Vector3
  3511. */
  3512. Vector3.Clamp = function (value, min, max) {
  3513. var x = value.x;
  3514. x = (x > max.x) ? max.x : x;
  3515. x = (x < min.x) ? min.x : x;
  3516. var y = value.y;
  3517. y = (y > max.y) ? max.y : y;
  3518. y = (y < min.y) ? min.y : y;
  3519. var z = value.z;
  3520. z = (z > max.z) ? max.z : z;
  3521. z = (z < min.z) ? min.z : z;
  3522. return new Vector3(x, y, z);
  3523. };
  3524. /**
  3525. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3526. * @param value1 defines the first control point
  3527. * @param tangent1 defines the first tangent vector
  3528. * @param value2 defines the second control point
  3529. * @param tangent2 defines the second tangent vector
  3530. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3531. * @returns the new Vector3
  3532. */
  3533. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3534. var squared = amount * amount;
  3535. var cubed = amount * squared;
  3536. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3537. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3538. var part3 = (cubed - (2.0 * squared)) + amount;
  3539. var part4 = cubed - squared;
  3540. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3541. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3542. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3543. return new Vector3(x, y, z);
  3544. };
  3545. /**
  3546. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3547. * @param start defines the start value
  3548. * @param end defines the end value
  3549. * @param amount max defines amount between both (between 0 and 1)
  3550. * @returns the new Vector3
  3551. */
  3552. Vector3.Lerp = function (start, end, amount) {
  3553. var result = new Vector3(0, 0, 0);
  3554. Vector3.LerpToRef(start, end, amount, result);
  3555. return result;
  3556. };
  3557. /**
  3558. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3559. * @param start defines the start value
  3560. * @param end defines the end value
  3561. * @param amount max defines amount between both (between 0 and 1)
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.LerpToRef = function (start, end, amount, result) {
  3565. result.x = start.x + ((end.x - start.x) * amount);
  3566. result.y = start.y + ((end.y - start.y) * amount);
  3567. result.z = start.z + ((end.z - start.z) * amount);
  3568. };
  3569. /**
  3570. * Returns the dot product (float) between the vectors "left" and "right"
  3571. * @param left defines the left operand
  3572. * @param right defines the right operand
  3573. * @returns the dot product
  3574. */
  3575. Vector3.Dot = function (left, right) {
  3576. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3577. };
  3578. /**
  3579. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3580. * The cross product is then orthogonal to both "left" and "right"
  3581. * @param left defines the left operand
  3582. * @param right defines the right operand
  3583. * @returns the cross product
  3584. */
  3585. Vector3.Cross = function (left, right) {
  3586. var result = Vector3.Zero();
  3587. Vector3.CrossToRef(left, right, result);
  3588. return result;
  3589. };
  3590. /**
  3591. * Sets the given vector "result" with the cross product of "left" and "right"
  3592. * The cross product is then orthogonal to both "left" and "right"
  3593. * @param left defines the left operand
  3594. * @param right defines the right operand
  3595. * @param result defines the Vector3 where to store the result
  3596. */
  3597. Vector3.CrossToRef = function (left, right, result) {
  3598. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3599. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3600. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3601. result.copyFrom(MathTmp.Vector3[0]);
  3602. };
  3603. /**
  3604. * Returns a new Vector3 as the normalization of the given vector
  3605. * @param vector defines the Vector3 to normalize
  3606. * @returns the new Vector3
  3607. */
  3608. Vector3.Normalize = function (vector) {
  3609. var result = Vector3.Zero();
  3610. Vector3.NormalizeToRef(vector, result);
  3611. return result;
  3612. };
  3613. /**
  3614. * Sets the given vector "result" with the normalization of the given first vector
  3615. * @param vector defines the Vector3 to normalize
  3616. * @param result defines the Vector3 where to store the result
  3617. */
  3618. Vector3.NormalizeToRef = function (vector, result) {
  3619. result.copyFrom(vector);
  3620. result.normalize();
  3621. };
  3622. /**
  3623. * Project a Vector3 onto screen space
  3624. * @param vector defines the Vector3 to project
  3625. * @param world defines the world matrix to use
  3626. * @param transform defines the transform (view x projection) matrix to use
  3627. * @param viewport defines the screen viewport to use
  3628. * @returns the new Vector3
  3629. */
  3630. Vector3.Project = function (vector, world, transform, viewport) {
  3631. var cw = viewport.width;
  3632. var ch = viewport.height;
  3633. var cx = viewport.x;
  3634. var cy = viewport.y;
  3635. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3636. 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);
  3637. var matrix = MathTmp.Matrix[0];
  3638. world.multiplyToRef(transform, matrix);
  3639. matrix.multiplyToRef(viewportMatrix, matrix);
  3640. return Vector3.TransformCoordinates(vector, matrix);
  3641. };
  3642. /**
  3643. * Unproject from screen space to object space
  3644. * @param source defines the screen space Vector3 to use
  3645. * @param viewportWidth defines the current width of the viewport
  3646. * @param viewportHeight defines the current height of the viewport
  3647. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3648. * @param transform defines the transform (view x projection) matrix to use
  3649. * @returns the new Vector3
  3650. */
  3651. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3652. var matrix = MathTmp.Matrix[0];
  3653. world.multiplyToRef(transform, matrix);
  3654. matrix.invert();
  3655. source.x = source.x / viewportWidth * 2 - 1;
  3656. source.y = -(source.y / viewportHeight * 2 - 1);
  3657. var vector = Vector3.TransformCoordinates(source, matrix);
  3658. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3659. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3660. vector = vector.scale(1.0 / num);
  3661. }
  3662. return vector;
  3663. };
  3664. /**
  3665. * Unproject from screen space to object space
  3666. * @param source defines the screen space Vector3 to use
  3667. * @param viewportWidth defines the current width of the viewport
  3668. * @param viewportHeight defines the current height of the viewport
  3669. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3670. * @param view defines the view matrix to use
  3671. * @param projection defines the projection matrix to use
  3672. * @returns the new Vector3
  3673. */
  3674. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3675. var result = Vector3.Zero();
  3676. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3677. return result;
  3678. };
  3679. /**
  3680. * Unproject from screen space to object space
  3681. * @param source defines the screen space Vector3 to use
  3682. * @param viewportWidth defines the current width of the viewport
  3683. * @param viewportHeight defines the current height of the viewport
  3684. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3685. * @param view defines the view matrix to use
  3686. * @param projection defines the projection matrix to use
  3687. * @param result defines the Vector3 where to store the result
  3688. */
  3689. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3690. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3691. };
  3692. /**
  3693. * Unproject from screen space to object space
  3694. * @param sourceX defines the screen space x coordinate to use
  3695. * @param sourceY defines the screen space y coordinate to use
  3696. * @param sourceZ defines the screen space z coordinate to use
  3697. * @param viewportWidth defines the current width of the viewport
  3698. * @param viewportHeight defines the current height of the viewport
  3699. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3700. * @param view defines the view matrix to use
  3701. * @param projection defines the projection matrix to use
  3702. * @param result defines the Vector3 where to store the result
  3703. */
  3704. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3705. var matrix = MathTmp.Matrix[0];
  3706. world.multiplyToRef(view, matrix);
  3707. matrix.multiplyToRef(projection, matrix);
  3708. matrix.invert();
  3709. var screenSource = MathTmp.Vector3[0];
  3710. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3711. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3712. screenSource.z = 2 * sourceZ - 1.0;
  3713. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3714. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3715. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3716. result.scaleInPlace(1.0 / num);
  3717. }
  3718. };
  3719. /**
  3720. * Gets the minimal coordinate values between two Vector3
  3721. * @param left defines the first operand
  3722. * @param right defines the second operand
  3723. * @returns the new Vector3
  3724. */
  3725. Vector3.Minimize = function (left, right) {
  3726. var min = left.clone();
  3727. min.minimizeInPlace(right);
  3728. return min;
  3729. };
  3730. /**
  3731. * Gets the maximal coordinate values between two Vector3
  3732. * @param left defines the first operand
  3733. * @param right defines the second operand
  3734. * @returns the new Vector3
  3735. */
  3736. Vector3.Maximize = function (left, right) {
  3737. var max = left.clone();
  3738. max.maximizeInPlace(right);
  3739. return max;
  3740. };
  3741. /**
  3742. * Returns the distance between the vectors "value1" and "value2"
  3743. * @param value1 defines the first operand
  3744. * @param value2 defines the second operand
  3745. * @returns the distance
  3746. */
  3747. Vector3.Distance = function (value1, value2) {
  3748. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3749. };
  3750. /**
  3751. * Returns the squared distance between the vectors "value1" and "value2"
  3752. * @param value1 defines the first operand
  3753. * @param value2 defines the second operand
  3754. * @returns the squared distance
  3755. */
  3756. Vector3.DistanceSquared = function (value1, value2) {
  3757. var x = value1.x - value2.x;
  3758. var y = value1.y - value2.y;
  3759. var z = value1.z - value2.z;
  3760. return (x * x) + (y * y) + (z * z);
  3761. };
  3762. /**
  3763. * Returns a new Vector3 located at the center between "value1" and "value2"
  3764. * @param value1 defines the first operand
  3765. * @param value2 defines the second operand
  3766. * @returns the new Vector3
  3767. */
  3768. Vector3.Center = function (value1, value2) {
  3769. var center = value1.add(value2);
  3770. center.scaleInPlace(0.5);
  3771. return center;
  3772. };
  3773. /**
  3774. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3775. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3776. * to something in order to rotate it from its local system to the given target system
  3777. * Note: axis1, axis2 and axis3 are normalized during this operation
  3778. * @param axis1 defines the first axis
  3779. * @param axis2 defines the second axis
  3780. * @param axis3 defines the third axis
  3781. * @returns a new Vector3
  3782. */
  3783. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3784. var rotation = Vector3.Zero();
  3785. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3786. return rotation;
  3787. };
  3788. /**
  3789. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3790. * @param axis1 defines the first axis
  3791. * @param axis2 defines the second axis
  3792. * @param axis3 defines the third axis
  3793. * @param ref defines the Vector3 where to store the result
  3794. */
  3795. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3796. var quat = MathTmp.Quaternion[0];
  3797. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3798. quat.toEulerAnglesToRef(ref);
  3799. };
  3800. return Vector3;
  3801. }());
  3802. BABYLON.Vector3 = Vector3;
  3803. //Vector4 class created for EulerAngle class conversion to Quaternion
  3804. var Vector4 = /** @class */ (function () {
  3805. /**
  3806. * Creates a Vector4 object from the given floats.
  3807. */
  3808. function Vector4(x, y, z, w) {
  3809. this.x = x;
  3810. this.y = y;
  3811. this.z = z;
  3812. this.w = w;
  3813. }
  3814. /**
  3815. * Returns the string with the Vector4 coordinates.
  3816. */
  3817. Vector4.prototype.toString = function () {
  3818. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3819. };
  3820. /**
  3821. * Returns the string "Vector4".
  3822. */
  3823. Vector4.prototype.getClassName = function () {
  3824. return "Vector4";
  3825. };
  3826. /**
  3827. * Returns the Vector4 hash code.
  3828. */
  3829. Vector4.prototype.getHashCode = function () {
  3830. var hash = this.x || 0;
  3831. hash = (hash * 397) ^ (this.y || 0);
  3832. hash = (hash * 397) ^ (this.z || 0);
  3833. hash = (hash * 397) ^ (this.w || 0);
  3834. return hash;
  3835. };
  3836. // Operators
  3837. /**
  3838. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3839. */
  3840. Vector4.prototype.asArray = function () {
  3841. var result = new Array();
  3842. this.toArray(result, 0);
  3843. return result;
  3844. };
  3845. /**
  3846. * Populates the given array from the given index with the Vector4 coordinates.
  3847. * Returns the Vector4.
  3848. */
  3849. Vector4.prototype.toArray = function (array, index) {
  3850. if (index === undefined) {
  3851. index = 0;
  3852. }
  3853. array[index] = this.x;
  3854. array[index + 1] = this.y;
  3855. array[index + 2] = this.z;
  3856. array[index + 3] = this.w;
  3857. return this;
  3858. };
  3859. /**
  3860. * Adds the given vector to the current Vector4.
  3861. * Returns the updated Vector4.
  3862. */
  3863. Vector4.prototype.addInPlace = function (otherVector) {
  3864. this.x += otherVector.x;
  3865. this.y += otherVector.y;
  3866. this.z += otherVector.z;
  3867. this.w += otherVector.w;
  3868. return this;
  3869. };
  3870. /**
  3871. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3872. */
  3873. Vector4.prototype.add = function (otherVector) {
  3874. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3875. };
  3876. /**
  3877. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3878. * Returns the current Vector4.
  3879. */
  3880. Vector4.prototype.addToRef = function (otherVector, result) {
  3881. result.x = this.x + otherVector.x;
  3882. result.y = this.y + otherVector.y;
  3883. result.z = this.z + otherVector.z;
  3884. result.w = this.w + otherVector.w;
  3885. return this;
  3886. };
  3887. /**
  3888. * Subtract in place the given vector from the current Vector4.
  3889. * Returns the updated Vector4.
  3890. */
  3891. Vector4.prototype.subtractInPlace = function (otherVector) {
  3892. this.x -= otherVector.x;
  3893. this.y -= otherVector.y;
  3894. this.z -= otherVector.z;
  3895. this.w -= otherVector.w;
  3896. return this;
  3897. };
  3898. /**
  3899. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3900. */
  3901. Vector4.prototype.subtract = function (otherVector) {
  3902. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3903. };
  3904. /**
  3905. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3906. * Returns the current Vector4.
  3907. */
  3908. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3909. result.x = this.x - otherVector.x;
  3910. result.y = this.y - otherVector.y;
  3911. result.z = this.z - otherVector.z;
  3912. result.w = this.w - otherVector.w;
  3913. return this;
  3914. };
  3915. /**
  3916. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3917. */
  3918. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3919. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3920. };
  3921. /**
  3922. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3923. * Returns the current Vector4.
  3924. */
  3925. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3926. result.x = this.x - x;
  3927. result.y = this.y - y;
  3928. result.z = this.z - z;
  3929. result.w = this.w - w;
  3930. return this;
  3931. };
  3932. /**
  3933. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3934. */
  3935. Vector4.prototype.negate = function () {
  3936. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3937. };
  3938. /**
  3939. * Multiplies the current Vector4 coordinates by scale (float).
  3940. * Returns the updated Vector4.
  3941. */
  3942. Vector4.prototype.scaleInPlace = function (scale) {
  3943. this.x *= scale;
  3944. this.y *= scale;
  3945. this.z *= scale;
  3946. this.w *= scale;
  3947. return this;
  3948. };
  3949. /**
  3950. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3951. */
  3952. Vector4.prototype.scale = function (scale) {
  3953. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3954. };
  3955. /**
  3956. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3957. * Returns the current Vector4.
  3958. */
  3959. Vector4.prototype.scaleToRef = function (scale, result) {
  3960. result.x = this.x * scale;
  3961. result.y = this.y * scale;
  3962. result.z = this.z * scale;
  3963. result.w = this.w * scale;
  3964. return this;
  3965. };
  3966. /**
  3967. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3968. * @param scale defines the scale factor
  3969. * @param result defines the Vector4 object where to store the result
  3970. * @returns the unmodified current Vector4
  3971. */
  3972. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3973. result.x += this.x * scale;
  3974. result.y += this.y * scale;
  3975. result.z += this.z * scale;
  3976. result.w += this.w * scale;
  3977. return this;
  3978. };
  3979. /**
  3980. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3981. */
  3982. Vector4.prototype.equals = function (otherVector) {
  3983. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3984. };
  3985. /**
  3986. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3987. */
  3988. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3989. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3990. return otherVector
  3991. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3992. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3993. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3994. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3995. };
  3996. /**
  3997. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3998. */
  3999. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4000. return this.x === x && this.y === y && this.z === z && this.w === w;
  4001. };
  4002. /**
  4003. * Multiplies in place the current Vector4 by the given one.
  4004. * Returns the updated Vector4.
  4005. */
  4006. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4007. this.x *= otherVector.x;
  4008. this.y *= otherVector.y;
  4009. this.z *= otherVector.z;
  4010. this.w *= otherVector.w;
  4011. return this;
  4012. };
  4013. /**
  4014. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4015. */
  4016. Vector4.prototype.multiply = function (otherVector) {
  4017. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4018. };
  4019. /**
  4020. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4021. * Returns the current Vector4.
  4022. */
  4023. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4024. result.x = this.x * otherVector.x;
  4025. result.y = this.y * otherVector.y;
  4026. result.z = this.z * otherVector.z;
  4027. result.w = this.w * otherVector.w;
  4028. return this;
  4029. };
  4030. /**
  4031. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4032. */
  4033. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4034. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4035. };
  4036. /**
  4037. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4038. */
  4039. Vector4.prototype.divide = function (otherVector) {
  4040. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4041. };
  4042. /**
  4043. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4044. * Returns the current Vector4.
  4045. */
  4046. Vector4.prototype.divideToRef = function (otherVector, result) {
  4047. result.x = this.x / otherVector.x;
  4048. result.y = this.y / otherVector.y;
  4049. result.z = this.z / otherVector.z;
  4050. result.w = this.w / otherVector.w;
  4051. return this;
  4052. };
  4053. /**
  4054. * Divides the current Vector3 coordinates by the given ones.
  4055. * @returns the updated Vector3.
  4056. */
  4057. Vector4.prototype.divideInPlace = function (otherVector) {
  4058. return this.divideToRef(otherVector, this);
  4059. };
  4060. /**
  4061. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4062. * @param other defines the second operand
  4063. * @returns the current updated Vector4
  4064. */
  4065. Vector4.prototype.minimizeInPlace = function (other) {
  4066. if (other.x < this.x)
  4067. this.x = other.x;
  4068. if (other.y < this.y)
  4069. this.y = other.y;
  4070. if (other.z < this.z)
  4071. this.z = other.z;
  4072. if (other.w < this.w)
  4073. this.w = other.w;
  4074. return this;
  4075. };
  4076. /**
  4077. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4078. * @param other defines the second operand
  4079. * @returns the current updated Vector4
  4080. */
  4081. Vector4.prototype.maximizeInPlace = function (other) {
  4082. if (other.x > this.x)
  4083. this.x = other.x;
  4084. if (other.y > this.y)
  4085. this.y = other.y;
  4086. if (other.z > this.z)
  4087. this.z = other.z;
  4088. if (other.w > this.w)
  4089. this.w = other.w;
  4090. return this;
  4091. };
  4092. /**
  4093. * Gets a new Vector4 from current Vector4 floored values
  4094. * @returns a new Vector4
  4095. */
  4096. Vector4.prototype.floor = function () {
  4097. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4098. };
  4099. /**
  4100. * Gets a new Vector4 from current Vector3 floored values
  4101. * @returns a new Vector4
  4102. */
  4103. Vector4.prototype.fract = function () {
  4104. 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));
  4105. };
  4106. // Properties
  4107. /**
  4108. * Returns the Vector4 length (float).
  4109. */
  4110. Vector4.prototype.length = function () {
  4111. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4112. };
  4113. /**
  4114. * Returns the Vector4 squared length (float).
  4115. */
  4116. Vector4.prototype.lengthSquared = function () {
  4117. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4118. };
  4119. // Methods
  4120. /**
  4121. * Normalizes in place the Vector4.
  4122. * Returns the updated Vector4.
  4123. */
  4124. Vector4.prototype.normalize = function () {
  4125. var len = this.length();
  4126. if (len === 0)
  4127. return this;
  4128. var num = 1.0 / len;
  4129. this.x *= num;
  4130. this.y *= num;
  4131. this.z *= num;
  4132. this.w *= num;
  4133. return this;
  4134. };
  4135. /**
  4136. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4137. */
  4138. Vector4.prototype.toVector3 = function () {
  4139. return new Vector3(this.x, this.y, this.z);
  4140. };
  4141. /**
  4142. * Returns a new Vector4 copied from the current one.
  4143. */
  4144. Vector4.prototype.clone = function () {
  4145. return new Vector4(this.x, this.y, this.z, this.w);
  4146. };
  4147. /**
  4148. * Updates the current Vector4 with the given one coordinates.
  4149. * Returns the updated Vector4.
  4150. */
  4151. Vector4.prototype.copyFrom = function (source) {
  4152. this.x = source.x;
  4153. this.y = source.y;
  4154. this.z = source.z;
  4155. this.w = source.w;
  4156. return this;
  4157. };
  4158. /**
  4159. * Updates the current Vector4 coordinates with the given floats.
  4160. * Returns the updated Vector4.
  4161. */
  4162. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4163. this.x = x;
  4164. this.y = y;
  4165. this.z = z;
  4166. this.w = w;
  4167. return this;
  4168. };
  4169. /**
  4170. * Updates the current Vector4 coordinates with the given floats.
  4171. * Returns the updated Vector4.
  4172. */
  4173. Vector4.prototype.set = function (x, y, z, w) {
  4174. return this.copyFromFloats(x, y, z, w);
  4175. };
  4176. // Statics
  4177. /**
  4178. * Returns a new Vector4 set from the starting index of the given array.
  4179. */
  4180. Vector4.FromArray = function (array, offset) {
  4181. if (!offset) {
  4182. offset = 0;
  4183. }
  4184. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4185. };
  4186. /**
  4187. * Updates the given vector "result" from the starting index of the given array.
  4188. */
  4189. Vector4.FromArrayToRef = function (array, offset, result) {
  4190. result.x = array[offset];
  4191. result.y = array[offset + 1];
  4192. result.z = array[offset + 2];
  4193. result.w = array[offset + 3];
  4194. };
  4195. /**
  4196. * Updates the given vector "result" from the starting index of the given Float32Array.
  4197. */
  4198. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4199. Vector4.FromArrayToRef(array, offset, result);
  4200. };
  4201. /**
  4202. * Updates the given vector "result" coordinates from the given floats.
  4203. */
  4204. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4205. result.x = x;
  4206. result.y = y;
  4207. result.z = z;
  4208. result.w = w;
  4209. };
  4210. /**
  4211. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4212. */
  4213. Vector4.Zero = function () {
  4214. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4215. };
  4216. /**
  4217. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4218. */
  4219. Vector4.One = function () {
  4220. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4221. };
  4222. /**
  4223. * Returns a new normalized Vector4 from the given one.
  4224. */
  4225. Vector4.Normalize = function (vector) {
  4226. var result = Vector4.Zero();
  4227. Vector4.NormalizeToRef(vector, result);
  4228. return result;
  4229. };
  4230. /**
  4231. * Updates the given vector "result" from the normalization of the given one.
  4232. */
  4233. Vector4.NormalizeToRef = function (vector, result) {
  4234. result.copyFrom(vector);
  4235. result.normalize();
  4236. };
  4237. Vector4.Minimize = function (left, right) {
  4238. var min = left.clone();
  4239. min.minimizeInPlace(right);
  4240. return min;
  4241. };
  4242. Vector4.Maximize = function (left, right) {
  4243. var max = left.clone();
  4244. max.maximizeInPlace(right);
  4245. return max;
  4246. };
  4247. /**
  4248. * Returns the distance (float) between the vectors "value1" and "value2".
  4249. */
  4250. Vector4.Distance = function (value1, value2) {
  4251. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4252. };
  4253. /**
  4254. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4255. */
  4256. Vector4.DistanceSquared = function (value1, value2) {
  4257. var x = value1.x - value2.x;
  4258. var y = value1.y - value2.y;
  4259. var z = value1.z - value2.z;
  4260. var w = value1.w - value2.w;
  4261. return (x * x) + (y * y) + (z * z) + (w * w);
  4262. };
  4263. /**
  4264. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4265. */
  4266. Vector4.Center = function (value1, value2) {
  4267. var center = value1.add(value2);
  4268. center.scaleInPlace(0.5);
  4269. return center;
  4270. };
  4271. /**
  4272. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4273. * This methods computes transformed normalized direction vectors only.
  4274. */
  4275. Vector4.TransformNormal = function (vector, transformation) {
  4276. var result = Vector4.Zero();
  4277. Vector4.TransformNormalToRef(vector, transformation, result);
  4278. return result;
  4279. };
  4280. /**
  4281. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4282. * This methods computes transformed normalized direction vectors only.
  4283. */
  4284. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4285. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4286. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4287. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4288. result.x = x;
  4289. result.y = y;
  4290. result.z = z;
  4291. result.w = vector.w;
  4292. };
  4293. /**
  4294. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4295. * This methods computes transformed normalized direction vectors only.
  4296. */
  4297. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4298. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4299. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4300. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4301. result.w = w;
  4302. };
  4303. return Vector4;
  4304. }());
  4305. BABYLON.Vector4 = Vector4;
  4306. var Size = /** @class */ (function () {
  4307. /**
  4308. * Creates a Size object from the given width and height (floats).
  4309. */
  4310. function Size(width, height) {
  4311. this.width = width;
  4312. this.height = height;
  4313. }
  4314. // Returns a string with the Size width and height.
  4315. Size.prototype.toString = function () {
  4316. return "{W: " + this.width + ", H: " + this.height + "}";
  4317. };
  4318. /**
  4319. * Returns the string "Size"
  4320. */
  4321. Size.prototype.getClassName = function () {
  4322. return "Size";
  4323. };
  4324. /**
  4325. * Returns the Size hash code.
  4326. */
  4327. Size.prototype.getHashCode = function () {
  4328. var hash = this.width || 0;
  4329. hash = (hash * 397) ^ (this.height || 0);
  4330. return hash;
  4331. };
  4332. /**
  4333. * Updates the current size from the given one.
  4334. * Returns the updated Size.
  4335. */
  4336. Size.prototype.copyFrom = function (src) {
  4337. this.width = src.width;
  4338. this.height = src.height;
  4339. };
  4340. /**
  4341. * Updates in place the current Size from the given floats.
  4342. * Returns the updated Size.
  4343. */
  4344. Size.prototype.copyFromFloats = function (width, height) {
  4345. this.width = width;
  4346. this.height = height;
  4347. return this;
  4348. };
  4349. /**
  4350. * Updates in place the current Size from the given floats.
  4351. * Returns the updated Size.
  4352. */
  4353. Size.prototype.set = function (width, height) {
  4354. return this.copyFromFloats(width, height);
  4355. };
  4356. /**
  4357. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4358. */
  4359. Size.prototype.multiplyByFloats = function (w, h) {
  4360. return new Size(this.width * w, this.height * h);
  4361. };
  4362. /**
  4363. * Returns a new Size copied from the given one.
  4364. */
  4365. Size.prototype.clone = function () {
  4366. return new Size(this.width, this.height);
  4367. };
  4368. /**
  4369. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4370. */
  4371. Size.prototype.equals = function (other) {
  4372. if (!other) {
  4373. return false;
  4374. }
  4375. return (this.width === other.width) && (this.height === other.height);
  4376. };
  4377. Object.defineProperty(Size.prototype, "surface", {
  4378. /**
  4379. * Returns the surface of the Size : width * height (float).
  4380. */
  4381. get: function () {
  4382. return this.width * this.height;
  4383. },
  4384. enumerable: true,
  4385. configurable: true
  4386. });
  4387. /**
  4388. * Returns a new Size set to (0.0, 0.0)
  4389. */
  4390. Size.Zero = function () {
  4391. return new Size(0.0, 0.0);
  4392. };
  4393. /**
  4394. * Returns a new Size set as the addition result of the current Size and the given one.
  4395. */
  4396. Size.prototype.add = function (otherSize) {
  4397. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4398. return r;
  4399. };
  4400. /**
  4401. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4402. */
  4403. Size.prototype.subtract = function (otherSize) {
  4404. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4405. return r;
  4406. };
  4407. /**
  4408. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4409. */
  4410. Size.Lerp = function (start, end, amount) {
  4411. var w = start.width + ((end.width - start.width) * amount);
  4412. var h = start.height + ((end.height - start.height) * amount);
  4413. return new Size(w, h);
  4414. };
  4415. return Size;
  4416. }());
  4417. BABYLON.Size = Size;
  4418. /**
  4419. * Class used to store quaternion data
  4420. * @see https://en.wikipedia.org/wiki/Quaternion
  4421. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4422. */
  4423. var Quaternion = /** @class */ (function () {
  4424. /**
  4425. * Creates a new Quaternion from the given floats
  4426. * @param x defines the first component (0 by default)
  4427. * @param y defines the second component (0 by default)
  4428. * @param z defines the third component (0 by default)
  4429. * @param w defines the fourth component (1.0 by default)
  4430. */
  4431. function Quaternion(
  4432. /** defines the first component (0 by default) */
  4433. x,
  4434. /** defines the second component (0 by default) */
  4435. y,
  4436. /** defines the third component (0 by default) */
  4437. z,
  4438. /** defines the fourth component (1.0 by default) */
  4439. w) {
  4440. if (x === void 0) { x = 0.0; }
  4441. if (y === void 0) { y = 0.0; }
  4442. if (z === void 0) { z = 0.0; }
  4443. if (w === void 0) { w = 1.0; }
  4444. this.x = x;
  4445. this.y = y;
  4446. this.z = z;
  4447. this.w = w;
  4448. }
  4449. /**
  4450. * Gets a string representation for the current quaternion
  4451. * @returns a string with the Quaternion coordinates
  4452. */
  4453. Quaternion.prototype.toString = function () {
  4454. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4455. };
  4456. /**
  4457. * Gets the class name of the quaternion
  4458. * @returns the string "Quaternion"
  4459. */
  4460. Quaternion.prototype.getClassName = function () {
  4461. return "Quaternion";
  4462. };
  4463. /**
  4464. * Gets a hash code for this quaternion
  4465. * @returns the quaternion hash code
  4466. */
  4467. Quaternion.prototype.getHashCode = function () {
  4468. var hash = this.x || 0;
  4469. hash = (hash * 397) ^ (this.y || 0);
  4470. hash = (hash * 397) ^ (this.z || 0);
  4471. hash = (hash * 397) ^ (this.w || 0);
  4472. return hash;
  4473. };
  4474. /**
  4475. * Copy the quaternion to an array
  4476. * @returns a new array populated with 4 elements from the quaternion coordinates
  4477. */
  4478. Quaternion.prototype.asArray = function () {
  4479. return [this.x, this.y, this.z, this.w];
  4480. };
  4481. /**
  4482. * Check if two quaternions are equals
  4483. * @param otherQuaternion defines the second operand
  4484. * @return true if the current quaternion and the given one coordinates are strictly equals
  4485. */
  4486. Quaternion.prototype.equals = function (otherQuaternion) {
  4487. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4488. };
  4489. /**
  4490. * Clone the current quaternion
  4491. * @returns a new quaternion copied from the current one
  4492. */
  4493. Quaternion.prototype.clone = function () {
  4494. return new Quaternion(this.x, this.y, this.z, this.w);
  4495. };
  4496. /**
  4497. * Copy a quaternion to the current one
  4498. * @param other defines the other quaternion
  4499. * @returns the updated current quaternion
  4500. */
  4501. Quaternion.prototype.copyFrom = function (other) {
  4502. this.x = other.x;
  4503. this.y = other.y;
  4504. this.z = other.z;
  4505. this.w = other.w;
  4506. return this;
  4507. };
  4508. /**
  4509. * Updates the current quaternion with the given float coordinates
  4510. * @param x defines the x coordinate
  4511. * @param y defines the y coordinate
  4512. * @param z defines the z coordinate
  4513. * @param w defines the w coordinate
  4514. * @returns the updated current quaternion
  4515. */
  4516. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4517. this.x = x;
  4518. this.y = y;
  4519. this.z = z;
  4520. this.w = w;
  4521. return this;
  4522. };
  4523. /**
  4524. * Updates the current quaternion from the given float coordinates
  4525. * @param x defines the x coordinate
  4526. * @param y defines the y coordinate
  4527. * @param z defines the z coordinate
  4528. * @param w defines the w coordinate
  4529. * @returns the updated current quaternion
  4530. */
  4531. Quaternion.prototype.set = function (x, y, z, w) {
  4532. return this.copyFromFloats(x, y, z, w);
  4533. };
  4534. /**
  4535. * Adds two quaternions
  4536. * @param other defines the second operand
  4537. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4538. */
  4539. Quaternion.prototype.add = function (other) {
  4540. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4541. };
  4542. /**
  4543. * Add a quaternion to the current one
  4544. * @param other defines the quaternion to add
  4545. * @returns the current quaternion
  4546. */
  4547. Quaternion.prototype.addInPlace = function (other) {
  4548. this.x += other.x;
  4549. this.y += other.y;
  4550. this.z += other.z;
  4551. this.w += other.w;
  4552. return this;
  4553. };
  4554. /**
  4555. * Subtract two quaternions
  4556. * @param other defines the second operand
  4557. * @returns a new quaternion as the subtraction result of the given one from the current one
  4558. */
  4559. Quaternion.prototype.subtract = function (other) {
  4560. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4561. };
  4562. /**
  4563. * Multiplies the current quaternion by a scale factor
  4564. * @param value defines the scale factor
  4565. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4566. */
  4567. Quaternion.prototype.scale = function (value) {
  4568. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4569. };
  4570. /**
  4571. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4572. * @param scale defines the scale factor
  4573. * @param result defines the Quaternion object where to store the result
  4574. * @returns the unmodified current quaternion
  4575. */
  4576. Quaternion.prototype.scaleToRef = function (scale, result) {
  4577. result.x = this.x * scale;
  4578. result.y = this.y * scale;
  4579. result.z = this.z * scale;
  4580. result.w = this.w * scale;
  4581. return this;
  4582. };
  4583. /**
  4584. * Multiplies in place the current quaternion by a scale factor
  4585. * @param value defines the scale factor
  4586. * @returns the current modified quaternion
  4587. */
  4588. Quaternion.prototype.scaleInPlace = function (value) {
  4589. this.x *= value;
  4590. this.y *= value;
  4591. this.z *= value;
  4592. this.w *= value;
  4593. return this;
  4594. };
  4595. /**
  4596. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4597. * @param scale defines the scale factor
  4598. * @param result defines the Quaternion object where to store the result
  4599. * @returns the unmodified current quaternion
  4600. */
  4601. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4602. result.x += this.x * scale;
  4603. result.y += this.y * scale;
  4604. result.z += this.z * scale;
  4605. result.w += this.w * scale;
  4606. return this;
  4607. };
  4608. /**
  4609. * Multiplies two quaternions
  4610. * @param q1 defines the second operand
  4611. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4612. */
  4613. Quaternion.prototype.multiply = function (q1) {
  4614. var result = new Quaternion(0, 0, 0, 1.0);
  4615. this.multiplyToRef(q1, result);
  4616. return result;
  4617. };
  4618. /**
  4619. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4620. * @param q1 defines the second operand
  4621. * @param result defines the target quaternion
  4622. * @returns the current quaternion
  4623. */
  4624. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4625. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4626. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4627. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4628. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4629. result.copyFromFloats(x, y, z, w);
  4630. return this;
  4631. };
  4632. /**
  4633. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4634. * @param q1 defines the second operand
  4635. * @returns the currentupdated quaternion
  4636. */
  4637. Quaternion.prototype.multiplyInPlace = function (q1) {
  4638. this.multiplyToRef(q1, this);
  4639. return this;
  4640. };
  4641. /**
  4642. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4643. * @param ref defines the target quaternion
  4644. * @returns the current quaternion
  4645. */
  4646. Quaternion.prototype.conjugateToRef = function (ref) {
  4647. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4648. return this;
  4649. };
  4650. /**
  4651. * Conjugates in place (1-q) the current quaternion
  4652. * @returns the current updated quaternion
  4653. */
  4654. Quaternion.prototype.conjugateInPlace = function () {
  4655. this.x *= -1;
  4656. this.y *= -1;
  4657. this.z *= -1;
  4658. return this;
  4659. };
  4660. /**
  4661. * Conjugates in place (1-q) the current quaternion
  4662. * @returns a new quaternion
  4663. */
  4664. Quaternion.prototype.conjugate = function () {
  4665. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4666. return result;
  4667. };
  4668. /**
  4669. * Gets length of current quaternion
  4670. * @returns the quaternion length (float)
  4671. */
  4672. Quaternion.prototype.length = function () {
  4673. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4674. };
  4675. /**
  4676. * Normalize in place the current quaternion
  4677. * @returns the current updated quaternion
  4678. */
  4679. Quaternion.prototype.normalize = function () {
  4680. var length = 1.0 / this.length();
  4681. this.x *= length;
  4682. this.y *= length;
  4683. this.z *= length;
  4684. this.w *= length;
  4685. return this;
  4686. };
  4687. /**
  4688. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4689. * @param order is a reserved parameter and is ignore for now
  4690. * @returns a new Vector3 containing the Euler angles
  4691. */
  4692. Quaternion.prototype.toEulerAngles = function (order) {
  4693. if (order === void 0) { order = "YZX"; }
  4694. var result = Vector3.Zero();
  4695. this.toEulerAnglesToRef(result, order);
  4696. return result;
  4697. };
  4698. /**
  4699. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4700. * @param result defines the vector which will be filled with the Euler angles
  4701. * @param order is a reserved parameter and is ignore for now
  4702. * @returns the current unchanged quaternion
  4703. */
  4704. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4705. if (order === void 0) { order = "YZX"; }
  4706. var qz = this.z;
  4707. var qx = this.x;
  4708. var qy = this.y;
  4709. var qw = this.w;
  4710. var sqw = qw * qw;
  4711. var sqz = qz * qz;
  4712. var sqx = qx * qx;
  4713. var sqy = qy * qy;
  4714. var zAxisY = qy * qz - qx * qw;
  4715. var limit = .4999999;
  4716. if (zAxisY < -limit) {
  4717. result.y = 2 * Math.atan2(qy, qw);
  4718. result.x = Math.PI / 2;
  4719. result.z = 0;
  4720. }
  4721. else if (zAxisY > limit) {
  4722. result.y = 2 * Math.atan2(qy, qw);
  4723. result.x = -Math.PI / 2;
  4724. result.z = 0;
  4725. }
  4726. else {
  4727. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4728. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4729. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4730. }
  4731. return this;
  4732. };
  4733. /**
  4734. * Updates the given rotation matrix with the current quaternion values
  4735. * @param result defines the target matrix
  4736. * @returns the current unchanged quaternion
  4737. */
  4738. Quaternion.prototype.toRotationMatrix = function (result) {
  4739. var xx = this.x * this.x;
  4740. var yy = this.y * this.y;
  4741. var zz = this.z * this.z;
  4742. var xy = this.x * this.y;
  4743. var zw = this.z * this.w;
  4744. var zx = this.z * this.x;
  4745. var yw = this.y * this.w;
  4746. var yz = this.y * this.z;
  4747. var xw = this.x * this.w;
  4748. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4749. result.m[1] = 2.0 * (xy + zw);
  4750. result.m[2] = 2.0 * (zx - yw);
  4751. result.m[3] = 0;
  4752. result.m[4] = 2.0 * (xy - zw);
  4753. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4754. result.m[6] = 2.0 * (yz + xw);
  4755. result.m[7] = 0;
  4756. result.m[8] = 2.0 * (zx + yw);
  4757. result.m[9] = 2.0 * (yz - xw);
  4758. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4759. result.m[11] = 0;
  4760. result.m[12] = 0;
  4761. result.m[13] = 0;
  4762. result.m[14] = 0;
  4763. result.m[15] = 1.0;
  4764. result._markAsUpdated();
  4765. return this;
  4766. };
  4767. /**
  4768. * Updates the current quaternion from the given rotation matrix values
  4769. * @param matrix defines the source matrix
  4770. * @returns the current updated quaternion
  4771. */
  4772. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4773. Quaternion.FromRotationMatrixToRef(matrix, this);
  4774. return this;
  4775. };
  4776. // Statics
  4777. /**
  4778. * Creates a new quaternion from a rotation matrix
  4779. * @param matrix defines the source matrix
  4780. * @returns a new quaternion created from the given rotation matrix values
  4781. */
  4782. Quaternion.FromRotationMatrix = function (matrix) {
  4783. var result = new Quaternion();
  4784. Quaternion.FromRotationMatrixToRef(matrix, result);
  4785. return result;
  4786. };
  4787. /**
  4788. * Updates the given quaternion with the given rotation matrix values
  4789. * @param matrix defines the source matrix
  4790. * @param result defines the target quaternion
  4791. */
  4792. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4793. var data = matrix.m;
  4794. var m11 = data[0], m12 = data[4], m13 = data[8];
  4795. var m21 = data[1], m22 = data[5], m23 = data[9];
  4796. var m31 = data[2], m32 = data[6], m33 = data[10];
  4797. var trace = m11 + m22 + m33;
  4798. var s;
  4799. if (trace > 0) {
  4800. s = 0.5 / Math.sqrt(trace + 1.0);
  4801. result.w = 0.25 / s;
  4802. result.x = (m32 - m23) * s;
  4803. result.y = (m13 - m31) * s;
  4804. result.z = (m21 - m12) * s;
  4805. }
  4806. else if (m11 > m22 && m11 > m33) {
  4807. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4808. result.w = (m32 - m23) / s;
  4809. result.x = 0.25 * s;
  4810. result.y = (m12 + m21) / s;
  4811. result.z = (m13 + m31) / s;
  4812. }
  4813. else if (m22 > m33) {
  4814. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4815. result.w = (m13 - m31) / s;
  4816. result.x = (m12 + m21) / s;
  4817. result.y = 0.25 * s;
  4818. result.z = (m23 + m32) / s;
  4819. }
  4820. else {
  4821. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4822. result.w = (m21 - m12) / s;
  4823. result.x = (m13 + m31) / s;
  4824. result.y = (m23 + m32) / s;
  4825. result.z = 0.25 * s;
  4826. }
  4827. };
  4828. /**
  4829. * Returns the dot product (float) between the quaternions "left" and "right"
  4830. * @param left defines the left operand
  4831. * @param right defines the right operand
  4832. * @returns the dot product
  4833. */
  4834. Quaternion.Dot = function (left, right) {
  4835. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4836. };
  4837. /**
  4838. * Checks if the two quaternions are close to each other
  4839. * @param quat0 defines the first quaternion to check
  4840. * @param quat1 defines the second quaternion to check
  4841. * @returns true if the two quaternions are close to each other
  4842. */
  4843. Quaternion.AreClose = function (quat0, quat1) {
  4844. var dot = Quaternion.Dot(quat0, quat1);
  4845. return dot >= 0;
  4846. };
  4847. /**
  4848. * Creates an empty quaternion
  4849. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4850. */
  4851. Quaternion.Zero = function () {
  4852. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4853. };
  4854. /**
  4855. * Inverse a given quaternion
  4856. * @param q defines the source quaternion
  4857. * @returns a new quaternion as the inverted current quaternion
  4858. */
  4859. Quaternion.Inverse = function (q) {
  4860. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4861. };
  4862. /**
  4863. * Creates an identity quaternion
  4864. * @returns the identity quaternion
  4865. */
  4866. Quaternion.Identity = function () {
  4867. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4868. };
  4869. /**
  4870. * Gets a boolean indicating if the given quaternion is identity
  4871. * @param quaternion defines the quaternion to check
  4872. * @returns true if the quaternion is identity
  4873. */
  4874. Quaternion.IsIdentity = function (quaternion) {
  4875. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4876. };
  4877. /**
  4878. * Creates a quaternion from a rotation around an axis
  4879. * @param axis defines the axis to use
  4880. * @param angle defines the angle to use
  4881. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4882. */
  4883. Quaternion.RotationAxis = function (axis, angle) {
  4884. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4885. };
  4886. /**
  4887. * Creates a rotation around an axis and stores it into the given quaternion
  4888. * @param axis defines the axis to use
  4889. * @param angle defines the angle to use
  4890. * @param result defines the target quaternion
  4891. * @returns the target quaternion
  4892. */
  4893. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4894. var sin = Math.sin(angle / 2);
  4895. axis.normalize();
  4896. result.w = Math.cos(angle / 2);
  4897. result.x = axis.x * sin;
  4898. result.y = axis.y * sin;
  4899. result.z = axis.z * sin;
  4900. return result;
  4901. };
  4902. /**
  4903. * Creates a new quaternion from data stored into an array
  4904. * @param array defines the data source
  4905. * @param offset defines the offset in the source array where the data starts
  4906. * @returns a new quaternion
  4907. */
  4908. Quaternion.FromArray = function (array, offset) {
  4909. if (!offset) {
  4910. offset = 0;
  4911. }
  4912. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4913. };
  4914. /**
  4915. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4916. * @param yaw defines the rotation around Y axis
  4917. * @param pitch defines the rotation around X axis
  4918. * @param roll defines the rotation around Z axis
  4919. * @returns the new quaternion
  4920. */
  4921. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4922. var q = new Quaternion();
  4923. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4924. return q;
  4925. };
  4926. /**
  4927. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4928. * @param yaw defines the rotation around Y axis
  4929. * @param pitch defines the rotation around X axis
  4930. * @param roll defines the rotation around Z axis
  4931. * @param result defines the target quaternion
  4932. */
  4933. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4934. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4935. var halfRoll = roll * 0.5;
  4936. var halfPitch = pitch * 0.5;
  4937. var halfYaw = yaw * 0.5;
  4938. var sinRoll = Math.sin(halfRoll);
  4939. var cosRoll = Math.cos(halfRoll);
  4940. var sinPitch = Math.sin(halfPitch);
  4941. var cosPitch = Math.cos(halfPitch);
  4942. var sinYaw = Math.sin(halfYaw);
  4943. var cosYaw = Math.cos(halfYaw);
  4944. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4945. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4946. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4947. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4948. };
  4949. /**
  4950. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4951. * @param alpha defines the rotation around first axis
  4952. * @param beta defines the rotation around second axis
  4953. * @param gamma defines the rotation around third axis
  4954. * @returns the new quaternion
  4955. */
  4956. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4957. var result = new Quaternion();
  4958. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4959. return result;
  4960. };
  4961. /**
  4962. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4963. * @param alpha defines the rotation around first axis
  4964. * @param beta defines the rotation around second axis
  4965. * @param gamma defines the rotation around third axis
  4966. * @param result defines the target quaternion
  4967. */
  4968. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4969. // Produces a quaternion from Euler angles in the z-x-z orientation
  4970. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4971. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4972. var halfBeta = beta * 0.5;
  4973. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4974. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4975. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4976. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4977. };
  4978. /**
  4979. * 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)
  4980. * @param axis1 defines the first axis
  4981. * @param axis2 defines the second axis
  4982. * @param axis3 defines the third axis
  4983. * @returns the new quaternion
  4984. */
  4985. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4986. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4987. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4988. return quat;
  4989. };
  4990. /**
  4991. * 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
  4992. * @param axis1 defines the first axis
  4993. * @param axis2 defines the second axis
  4994. * @param axis3 defines the third axis
  4995. * @param ref defines the target quaternion
  4996. */
  4997. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4998. var rotMat = MathTmp.Matrix[0];
  4999. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5000. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5001. };
  5002. /**
  5003. * Interpolates between two quaternions
  5004. * @param left defines first quaternion
  5005. * @param right defines second quaternion
  5006. * @param amount defines the gradient to use
  5007. * @returns the new interpolated quaternion
  5008. */
  5009. Quaternion.Slerp = function (left, right, amount) {
  5010. var result = Quaternion.Identity();
  5011. Quaternion.SlerpToRef(left, right, amount, result);
  5012. return result;
  5013. };
  5014. /**
  5015. * Interpolates between two quaternions and stores it into a target quaternion
  5016. * @param left defines first quaternion
  5017. * @param right defines second quaternion
  5018. * @param amount defines the gradient to use
  5019. * @param result defines the target quaternion
  5020. */
  5021. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5022. var num2;
  5023. var num3;
  5024. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5025. var flag = false;
  5026. if (num4 < 0) {
  5027. flag = true;
  5028. num4 = -num4;
  5029. }
  5030. if (num4 > 0.999999) {
  5031. num3 = 1 - amount;
  5032. num2 = flag ? -amount : amount;
  5033. }
  5034. else {
  5035. var num5 = Math.acos(num4);
  5036. var num6 = (1.0 / Math.sin(num5));
  5037. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5038. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5039. }
  5040. result.x = (num3 * left.x) + (num2 * right.x);
  5041. result.y = (num3 * left.y) + (num2 * right.y);
  5042. result.z = (num3 * left.z) + (num2 * right.z);
  5043. result.w = (num3 * left.w) + (num2 * right.w);
  5044. };
  5045. /**
  5046. * Interpolate between two quaternions using Hermite interpolation
  5047. * @param value1 defines first quaternion
  5048. * @param tangent1 defines the incoming tangent
  5049. * @param value2 defines second quaternion
  5050. * @param tangent2 defines the outgoing tangent
  5051. * @param amount defines the target quaternion
  5052. * @returns the new interpolated quaternion
  5053. */
  5054. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5055. var squared = amount * amount;
  5056. var cubed = amount * squared;
  5057. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5058. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5059. var part3 = (cubed - (2.0 * squared)) + amount;
  5060. var part4 = cubed - squared;
  5061. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5062. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5063. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5064. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5065. return new Quaternion(x, y, z, w);
  5066. };
  5067. return Quaternion;
  5068. }());
  5069. BABYLON.Quaternion = Quaternion;
  5070. /**
  5071. * Class used to store matrix data (4x4)
  5072. */
  5073. var Matrix = /** @class */ (function () {
  5074. /**
  5075. * Creates an empty matrix (filled with zeros)
  5076. */
  5077. function Matrix() {
  5078. this._isIdentity = false;
  5079. this._isIdentityDirty = true;
  5080. /**
  5081. * Gets or sets the internal data of the matrix
  5082. */
  5083. this.m = new Float32Array(16);
  5084. this._markAsUpdated();
  5085. }
  5086. /** @hidden */
  5087. Matrix.prototype._markAsUpdated = function () {
  5088. this.updateFlag = Matrix._updateFlagSeed++;
  5089. this._isIdentityDirty = true;
  5090. };
  5091. // Properties
  5092. /**
  5093. * Check if the current matrix is indentity
  5094. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5095. * @returns true is the matrix is the identity matrix
  5096. */
  5097. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5098. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5099. if (this._isIdentityDirty) {
  5100. this._isIdentityDirty = false;
  5101. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5102. this._isIdentity = false;
  5103. }
  5104. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5105. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5106. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5107. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5108. this._isIdentity = false;
  5109. }
  5110. else {
  5111. this._isIdentity = true;
  5112. }
  5113. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5114. this._isIdentity = false;
  5115. }
  5116. }
  5117. return this._isIdentity;
  5118. };
  5119. /**
  5120. * Gets the determinant of the matrix
  5121. * @returns the matrix determinant
  5122. */
  5123. Matrix.prototype.determinant = function () {
  5124. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5125. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5126. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5127. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5128. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5129. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5130. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5131. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5132. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5133. };
  5134. // Methods
  5135. /**
  5136. * Returns the matrix as a Float32Array
  5137. * @returns the matrix underlying array
  5138. */
  5139. Matrix.prototype.toArray = function () {
  5140. return this.m;
  5141. };
  5142. /**
  5143. * Returns the matrix as a Float32Array
  5144. * @returns the matrix underlying array.
  5145. */
  5146. Matrix.prototype.asArray = function () {
  5147. return this.toArray();
  5148. };
  5149. /**
  5150. * Inverts the current matrix in place
  5151. * @returns the current inverted matrix
  5152. */
  5153. Matrix.prototype.invert = function () {
  5154. this.invertToRef(this);
  5155. return this;
  5156. };
  5157. /**
  5158. * Sets all the matrix elements to zero
  5159. * @returns the current matrix
  5160. */
  5161. Matrix.prototype.reset = function () {
  5162. for (var index = 0; index < 16; index++) {
  5163. this.m[index] = 0.0;
  5164. }
  5165. this._markAsUpdated();
  5166. return this;
  5167. };
  5168. /**
  5169. * Adds the current matrix with a second one
  5170. * @param other defines the matrix to add
  5171. * @returns a new matrix as the addition of the current matrix and the given one
  5172. */
  5173. Matrix.prototype.add = function (other) {
  5174. var result = new Matrix();
  5175. this.addToRef(other, result);
  5176. return result;
  5177. };
  5178. /**
  5179. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5180. * @param other defines the matrix to add
  5181. * @param result defines the target matrix
  5182. * @returns the current matrix
  5183. */
  5184. Matrix.prototype.addToRef = function (other, result) {
  5185. for (var index = 0; index < 16; index++) {
  5186. result.m[index] = this.m[index] + other.m[index];
  5187. }
  5188. result._markAsUpdated();
  5189. return this;
  5190. };
  5191. /**
  5192. * Adds in place the given matrix to the current matrix
  5193. * @param other defines the second operand
  5194. * @returns the current updated matrix
  5195. */
  5196. Matrix.prototype.addToSelf = function (other) {
  5197. for (var index = 0; index < 16; index++) {
  5198. this.m[index] += other.m[index];
  5199. }
  5200. this._markAsUpdated();
  5201. return this;
  5202. };
  5203. /**
  5204. * Sets the given matrix to the current inverted Matrix
  5205. * @param other defines the target matrix
  5206. * @returns the unmodified current matrix
  5207. */
  5208. Matrix.prototype.invertToRef = function (other) {
  5209. var l1 = this.m[0];
  5210. var l2 = this.m[1];
  5211. var l3 = this.m[2];
  5212. var l4 = this.m[3];
  5213. var l5 = this.m[4];
  5214. var l6 = this.m[5];
  5215. var l7 = this.m[6];
  5216. var l8 = this.m[7];
  5217. var l9 = this.m[8];
  5218. var l10 = this.m[9];
  5219. var l11 = this.m[10];
  5220. var l12 = this.m[11];
  5221. var l13 = this.m[12];
  5222. var l14 = this.m[13];
  5223. var l15 = this.m[14];
  5224. var l16 = this.m[15];
  5225. var l17 = (l11 * l16) - (l12 * l15);
  5226. var l18 = (l10 * l16) - (l12 * l14);
  5227. var l19 = (l10 * l15) - (l11 * l14);
  5228. var l20 = (l9 * l16) - (l12 * l13);
  5229. var l21 = (l9 * l15) - (l11 * l13);
  5230. var l22 = (l9 * l14) - (l10 * l13);
  5231. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5232. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5233. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5234. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5235. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5236. var l28 = (l7 * l16) - (l8 * l15);
  5237. var l29 = (l6 * l16) - (l8 * l14);
  5238. var l30 = (l6 * l15) - (l7 * l14);
  5239. var l31 = (l5 * l16) - (l8 * l13);
  5240. var l32 = (l5 * l15) - (l7 * l13);
  5241. var l33 = (l5 * l14) - (l6 * l13);
  5242. var l34 = (l7 * l12) - (l8 * l11);
  5243. var l35 = (l6 * l12) - (l8 * l10);
  5244. var l36 = (l6 * l11) - (l7 * l10);
  5245. var l37 = (l5 * l12) - (l8 * l9);
  5246. var l38 = (l5 * l11) - (l7 * l9);
  5247. var l39 = (l5 * l10) - (l6 * l9);
  5248. other.m[0] = l23 * l27;
  5249. other.m[4] = l24 * l27;
  5250. other.m[8] = l25 * l27;
  5251. other.m[12] = l26 * l27;
  5252. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5253. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5254. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5255. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5256. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5257. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5258. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5259. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5260. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5261. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5262. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5263. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5264. other._markAsUpdated();
  5265. return this;
  5266. };
  5267. /**
  5268. * Inserts the translation vector (using 3 floats) in the current matrix
  5269. * @param x defines the 1st component of the translation
  5270. * @param y defines the 2nd component of the translation
  5271. * @param z defines the 3rd component of the translation
  5272. * @returns the current updated matrix
  5273. */
  5274. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5275. this.m[12] = x;
  5276. this.m[13] = y;
  5277. this.m[14] = z;
  5278. this._markAsUpdated();
  5279. return this;
  5280. };
  5281. /**
  5282. * Inserts the translation vector in the current matrix
  5283. * @param vector3 defines the translation to insert
  5284. * @returns the current updated matrix
  5285. */
  5286. Matrix.prototype.setTranslation = function (vector3) {
  5287. this.m[12] = vector3.x;
  5288. this.m[13] = vector3.y;
  5289. this.m[14] = vector3.z;
  5290. this._markAsUpdated();
  5291. return this;
  5292. };
  5293. /**
  5294. * Gets the translation value of the current matrix
  5295. * @returns a new Vector3 as the extracted translation from the matrix
  5296. */
  5297. Matrix.prototype.getTranslation = function () {
  5298. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5299. };
  5300. /**
  5301. * Fill a Vector3 with the extracted translation from the matrix
  5302. * @param result defines the Vector3 where to store the translation
  5303. * @returns the current matrix
  5304. */
  5305. Matrix.prototype.getTranslationToRef = function (result) {
  5306. result.x = this.m[12];
  5307. result.y = this.m[13];
  5308. result.z = this.m[14];
  5309. return this;
  5310. };
  5311. /**
  5312. * Remove rotation and scaling part from the matrix
  5313. * @returns the updated matrix
  5314. */
  5315. Matrix.prototype.removeRotationAndScaling = function () {
  5316. this.setRowFromFloats(0, 1, 0, 0, 0);
  5317. this.setRowFromFloats(1, 0, 1, 0, 0);
  5318. this.setRowFromFloats(2, 0, 0, 1, 0);
  5319. return this;
  5320. };
  5321. /**
  5322. * Multiply two matrices
  5323. * @param other defines the second operand
  5324. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5325. */
  5326. Matrix.prototype.multiply = function (other) {
  5327. var result = new Matrix();
  5328. this.multiplyToRef(other, result);
  5329. return result;
  5330. };
  5331. /**
  5332. * Copy the current matrix from the given one
  5333. * @param other defines the source matrix
  5334. * @returns the current updated matrix
  5335. */
  5336. Matrix.prototype.copyFrom = function (other) {
  5337. for (var index = 0; index < 16; index++) {
  5338. this.m[index] = other.m[index];
  5339. }
  5340. this._markAsUpdated();
  5341. return this;
  5342. };
  5343. /**
  5344. * Populates the given array from the starting index with the current matrix values
  5345. * @param array defines the target array
  5346. * @param offset defines the offset in the target array where to start storing values
  5347. * @returns the current matrix
  5348. */
  5349. Matrix.prototype.copyToArray = function (array, offset) {
  5350. if (offset === void 0) { offset = 0; }
  5351. for (var index = 0; index < 16; index++) {
  5352. array[offset + index] = this.m[index];
  5353. }
  5354. return this;
  5355. };
  5356. /**
  5357. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5358. * @param other defines the second operand
  5359. * @param result defines the matrix where to store the multiplication
  5360. * @returns the current matrix
  5361. */
  5362. Matrix.prototype.multiplyToRef = function (other, result) {
  5363. this.multiplyToArray(other, result.m, 0);
  5364. result._markAsUpdated();
  5365. return this;
  5366. };
  5367. /**
  5368. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5369. * @param other defines the second operand
  5370. * @param result defines the array where to store the multiplication
  5371. * @param offset defines the offset in the target array where to start storing values
  5372. * @returns the current matrix
  5373. */
  5374. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5375. var tm0 = this.m[0];
  5376. var tm1 = this.m[1];
  5377. var tm2 = this.m[2];
  5378. var tm3 = this.m[3];
  5379. var tm4 = this.m[4];
  5380. var tm5 = this.m[5];
  5381. var tm6 = this.m[6];
  5382. var tm7 = this.m[7];
  5383. var tm8 = this.m[8];
  5384. var tm9 = this.m[9];
  5385. var tm10 = this.m[10];
  5386. var tm11 = this.m[11];
  5387. var tm12 = this.m[12];
  5388. var tm13 = this.m[13];
  5389. var tm14 = this.m[14];
  5390. var tm15 = this.m[15];
  5391. var om0 = other.m[0];
  5392. var om1 = other.m[1];
  5393. var om2 = other.m[2];
  5394. var om3 = other.m[3];
  5395. var om4 = other.m[4];
  5396. var om5 = other.m[5];
  5397. var om6 = other.m[6];
  5398. var om7 = other.m[7];
  5399. var om8 = other.m[8];
  5400. var om9 = other.m[9];
  5401. var om10 = other.m[10];
  5402. var om11 = other.m[11];
  5403. var om12 = other.m[12];
  5404. var om13 = other.m[13];
  5405. var om14 = other.m[14];
  5406. var om15 = other.m[15];
  5407. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5408. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5409. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5410. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5411. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5412. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5413. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5414. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5415. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5416. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5417. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5418. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5419. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5420. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5421. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5422. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5423. return this;
  5424. };
  5425. /**
  5426. * Check equality between this matrix and a second one
  5427. * @param value defines the second matrix to compare
  5428. * @returns true is the current matrix and the given one values are strictly equal
  5429. */
  5430. Matrix.prototype.equals = function (value) {
  5431. return value &&
  5432. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5433. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5434. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5435. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5436. };
  5437. /**
  5438. * Clone the current matrix
  5439. * @returns a new matrix from the current matrix
  5440. */
  5441. Matrix.prototype.clone = function () {
  5442. 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]);
  5443. };
  5444. /**
  5445. * Returns the name of the current matrix class
  5446. * @returns the string "Matrix"
  5447. */
  5448. Matrix.prototype.getClassName = function () {
  5449. return "Matrix";
  5450. };
  5451. /**
  5452. * Gets the hash code of the current matrix
  5453. * @returns the hash code
  5454. */
  5455. Matrix.prototype.getHashCode = function () {
  5456. var hash = this.m[0] || 0;
  5457. for (var i = 1; i < 16; i++) {
  5458. hash = (hash * 397) ^ (this.m[i] || 0);
  5459. }
  5460. return hash;
  5461. };
  5462. /**
  5463. * Decomposes the current Matrix into a translation, rotation and scaling components
  5464. * @param scale defines the scale vector3 given as a reference to update
  5465. * @param rotation defines the rotation quaternion given as a reference to update
  5466. * @param translation defines the translation vector3 given as a reference to update
  5467. * @returns true if operation was successful
  5468. */
  5469. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5470. if (translation) {
  5471. translation.x = this.m[12];
  5472. translation.y = this.m[13];
  5473. translation.z = this.m[14];
  5474. }
  5475. scale = scale || MathTmp.Vector3[0];
  5476. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5477. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5478. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5479. if (this.determinant() <= 0) {
  5480. scale.y *= -1;
  5481. }
  5482. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5483. if (rotation) {
  5484. rotation.x = 0;
  5485. rotation.y = 0;
  5486. rotation.z = 0;
  5487. rotation.w = 1;
  5488. }
  5489. return false;
  5490. }
  5491. if (rotation) {
  5492. 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]);
  5493. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5494. }
  5495. return true;
  5496. };
  5497. /**
  5498. * Gets specific row of the matrix
  5499. * @param index defines the number of the row to get
  5500. * @returns the index-th row of the current matrix as a new Vector4
  5501. */
  5502. Matrix.prototype.getRow = function (index) {
  5503. if (index < 0 || index > 3) {
  5504. return null;
  5505. }
  5506. var i = index * 4;
  5507. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5508. };
  5509. /**
  5510. * Sets the index-th row of the current matrix to the vector4 values
  5511. * @param index defines the number of the row to set
  5512. * @param row defines the target vector4
  5513. * @returns the updated current matrix
  5514. */
  5515. Matrix.prototype.setRow = function (index, row) {
  5516. if (index < 0 || index > 3) {
  5517. return this;
  5518. }
  5519. var i = index * 4;
  5520. this.m[i + 0] = row.x;
  5521. this.m[i + 1] = row.y;
  5522. this.m[i + 2] = row.z;
  5523. this.m[i + 3] = row.w;
  5524. this._markAsUpdated();
  5525. return this;
  5526. };
  5527. /**
  5528. * Compute the transpose of the matrix
  5529. * @returns the new transposed matrix
  5530. */
  5531. Matrix.prototype.transpose = function () {
  5532. return Matrix.Transpose(this);
  5533. };
  5534. /**
  5535. * Compute the transpose of the matrix and store it in a given matrix
  5536. * @param result defines the target matrix
  5537. * @returns the current matrix
  5538. */
  5539. Matrix.prototype.transposeToRef = function (result) {
  5540. Matrix.TransposeToRef(this, result);
  5541. return this;
  5542. };
  5543. /**
  5544. * Sets the index-th row of the current matrix with the given 4 x float values
  5545. * @param index defines the row index
  5546. * @param x defines the x component to set
  5547. * @param y defines the y component to set
  5548. * @param z defines the z component to set
  5549. * @param w defines the w component to set
  5550. * @returns the updated current matrix
  5551. */
  5552. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5553. if (index < 0 || index > 3) {
  5554. return this;
  5555. }
  5556. var i = index * 4;
  5557. this.m[i + 0] = x;
  5558. this.m[i + 1] = y;
  5559. this.m[i + 2] = z;
  5560. this.m[i + 3] = w;
  5561. this._markAsUpdated();
  5562. return this;
  5563. };
  5564. /**
  5565. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5566. * @param scale defines the scale factor
  5567. * @returns a new matrix
  5568. */
  5569. Matrix.prototype.scale = function (scale) {
  5570. var result = new Matrix();
  5571. this.scaleToRef(scale, result);
  5572. return result;
  5573. };
  5574. /**
  5575. * Scale the current matrix values by a factor to a given result matrix
  5576. * @param scale defines the scale factor
  5577. * @param result defines the matrix to store the result
  5578. * @returns the current matrix
  5579. */
  5580. Matrix.prototype.scaleToRef = function (scale, result) {
  5581. for (var index = 0; index < 16; index++) {
  5582. result.m[index] = this.m[index] * scale;
  5583. }
  5584. result._markAsUpdated();
  5585. return this;
  5586. };
  5587. /**
  5588. * Scale the current matrix values by a factor and add the result to a given matrix
  5589. * @param scale defines the scale factor
  5590. * @param result defines the Matrix to store the result
  5591. * @returns the current matrix
  5592. */
  5593. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5594. for (var index = 0; index < 16; index++) {
  5595. result.m[index] += this.m[index] * scale;
  5596. }
  5597. result._markAsUpdated();
  5598. return this;
  5599. };
  5600. /**
  5601. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5602. * @param ref matrix to store the result
  5603. */
  5604. Matrix.prototype.toNormalMatrix = function (ref) {
  5605. this.invertToRef(ref);
  5606. ref.transpose();
  5607. var m = ref.m;
  5608. 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);
  5609. };
  5610. /**
  5611. * Gets only rotation part of the current matrix
  5612. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5613. */
  5614. Matrix.prototype.getRotationMatrix = function () {
  5615. var result = Matrix.Identity();
  5616. this.getRotationMatrixToRef(result);
  5617. return result;
  5618. };
  5619. /**
  5620. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5621. * @param result defines the target matrix to store data to
  5622. * @returns the current matrix
  5623. */
  5624. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5625. var m = this.m;
  5626. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5627. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5628. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5629. if (this.determinant() <= 0) {
  5630. sy *= -1;
  5631. }
  5632. if (sx === 0 || sy === 0 || sz === 0) {
  5633. Matrix.IdentityToRef(result);
  5634. }
  5635. else {
  5636. 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);
  5637. }
  5638. return this;
  5639. };
  5640. // Statics
  5641. /**
  5642. * Creates a matrix from an array
  5643. * @param array defines the source array
  5644. * @param offset defines an offset in the source array
  5645. * @returns a new Matrix set from the starting index of the given array
  5646. */
  5647. Matrix.FromArray = function (array, offset) {
  5648. var result = new Matrix();
  5649. if (!offset) {
  5650. offset = 0;
  5651. }
  5652. Matrix.FromArrayToRef(array, offset, result);
  5653. return result;
  5654. };
  5655. /**
  5656. * Copy the content of an array into a given matrix
  5657. * @param array defines the source array
  5658. * @param offset defines an offset in the source array
  5659. * @param result defines the target matrix
  5660. */
  5661. Matrix.FromArrayToRef = function (array, offset, result) {
  5662. for (var index = 0; index < 16; index++) {
  5663. result.m[index] = array[index + offset];
  5664. }
  5665. result._markAsUpdated();
  5666. };
  5667. /**
  5668. * Stores an array into a matrix after having multiplied each component by a given factor
  5669. * @param array defines the source array
  5670. * @param offset defines the offset in the source array
  5671. * @param scale defines the scaling factor
  5672. * @param result defines the target matrix
  5673. */
  5674. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5675. for (var index = 0; index < 16; index++) {
  5676. result.m[index] = array[index + offset] * scale;
  5677. }
  5678. result._markAsUpdated();
  5679. };
  5680. /**
  5681. * Stores a list of values (16) inside a given matrix
  5682. * @param initialM11 defines 1st value of 1st row
  5683. * @param initialM12 defines 2nd value of 1st row
  5684. * @param initialM13 defines 3rd value of 1st row
  5685. * @param initialM14 defines 4th value of 1st row
  5686. * @param initialM21 defines 1st value of 2nd row
  5687. * @param initialM22 defines 2nd value of 2nd row
  5688. * @param initialM23 defines 3rd value of 2nd row
  5689. * @param initialM24 defines 4th value of 2nd row
  5690. * @param initialM31 defines 1st value of 3rd row
  5691. * @param initialM32 defines 2nd value of 3rd row
  5692. * @param initialM33 defines 3rd value of 3rd row
  5693. * @param initialM34 defines 4th value of 3rd row
  5694. * @param initialM41 defines 1st value of 4th row
  5695. * @param initialM42 defines 2nd value of 4th row
  5696. * @param initialM43 defines 3rd value of 4th row
  5697. * @param initialM44 defines 4th value of 4th row
  5698. * @param result defines the target matrix
  5699. */
  5700. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5701. result.m[0] = initialM11;
  5702. result.m[1] = initialM12;
  5703. result.m[2] = initialM13;
  5704. result.m[3] = initialM14;
  5705. result.m[4] = initialM21;
  5706. result.m[5] = initialM22;
  5707. result.m[6] = initialM23;
  5708. result.m[7] = initialM24;
  5709. result.m[8] = initialM31;
  5710. result.m[9] = initialM32;
  5711. result.m[10] = initialM33;
  5712. result.m[11] = initialM34;
  5713. result.m[12] = initialM41;
  5714. result.m[13] = initialM42;
  5715. result.m[14] = initialM43;
  5716. result.m[15] = initialM44;
  5717. result._markAsUpdated();
  5718. };
  5719. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5720. /**
  5721. * Gets an identity matrix that must not be updated
  5722. */
  5723. get: function () {
  5724. return Matrix._identityReadOnly;
  5725. },
  5726. enumerable: true,
  5727. configurable: true
  5728. });
  5729. /**
  5730. * Creates new matrix from a list of values (16)
  5731. * @param initialM11 defines 1st value of 1st row
  5732. * @param initialM12 defines 2nd value of 1st row
  5733. * @param initialM13 defines 3rd value of 1st row
  5734. * @param initialM14 defines 4th value of 1st row
  5735. * @param initialM21 defines 1st value of 2nd row
  5736. * @param initialM22 defines 2nd value of 2nd row
  5737. * @param initialM23 defines 3rd value of 2nd row
  5738. * @param initialM24 defines 4th value of 2nd row
  5739. * @param initialM31 defines 1st value of 3rd row
  5740. * @param initialM32 defines 2nd value of 3rd row
  5741. * @param initialM33 defines 3rd value of 3rd row
  5742. * @param initialM34 defines 4th value of 3rd row
  5743. * @param initialM41 defines 1st value of 4th row
  5744. * @param initialM42 defines 2nd value of 4th row
  5745. * @param initialM43 defines 3rd value of 4th row
  5746. * @param initialM44 defines 4th value of 4th row
  5747. * @returns the new matrix
  5748. */
  5749. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5750. var result = new Matrix();
  5751. result.m[0] = initialM11;
  5752. result.m[1] = initialM12;
  5753. result.m[2] = initialM13;
  5754. result.m[3] = initialM14;
  5755. result.m[4] = initialM21;
  5756. result.m[5] = initialM22;
  5757. result.m[6] = initialM23;
  5758. result.m[7] = initialM24;
  5759. result.m[8] = initialM31;
  5760. result.m[9] = initialM32;
  5761. result.m[10] = initialM33;
  5762. result.m[11] = initialM34;
  5763. result.m[12] = initialM41;
  5764. result.m[13] = initialM42;
  5765. result.m[14] = initialM43;
  5766. result.m[15] = initialM44;
  5767. return result;
  5768. };
  5769. /**
  5770. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5771. * @param scale defines the scale vector3
  5772. * @param rotation defines the rotation quaternion
  5773. * @param translation defines the translation vector3
  5774. * @returns a new matrix
  5775. */
  5776. Matrix.Compose = function (scale, rotation, translation) {
  5777. var result = Matrix.Identity();
  5778. Matrix.ComposeToRef(scale, rotation, translation, result);
  5779. return result;
  5780. };
  5781. /**
  5782. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5783. * @param scale defines the scale vector3
  5784. * @param rotation defines the rotation quaternion
  5785. * @param translation defines the translation vector3
  5786. * @param result defines the target matrix
  5787. */
  5788. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5789. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5790. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5791. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5792. result.setTranslation(translation);
  5793. };
  5794. /**
  5795. * Creates a new identity matrix
  5796. * @returns a new identity matrix
  5797. */
  5798. Matrix.Identity = function () {
  5799. 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);
  5800. };
  5801. /**
  5802. * Creates a new identity matrix and stores the result in a given matrix
  5803. * @param result defines the target matrix
  5804. */
  5805. Matrix.IdentityToRef = function (result) {
  5806. 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);
  5807. };
  5808. /**
  5809. * Creates a new zero matrix
  5810. * @returns a new zero matrix
  5811. */
  5812. Matrix.Zero = function () {
  5813. 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);
  5814. };
  5815. /**
  5816. * Creates a new rotation matrix for "angle" radians around the X axis
  5817. * @param angle defines the angle (in radians) to use
  5818. * @return the new matrix
  5819. */
  5820. Matrix.RotationX = function (angle) {
  5821. var result = new Matrix();
  5822. Matrix.RotationXToRef(angle, result);
  5823. return result;
  5824. };
  5825. /**
  5826. * Creates a new matrix as the invert of a given matrix
  5827. * @param source defines the source matrix
  5828. * @returns the new matrix
  5829. */
  5830. Matrix.Invert = function (source) {
  5831. var result = new Matrix();
  5832. source.invertToRef(result);
  5833. return result;
  5834. };
  5835. /**
  5836. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5837. * @param angle defines the angle (in radians) to use
  5838. * @param result defines the target matrix
  5839. */
  5840. Matrix.RotationXToRef = function (angle, result) {
  5841. var s = Math.sin(angle);
  5842. var c = Math.cos(angle);
  5843. result.m[0] = 1.0;
  5844. result.m[15] = 1.0;
  5845. result.m[5] = c;
  5846. result.m[10] = c;
  5847. result.m[9] = -s;
  5848. result.m[6] = s;
  5849. result.m[1] = 0.0;
  5850. result.m[2] = 0.0;
  5851. result.m[3] = 0.0;
  5852. result.m[4] = 0.0;
  5853. result.m[7] = 0.0;
  5854. result.m[8] = 0.0;
  5855. result.m[11] = 0.0;
  5856. result.m[12] = 0.0;
  5857. result.m[13] = 0.0;
  5858. result.m[14] = 0.0;
  5859. result._markAsUpdated();
  5860. };
  5861. /**
  5862. * Creates a new rotation matrix for "angle" radians around the Y axis
  5863. * @param angle defines the angle (in radians) to use
  5864. * @return the new matrix
  5865. */
  5866. Matrix.RotationY = function (angle) {
  5867. var result = new Matrix();
  5868. Matrix.RotationYToRef(angle, result);
  5869. return result;
  5870. };
  5871. /**
  5872. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5873. * @param angle defines the angle (in radians) to use
  5874. * @param result defines the target matrix
  5875. */
  5876. Matrix.RotationYToRef = function (angle, result) {
  5877. var s = Math.sin(angle);
  5878. var c = Math.cos(angle);
  5879. result.m[5] = 1.0;
  5880. result.m[15] = 1.0;
  5881. result.m[0] = c;
  5882. result.m[2] = -s;
  5883. result.m[8] = s;
  5884. result.m[10] = c;
  5885. result.m[1] = 0.0;
  5886. result.m[3] = 0.0;
  5887. result.m[4] = 0.0;
  5888. result.m[6] = 0.0;
  5889. result.m[7] = 0.0;
  5890. result.m[9] = 0.0;
  5891. result.m[11] = 0.0;
  5892. result.m[12] = 0.0;
  5893. result.m[13] = 0.0;
  5894. result.m[14] = 0.0;
  5895. result._markAsUpdated();
  5896. };
  5897. /**
  5898. * Creates a new rotation matrix for "angle" radians around the Z axis
  5899. * @param angle defines the angle (in radians) to use
  5900. * @return the new matrix
  5901. */
  5902. Matrix.RotationZ = function (angle) {
  5903. var result = new Matrix();
  5904. Matrix.RotationZToRef(angle, result);
  5905. return result;
  5906. };
  5907. /**
  5908. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5909. * @param angle defines the angle (in radians) to use
  5910. * @param result defines the target matrix
  5911. */
  5912. Matrix.RotationZToRef = function (angle, result) {
  5913. var s = Math.sin(angle);
  5914. var c = Math.cos(angle);
  5915. result.m[10] = 1.0;
  5916. result.m[15] = 1.0;
  5917. result.m[0] = c;
  5918. result.m[1] = s;
  5919. result.m[4] = -s;
  5920. result.m[5] = c;
  5921. result.m[2] = 0.0;
  5922. result.m[3] = 0.0;
  5923. result.m[6] = 0.0;
  5924. result.m[7] = 0.0;
  5925. result.m[8] = 0.0;
  5926. result.m[9] = 0.0;
  5927. result.m[11] = 0.0;
  5928. result.m[12] = 0.0;
  5929. result.m[13] = 0.0;
  5930. result.m[14] = 0.0;
  5931. result._markAsUpdated();
  5932. };
  5933. /**
  5934. * Creates a new rotation matrix for "angle" radians around the given axis
  5935. * @param axis defines the axis to use
  5936. * @param angle defines the angle (in radians) to use
  5937. * @return the new matrix
  5938. */
  5939. Matrix.RotationAxis = function (axis, angle) {
  5940. var result = Matrix.Zero();
  5941. Matrix.RotationAxisToRef(axis, angle, result);
  5942. return result;
  5943. };
  5944. /**
  5945. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5946. * @param axis defines the axis to use
  5947. * @param angle defines the angle (in radians) to use
  5948. * @param result defines the target matrix
  5949. */
  5950. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5951. var s = Math.sin(-angle);
  5952. var c = Math.cos(-angle);
  5953. var c1 = 1 - c;
  5954. axis.normalize();
  5955. result.m[0] = (axis.x * axis.x) * c1 + c;
  5956. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5957. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5958. result.m[3] = 0.0;
  5959. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5960. result.m[5] = (axis.y * axis.y) * c1 + c;
  5961. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5962. result.m[7] = 0.0;
  5963. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5964. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5965. result.m[10] = (axis.z * axis.z) * c1 + c;
  5966. result.m[11] = 0.0;
  5967. result.m[15] = 1.0;
  5968. result._markAsUpdated();
  5969. };
  5970. /**
  5971. * Creates a rotation matrix
  5972. * @param yaw defines the yaw angle in radians (Y axis)
  5973. * @param pitch defines the pitch angle in radians (X axis)
  5974. * @param roll defines the roll angle in radians (X axis)
  5975. * @returns the new rotation matrix
  5976. */
  5977. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5978. var result = new Matrix();
  5979. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5980. return result;
  5981. };
  5982. /**
  5983. * Creates a rotation matrix and stores it in a given matrix
  5984. * @param yaw defines the yaw angle in radians (Y axis)
  5985. * @param pitch defines the pitch angle in radians (X axis)
  5986. * @param roll defines the roll angle in radians (X axis)
  5987. * @param result defines the target matrix
  5988. */
  5989. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5990. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5991. this._tempQuaternion.toRotationMatrix(result);
  5992. };
  5993. /**
  5994. * Creates a scaling matrix
  5995. * @param x defines the scale factor on X axis
  5996. * @param y defines the scale factor on Y axis
  5997. * @param z defines the scale factor on Z axis
  5998. * @returns the new matrix
  5999. */
  6000. Matrix.Scaling = function (x, y, z) {
  6001. var result = Matrix.Zero();
  6002. Matrix.ScalingToRef(x, y, z, result);
  6003. return result;
  6004. };
  6005. /**
  6006. * Creates a scaling matrix and stores it in a given matrix
  6007. * @param x defines the scale factor on X axis
  6008. * @param y defines the scale factor on Y axis
  6009. * @param z defines the scale factor on Z axis
  6010. * @param result defines the target matrix
  6011. */
  6012. Matrix.ScalingToRef = function (x, y, z, result) {
  6013. result.m[0] = x;
  6014. result.m[1] = 0.0;
  6015. result.m[2] = 0.0;
  6016. result.m[3] = 0.0;
  6017. result.m[4] = 0.0;
  6018. result.m[5] = y;
  6019. result.m[6] = 0.0;
  6020. result.m[7] = 0.0;
  6021. result.m[8] = 0.0;
  6022. result.m[9] = 0.0;
  6023. result.m[10] = z;
  6024. result.m[11] = 0.0;
  6025. result.m[12] = 0.0;
  6026. result.m[13] = 0.0;
  6027. result.m[14] = 0.0;
  6028. result.m[15] = 1.0;
  6029. result._markAsUpdated();
  6030. };
  6031. /**
  6032. * Creates a translation matrix
  6033. * @param x defines the translation on X axis
  6034. * @param y defines the translation on Y axis
  6035. * @param z defines the translationon Z axis
  6036. * @returns the new matrix
  6037. */
  6038. Matrix.Translation = function (x, y, z) {
  6039. var result = Matrix.Identity();
  6040. Matrix.TranslationToRef(x, y, z, result);
  6041. return result;
  6042. };
  6043. /**
  6044. * Creates a translation matrix and stores it in a given matrix
  6045. * @param x defines the translation on X axis
  6046. * @param y defines the translation on Y axis
  6047. * @param z defines the translationon Z axis
  6048. * @param result defines the target matrix
  6049. */
  6050. Matrix.TranslationToRef = function (x, y, z, result) {
  6051. 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);
  6052. };
  6053. /**
  6054. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6055. * @param startValue defines the start value
  6056. * @param endValue defines the end value
  6057. * @param gradient defines the gradient factor
  6058. * @returns the new matrix
  6059. */
  6060. Matrix.Lerp = function (startValue, endValue, gradient) {
  6061. var result = Matrix.Zero();
  6062. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6063. return result;
  6064. };
  6065. /**
  6066. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6067. * @param startValue defines the start value
  6068. * @param endValue defines the end value
  6069. * @param gradient defines the gradient factor
  6070. * @param result defines the Matrix object where to store data
  6071. */
  6072. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6073. for (var index = 0; index < 16; index++) {
  6074. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6075. }
  6076. result._markAsUpdated();
  6077. };
  6078. /**
  6079. * Builds a new matrix whose values are computed by:
  6080. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6081. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6082. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6083. * @param startValue defines the first matrix
  6084. * @param endValue defines the second matrix
  6085. * @param gradient defines the gradient between the two matrices
  6086. * @returns the new matrix
  6087. */
  6088. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6089. var result = Matrix.Zero();
  6090. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6091. return result;
  6092. };
  6093. /**
  6094. * Update a matrix to values which are computed by:
  6095. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6096. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6097. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6098. * @param startValue defines the first matrix
  6099. * @param endValue defines the second matrix
  6100. * @param gradient defines the gradient between the two matrices
  6101. * @param result defines the target matrix
  6102. */
  6103. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6104. var startScale = MathTmp.Vector3[0];
  6105. var startRotation = MathTmp.Quaternion[0];
  6106. var startTranslation = MathTmp.Vector3[1];
  6107. startValue.decompose(startScale, startRotation, startTranslation);
  6108. var endScale = MathTmp.Vector3[2];
  6109. var endRotation = MathTmp.Quaternion[1];
  6110. var endTranslation = MathTmp.Vector3[3];
  6111. endValue.decompose(endScale, endRotation, endTranslation);
  6112. var resultScale = MathTmp.Vector3[4];
  6113. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6114. var resultRotation = MathTmp.Quaternion[2];
  6115. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6116. var resultTranslation = MathTmp.Vector3[5];
  6117. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6118. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6119. };
  6120. /**
  6121. * 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"
  6122. * This function works in left handed mode
  6123. * @param eye defines the final position of the entity
  6124. * @param target defines where the entity should look at
  6125. * @param up defines the up vector for the entity
  6126. * @returns the new matrix
  6127. */
  6128. Matrix.LookAtLH = function (eye, target, up) {
  6129. var result = Matrix.Zero();
  6130. Matrix.LookAtLHToRef(eye, target, up, result);
  6131. return result;
  6132. };
  6133. /**
  6134. * 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".
  6135. * This function works in left handed mode
  6136. * @param eye defines the final position of the entity
  6137. * @param target defines where the entity should look at
  6138. * @param up defines the up vector for the entity
  6139. * @param result defines the target matrix
  6140. */
  6141. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6142. // Z axis
  6143. target.subtractToRef(eye, this._zAxis);
  6144. this._zAxis.normalize();
  6145. // X axis
  6146. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6147. if (this._xAxis.lengthSquared() === 0) {
  6148. this._xAxis.x = 1.0;
  6149. }
  6150. else {
  6151. this._xAxis.normalize();
  6152. }
  6153. // Y axis
  6154. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6155. this._yAxis.normalize();
  6156. // Eye angles
  6157. var ex = -Vector3.Dot(this._xAxis, eye);
  6158. var ey = -Vector3.Dot(this._yAxis, eye);
  6159. var ez = -Vector3.Dot(this._zAxis, eye);
  6160. 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);
  6161. };
  6162. /**
  6163. * 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"
  6164. * This function works in right handed mode
  6165. * @param eye defines the final position of the entity
  6166. * @param target defines where the entity should look at
  6167. * @param up defines the up vector for the entity
  6168. * @returns the new matrix
  6169. */
  6170. Matrix.LookAtRH = function (eye, target, up) {
  6171. var result = Matrix.Zero();
  6172. Matrix.LookAtRHToRef(eye, target, up, result);
  6173. return result;
  6174. };
  6175. /**
  6176. * 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".
  6177. * This function works in right handed mode
  6178. * @param eye defines the final position of the entity
  6179. * @param target defines where the entity should look at
  6180. * @param up defines the up vector for the entity
  6181. * @param result defines the target matrix
  6182. */
  6183. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6184. // Z axis
  6185. eye.subtractToRef(target, this._zAxis);
  6186. this._zAxis.normalize();
  6187. // X axis
  6188. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6189. if (this._xAxis.lengthSquared() === 0) {
  6190. this._xAxis.x = 1.0;
  6191. }
  6192. else {
  6193. this._xAxis.normalize();
  6194. }
  6195. // Y axis
  6196. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6197. this._yAxis.normalize();
  6198. // Eye angles
  6199. var ex = -Vector3.Dot(this._xAxis, eye);
  6200. var ey = -Vector3.Dot(this._yAxis, eye);
  6201. var ez = -Vector3.Dot(this._zAxis, eye);
  6202. 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);
  6203. };
  6204. /**
  6205. * Create a left-handed orthographic projection matrix
  6206. * @param width defines the viewport width
  6207. * @param height defines the viewport height
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a left-handed orthographic projection matrix
  6211. */
  6212. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Store a left-handed orthographic projection to a given matrix
  6219. * @param width defines the viewport width
  6220. * @param height defines the viewport height
  6221. * @param znear defines the near clip plane
  6222. * @param zfar defines the far clip plane
  6223. * @param result defines the target matrix
  6224. */
  6225. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6226. var n = znear;
  6227. var f = zfar;
  6228. var a = 2.0 / width;
  6229. var b = 2.0 / height;
  6230. var c = 2.0 / (f - n);
  6231. var d = -(f + n) / (f - n);
  6232. 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);
  6233. };
  6234. /**
  6235. * Create a left-handed orthographic projection matrix
  6236. * @param left defines the viewport left coordinate
  6237. * @param right defines the viewport right coordinate
  6238. * @param bottom defines the viewport bottom coordinate
  6239. * @param top defines the viewport top coordinate
  6240. * @param znear defines the near clip plane
  6241. * @param zfar defines the far clip plane
  6242. * @returns a new matrix as a left-handed orthographic projection matrix
  6243. */
  6244. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6245. var matrix = Matrix.Zero();
  6246. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6247. return matrix;
  6248. };
  6249. /**
  6250. * Stores a left-handed orthographic projection into a given matrix
  6251. * @param left defines the viewport left coordinate
  6252. * @param right defines the viewport right coordinate
  6253. * @param bottom defines the viewport bottom coordinate
  6254. * @param top defines the viewport top coordinate
  6255. * @param znear defines the near clip plane
  6256. * @param zfar defines the far clip plane
  6257. * @param result defines the target matrix
  6258. */
  6259. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6260. var n = znear;
  6261. var f = zfar;
  6262. var a = 2.0 / (right - left);
  6263. var b = 2.0 / (top - bottom);
  6264. var c = 2.0 / (f - n);
  6265. var d = -(f + n) / (f - n);
  6266. var i0 = (left + right) / (left - right);
  6267. var i1 = (top + bottom) / (bottom - top);
  6268. 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);
  6269. };
  6270. /**
  6271. * Creates a right-handed orthographic projection matrix
  6272. * @param left defines the viewport left coordinate
  6273. * @param right defines the viewport right coordinate
  6274. * @param bottom defines the viewport bottom coordinate
  6275. * @param top defines the viewport top coordinate
  6276. * @param znear defines the near clip plane
  6277. * @param zfar defines the far clip plane
  6278. * @returns a new matrix as a right-handed orthographic projection matrix
  6279. */
  6280. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6281. var matrix = Matrix.Zero();
  6282. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6283. return matrix;
  6284. };
  6285. /**
  6286. * Stores a right-handed orthographic projection into a given matrix
  6287. * @param left defines the viewport left coordinate
  6288. * @param right defines the viewport right coordinate
  6289. * @param bottom defines the viewport bottom coordinate
  6290. * @param top defines the viewport top coordinate
  6291. * @param znear defines the near clip plane
  6292. * @param zfar defines the far clip plane
  6293. * @param result defines the target matrix
  6294. */
  6295. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6296. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6297. result.m[10] *= -1.0;
  6298. };
  6299. /**
  6300. * Creates a left-handed perspective projection matrix
  6301. * @param width defines the viewport width
  6302. * @param height defines the viewport height
  6303. * @param znear defines the near clip plane
  6304. * @param zfar defines the far clip plane
  6305. * @returns a new matrix as a left-handed perspective projection matrix
  6306. */
  6307. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6308. var matrix = Matrix.Zero();
  6309. var n = znear;
  6310. var f = zfar;
  6311. var a = 2.0 * n / width;
  6312. var b = 2.0 * n / height;
  6313. var c = (f + n) / (f - n);
  6314. var d = -2.0 * f * n / (f - n);
  6315. 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);
  6316. return matrix;
  6317. };
  6318. /**
  6319. * Creates a left-handed perspective projection matrix
  6320. * @param fov defines the horizontal field of view
  6321. * @param aspect defines the aspect ratio
  6322. * @param znear defines the near clip plane
  6323. * @param zfar defines the far clip plane
  6324. * @returns a new matrix as a left-handed perspective projection matrix
  6325. */
  6326. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6327. var matrix = Matrix.Zero();
  6328. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6329. return matrix;
  6330. };
  6331. /**
  6332. * Stores a left-handed perspective projection into a given matrix
  6333. * @param fov defines the horizontal field of view
  6334. * @param aspect defines the aspect ratio
  6335. * @param znear defines the near clip plane
  6336. * @param zfar defines the far clip plane
  6337. * @param result defines the target matrix
  6338. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6339. */
  6340. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6341. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6342. var n = znear;
  6343. var f = zfar;
  6344. var t = 1.0 / (Math.tan(fov * 0.5));
  6345. var a = isVerticalFovFixed ? (t / aspect) : t;
  6346. var b = isVerticalFovFixed ? t : (t * aspect);
  6347. var c = (f + n) / (f - n);
  6348. var d = -2.0 * f * n / (f - n);
  6349. 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);
  6350. };
  6351. /**
  6352. * Creates a right-handed perspective projection matrix
  6353. * @param fov defines the horizontal field of view
  6354. * @param aspect defines the aspect ratio
  6355. * @param znear defines the near clip plane
  6356. * @param zfar defines the far clip plane
  6357. * @returns a new matrix as a right-handed perspective projection matrix
  6358. */
  6359. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6360. var matrix = Matrix.Zero();
  6361. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6362. return matrix;
  6363. };
  6364. /**
  6365. * Stores a right-handed perspective projection into a given matrix
  6366. * @param fov defines the horizontal field of view
  6367. * @param aspect defines the aspect ratio
  6368. * @param znear defines the near clip plane
  6369. * @param zfar defines the far clip plane
  6370. * @param result defines the target matrix
  6371. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6372. */
  6373. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6374. //alternatively this could be expressed as:
  6375. // m = PerspectiveFovLHToRef
  6376. // m[10] *= -1.0;
  6377. // m[11] *= -1.0;
  6378. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6379. var n = znear;
  6380. var f = zfar;
  6381. var t = 1.0 / (Math.tan(fov * 0.5));
  6382. var a = isVerticalFovFixed ? (t / aspect) : t;
  6383. var b = isVerticalFovFixed ? t : (t * aspect);
  6384. var c = -(f + n) / (f - n);
  6385. var d = -2 * f * n / (f - n);
  6386. 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);
  6387. };
  6388. /**
  6389. * Stores a perspective projection for WebVR info a given matrix
  6390. * @param fov defines the field of view
  6391. * @param znear defines the near clip plane
  6392. * @param zfar defines the far clip plane
  6393. * @param result defines the target matrix
  6394. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6395. */
  6396. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6397. if (rightHanded === void 0) { rightHanded = false; }
  6398. var rightHandedFactor = rightHanded ? -1 : 1;
  6399. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6400. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6401. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6402. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6403. var xScale = 2.0 / (leftTan + rightTan);
  6404. var yScale = 2.0 / (upTan + downTan);
  6405. result.m[0] = xScale;
  6406. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6407. result.m[5] = yScale;
  6408. result.m[6] = result.m[7] = 0.0;
  6409. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6410. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6411. result.m[10] = -zfar / (znear - zfar);
  6412. result.m[11] = 1.0 * rightHandedFactor;
  6413. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6414. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6415. result._markAsUpdated();
  6416. };
  6417. /**
  6418. * Computes a complete transformation matrix
  6419. * @param viewport defines the viewport to use
  6420. * @param world defines the world matrix
  6421. * @param view defines the view matrix
  6422. * @param projection defines the projection matrix
  6423. * @param zmin defines the near clip plane
  6424. * @param zmax defines the far clip plane
  6425. * @returns the transformation matrix
  6426. */
  6427. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6428. var cw = viewport.width;
  6429. var ch = viewport.height;
  6430. var cx = viewport.x;
  6431. var cy = viewport.y;
  6432. 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);
  6433. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6434. };
  6435. /**
  6436. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6437. * @param matrix defines the matrix to use
  6438. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6439. */
  6440. Matrix.GetAsMatrix2x2 = function (matrix) {
  6441. return new Float32Array([
  6442. matrix.m[0], matrix.m[1],
  6443. matrix.m[4], matrix.m[5]
  6444. ]);
  6445. };
  6446. /**
  6447. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6448. * @param matrix defines the matrix to use
  6449. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6450. */
  6451. Matrix.GetAsMatrix3x3 = function (matrix) {
  6452. return new Float32Array([
  6453. matrix.m[0], matrix.m[1], matrix.m[2],
  6454. matrix.m[4], matrix.m[5], matrix.m[6],
  6455. matrix.m[8], matrix.m[9], matrix.m[10]
  6456. ]);
  6457. };
  6458. /**
  6459. * Compute the transpose of a given matrix
  6460. * @param matrix defines the matrix to transpose
  6461. * @returns the new matrix
  6462. */
  6463. Matrix.Transpose = function (matrix) {
  6464. var result = new Matrix();
  6465. Matrix.TransposeToRef(matrix, result);
  6466. return result;
  6467. };
  6468. /**
  6469. * Compute the transpose of a matrix and store it in a target matrix
  6470. * @param matrix defines the matrix to transpose
  6471. * @param result defines the target matrix
  6472. */
  6473. Matrix.TransposeToRef = function (matrix, result) {
  6474. result.m[0] = matrix.m[0];
  6475. result.m[1] = matrix.m[4];
  6476. result.m[2] = matrix.m[8];
  6477. result.m[3] = matrix.m[12];
  6478. result.m[4] = matrix.m[1];
  6479. result.m[5] = matrix.m[5];
  6480. result.m[6] = matrix.m[9];
  6481. result.m[7] = matrix.m[13];
  6482. result.m[8] = matrix.m[2];
  6483. result.m[9] = matrix.m[6];
  6484. result.m[10] = matrix.m[10];
  6485. result.m[11] = matrix.m[14];
  6486. result.m[12] = matrix.m[3];
  6487. result.m[13] = matrix.m[7];
  6488. result.m[14] = matrix.m[11];
  6489. result.m[15] = matrix.m[15];
  6490. };
  6491. /**
  6492. * Computes a reflection matrix from a plane
  6493. * @param plane defines the reflection plane
  6494. * @returns a new matrix
  6495. */
  6496. Matrix.Reflection = function (plane) {
  6497. var matrix = new Matrix();
  6498. Matrix.ReflectionToRef(plane, matrix);
  6499. return matrix;
  6500. };
  6501. /**
  6502. * Computes a reflection matrix from a plane
  6503. * @param plane defines the reflection plane
  6504. * @param result defines the target matrix
  6505. */
  6506. Matrix.ReflectionToRef = function (plane, result) {
  6507. plane.normalize();
  6508. var x = plane.normal.x;
  6509. var y = plane.normal.y;
  6510. var z = plane.normal.z;
  6511. var temp = -2 * x;
  6512. var temp2 = -2 * y;
  6513. var temp3 = -2 * z;
  6514. result.m[0] = (temp * x) + 1;
  6515. result.m[1] = temp2 * x;
  6516. result.m[2] = temp3 * x;
  6517. result.m[3] = 0.0;
  6518. result.m[4] = temp * y;
  6519. result.m[5] = (temp2 * y) + 1;
  6520. result.m[6] = temp3 * y;
  6521. result.m[7] = 0.0;
  6522. result.m[8] = temp * z;
  6523. result.m[9] = temp2 * z;
  6524. result.m[10] = (temp3 * z) + 1;
  6525. result.m[11] = 0.0;
  6526. result.m[12] = temp * plane.d;
  6527. result.m[13] = temp2 * plane.d;
  6528. result.m[14] = temp3 * plane.d;
  6529. result.m[15] = 1.0;
  6530. result._markAsUpdated();
  6531. };
  6532. /**
  6533. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6534. * @param xaxis defines the value of the 1st axis
  6535. * @param yaxis defines the value of the 2nd axis
  6536. * @param zaxis defines the value of the 3rd axis
  6537. * @param result defines the target matrix
  6538. */
  6539. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6540. result.m[0] = xaxis.x;
  6541. result.m[1] = xaxis.y;
  6542. result.m[2] = xaxis.z;
  6543. result.m[3] = 0.0;
  6544. result.m[4] = yaxis.x;
  6545. result.m[5] = yaxis.y;
  6546. result.m[6] = yaxis.z;
  6547. result.m[7] = 0.0;
  6548. result.m[8] = zaxis.x;
  6549. result.m[9] = zaxis.y;
  6550. result.m[10] = zaxis.z;
  6551. result.m[11] = 0.0;
  6552. result.m[12] = 0.0;
  6553. result.m[13] = 0.0;
  6554. result.m[14] = 0.0;
  6555. result.m[15] = 1.0;
  6556. result._markAsUpdated();
  6557. };
  6558. /**
  6559. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6560. * @param quat defines the quaternion to use
  6561. * @param result defines the target matrix
  6562. */
  6563. Matrix.FromQuaternionToRef = function (quat, result) {
  6564. var xx = quat.x * quat.x;
  6565. var yy = quat.y * quat.y;
  6566. var zz = quat.z * quat.z;
  6567. var xy = quat.x * quat.y;
  6568. var zw = quat.z * quat.w;
  6569. var zx = quat.z * quat.x;
  6570. var yw = quat.y * quat.w;
  6571. var yz = quat.y * quat.z;
  6572. var xw = quat.x * quat.w;
  6573. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6574. result.m[1] = 2.0 * (xy + zw);
  6575. result.m[2] = 2.0 * (zx - yw);
  6576. result.m[3] = 0.0;
  6577. result.m[4] = 2.0 * (xy - zw);
  6578. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6579. result.m[6] = 2.0 * (yz + xw);
  6580. result.m[7] = 0.0;
  6581. result.m[8] = 2.0 * (zx + yw);
  6582. result.m[9] = 2.0 * (yz - xw);
  6583. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6584. result.m[11] = 0.0;
  6585. result.m[12] = 0.0;
  6586. result.m[13] = 0.0;
  6587. result.m[14] = 0.0;
  6588. result.m[15] = 1.0;
  6589. result._markAsUpdated();
  6590. };
  6591. Matrix._tempQuaternion = new Quaternion();
  6592. Matrix._xAxis = Vector3.Zero();
  6593. Matrix._yAxis = Vector3.Zero();
  6594. Matrix._zAxis = Vector3.Zero();
  6595. Matrix._updateFlagSeed = 0;
  6596. Matrix._identityReadOnly = Matrix.Identity();
  6597. return Matrix;
  6598. }());
  6599. BABYLON.Matrix = Matrix;
  6600. var Plane = /** @class */ (function () {
  6601. /**
  6602. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6603. */
  6604. function Plane(a, b, c, d) {
  6605. this.normal = new Vector3(a, b, c);
  6606. this.d = d;
  6607. }
  6608. /**
  6609. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6610. */
  6611. Plane.prototype.asArray = function () {
  6612. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6613. };
  6614. // Methods
  6615. /**
  6616. * Returns a new plane copied from the current Plane.
  6617. */
  6618. Plane.prototype.clone = function () {
  6619. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6620. };
  6621. /**
  6622. * Returns the string "Plane".
  6623. */
  6624. Plane.prototype.getClassName = function () {
  6625. return "Plane";
  6626. };
  6627. /**
  6628. * Returns the Plane hash code.
  6629. */
  6630. Plane.prototype.getHashCode = function () {
  6631. var hash = this.normal.getHashCode();
  6632. hash = (hash * 397) ^ (this.d || 0);
  6633. return hash;
  6634. };
  6635. /**
  6636. * Normalize the current Plane in place.
  6637. * Returns the updated Plane.
  6638. */
  6639. Plane.prototype.normalize = function () {
  6640. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6641. var magnitude = 0.0;
  6642. if (norm !== 0) {
  6643. magnitude = 1.0 / norm;
  6644. }
  6645. this.normal.x *= magnitude;
  6646. this.normal.y *= magnitude;
  6647. this.normal.z *= magnitude;
  6648. this.d *= magnitude;
  6649. return this;
  6650. };
  6651. /**
  6652. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6653. */
  6654. Plane.prototype.transform = function (transformation) {
  6655. var transposedMatrix = Matrix.Transpose(transformation);
  6656. var x = this.normal.x;
  6657. var y = this.normal.y;
  6658. var z = this.normal.z;
  6659. var d = this.d;
  6660. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6661. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6662. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6663. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6664. return new Plane(normalX, normalY, normalZ, finalD);
  6665. };
  6666. /**
  6667. * Returns the dot product (float) of the point coordinates and the plane normal.
  6668. */
  6669. Plane.prototype.dotCoordinate = function (point) {
  6670. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6671. };
  6672. /**
  6673. * Updates the current Plane from the plane defined by the three given points.
  6674. * Returns the updated Plane.
  6675. */
  6676. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6677. var x1 = point2.x - point1.x;
  6678. var y1 = point2.y - point1.y;
  6679. var z1 = point2.z - point1.z;
  6680. var x2 = point3.x - point1.x;
  6681. var y2 = point3.y - point1.y;
  6682. var z2 = point3.z - point1.z;
  6683. var yz = (y1 * z2) - (z1 * y2);
  6684. var xz = (z1 * x2) - (x1 * z2);
  6685. var xy = (x1 * y2) - (y1 * x2);
  6686. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6687. var invPyth;
  6688. if (pyth !== 0) {
  6689. invPyth = 1.0 / pyth;
  6690. }
  6691. else {
  6692. invPyth = 0.0;
  6693. }
  6694. this.normal.x = yz * invPyth;
  6695. this.normal.y = xz * invPyth;
  6696. this.normal.z = xy * invPyth;
  6697. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6698. return this;
  6699. };
  6700. /**
  6701. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6702. */
  6703. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6704. var dot = Vector3.Dot(this.normal, direction);
  6705. return (dot <= epsilon);
  6706. };
  6707. /**
  6708. * Returns the signed distance (float) from the given point to the Plane.
  6709. */
  6710. Plane.prototype.signedDistanceTo = function (point) {
  6711. return Vector3.Dot(point, this.normal) + this.d;
  6712. };
  6713. // Statics
  6714. /**
  6715. * Returns a new Plane from the given array.
  6716. */
  6717. Plane.FromArray = function (array) {
  6718. return new Plane(array[0], array[1], array[2], array[3]);
  6719. };
  6720. /**
  6721. * Returns a new Plane defined by the three given points.
  6722. */
  6723. Plane.FromPoints = function (point1, point2, point3) {
  6724. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6725. result.copyFromPoints(point1, point2, point3);
  6726. return result;
  6727. };
  6728. /**
  6729. * Returns a new Plane the normal vector to this plane at the given origin point.
  6730. * Note : the vector "normal" is updated because normalized.
  6731. */
  6732. Plane.FromPositionAndNormal = function (origin, normal) {
  6733. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6734. normal.normalize();
  6735. result.normal = normal;
  6736. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6737. return result;
  6738. };
  6739. /**
  6740. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6741. */
  6742. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6743. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6744. return Vector3.Dot(point, normal) + d;
  6745. };
  6746. return Plane;
  6747. }());
  6748. BABYLON.Plane = Plane;
  6749. var Viewport = /** @class */ (function () {
  6750. /**
  6751. * Creates a Viewport object located at (x, y) and sized (width, height).
  6752. */
  6753. function Viewport(x, y, width, height) {
  6754. this.x = x;
  6755. this.y = y;
  6756. this.width = width;
  6757. this.height = height;
  6758. }
  6759. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6760. if (renderWidthOrEngine.getRenderWidth) {
  6761. var engine = renderWidthOrEngine;
  6762. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6763. }
  6764. var renderWidth = renderWidthOrEngine;
  6765. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6766. };
  6767. /**
  6768. * Returns a new Viewport copied from the current one.
  6769. */
  6770. Viewport.prototype.clone = function () {
  6771. return new Viewport(this.x, this.y, this.width, this.height);
  6772. };
  6773. return Viewport;
  6774. }());
  6775. BABYLON.Viewport = Viewport;
  6776. var Frustum = /** @class */ (function () {
  6777. function Frustum() {
  6778. }
  6779. /**
  6780. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6781. */
  6782. Frustum.GetPlanes = function (transform) {
  6783. var frustumPlanes = [];
  6784. for (var index = 0; index < 6; index++) {
  6785. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6786. }
  6787. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6788. return frustumPlanes;
  6789. };
  6790. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6791. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6792. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6793. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6794. frustumPlane.d = transform.m[15] + transform.m[14];
  6795. frustumPlane.normalize();
  6796. };
  6797. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6798. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6799. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6800. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6801. frustumPlane.d = transform.m[15] - transform.m[14];
  6802. frustumPlane.normalize();
  6803. };
  6804. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6805. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6806. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6807. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6808. frustumPlane.d = transform.m[15] + transform.m[12];
  6809. frustumPlane.normalize();
  6810. };
  6811. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6812. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6813. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6814. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6815. frustumPlane.d = transform.m[15] - transform.m[12];
  6816. frustumPlane.normalize();
  6817. };
  6818. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6819. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6820. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6821. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6822. frustumPlane.d = transform.m[15] - transform.m[13];
  6823. frustumPlane.normalize();
  6824. };
  6825. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6826. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6827. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6828. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6829. frustumPlane.d = transform.m[15] + transform.m[13];
  6830. frustumPlane.normalize();
  6831. };
  6832. /**
  6833. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6834. */
  6835. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6836. // Near
  6837. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6838. // Far
  6839. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6840. // Left
  6841. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6842. // Right
  6843. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6844. // Top
  6845. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6846. // Bottom
  6847. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6848. };
  6849. return Frustum;
  6850. }());
  6851. BABYLON.Frustum = Frustum;
  6852. /** Defines supported spaces */
  6853. var Space;
  6854. (function (Space) {
  6855. /** Local (object) space */
  6856. Space[Space["LOCAL"] = 0] = "LOCAL";
  6857. /** World space */
  6858. Space[Space["WORLD"] = 1] = "WORLD";
  6859. /** Bone space */
  6860. Space[Space["BONE"] = 2] = "BONE";
  6861. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6862. /** Defines the 3 main axes */
  6863. var Axis = /** @class */ (function () {
  6864. function Axis() {
  6865. }
  6866. /** X axis */
  6867. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6868. /** Y axis */
  6869. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6870. /** Z axis */
  6871. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6872. return Axis;
  6873. }());
  6874. BABYLON.Axis = Axis;
  6875. ;
  6876. var BezierCurve = /** @class */ (function () {
  6877. function BezierCurve() {
  6878. }
  6879. /**
  6880. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6881. */
  6882. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6883. // Extract X (which is equal to time here)
  6884. var f0 = 1 - 3 * x2 + 3 * x1;
  6885. var f1 = 3 * x2 - 6 * x1;
  6886. var f2 = 3 * x1;
  6887. var refinedT = t;
  6888. for (var i = 0; i < 5; i++) {
  6889. var refinedT2 = refinedT * refinedT;
  6890. var refinedT3 = refinedT2 * refinedT;
  6891. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6892. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6893. refinedT -= (x - t) * slope;
  6894. refinedT = Math.min(1, Math.max(0, refinedT));
  6895. }
  6896. // Resolve cubic bezier for the given x
  6897. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6898. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6899. Math.pow(refinedT, 3);
  6900. };
  6901. return BezierCurve;
  6902. }());
  6903. BABYLON.BezierCurve = BezierCurve;
  6904. /**
  6905. * Defines potential orientation for back face culling
  6906. */
  6907. var Orientation;
  6908. (function (Orientation) {
  6909. /**
  6910. * Clockwise
  6911. */
  6912. Orientation[Orientation["CW"] = 0] = "CW";
  6913. /** Counter clockwise */
  6914. Orientation[Orientation["CCW"] = 1] = "CCW";
  6915. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6916. /**
  6917. * Defines angle representation
  6918. */
  6919. var Angle = /** @class */ (function () {
  6920. /**
  6921. * Creates an Angle object of "radians" radians (float).
  6922. */
  6923. function Angle(radians) {
  6924. this._radians = radians;
  6925. if (this._radians < 0.0)
  6926. this._radians += (2.0 * Math.PI);
  6927. }
  6928. /**
  6929. * Get value in degrees
  6930. * @returns the Angle value in degrees (float)
  6931. */
  6932. Angle.prototype.degrees = function () {
  6933. return this._radians * 180.0 / Math.PI;
  6934. };
  6935. /**
  6936. * Get value in radians
  6937. * @returns the Angle value in radians (float)
  6938. */
  6939. Angle.prototype.radians = function () {
  6940. return this._radians;
  6941. };
  6942. /**
  6943. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6944. * @param a defines first vector
  6945. * @param b defines second vector
  6946. * @returns a new Angle
  6947. */
  6948. Angle.BetweenTwoPoints = function (a, b) {
  6949. var delta = b.subtract(a);
  6950. var theta = Math.atan2(delta.y, delta.x);
  6951. return new Angle(theta);
  6952. };
  6953. /**
  6954. * Gets a new Angle object from the given float in radians
  6955. * @param radians defines the angle value in radians
  6956. * @returns a new Angle
  6957. */
  6958. Angle.FromRadians = function (radians) {
  6959. return new Angle(radians);
  6960. };
  6961. /**
  6962. * Gets a new Angle object from the given float in degrees
  6963. * @param degrees defines the angle value in degrees
  6964. * @returns a new Angle
  6965. */
  6966. Angle.FromDegrees = function (degrees) {
  6967. return new Angle(degrees * Math.PI / 180.0);
  6968. };
  6969. return Angle;
  6970. }());
  6971. BABYLON.Angle = Angle;
  6972. var Arc2 = /** @class */ (function () {
  6973. /**
  6974. * Creates an Arc object from the three given points : start, middle and end.
  6975. */
  6976. function Arc2(startPoint, midPoint, endPoint) {
  6977. this.startPoint = startPoint;
  6978. this.midPoint = midPoint;
  6979. this.endPoint = endPoint;
  6980. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6981. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6982. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6983. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6984. 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);
  6985. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6986. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6987. var a1 = this.startAngle.degrees();
  6988. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6989. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6990. // angles correction
  6991. if (a2 - a1 > +180.0)
  6992. a2 -= 360.0;
  6993. if (a2 - a1 < -180.0)
  6994. a2 += 360.0;
  6995. if (a3 - a2 > +180.0)
  6996. a3 -= 360.0;
  6997. if (a3 - a2 < -180.0)
  6998. a3 += 360.0;
  6999. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7000. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7001. }
  7002. return Arc2;
  7003. }());
  7004. BABYLON.Arc2 = Arc2;
  7005. var Path2 = /** @class */ (function () {
  7006. /**
  7007. * Creates a Path2 object from the starting 2D coordinates x and y.
  7008. */
  7009. function Path2(x, y) {
  7010. this._points = new Array();
  7011. this._length = 0.0;
  7012. this.closed = false;
  7013. this._points.push(new Vector2(x, y));
  7014. }
  7015. /**
  7016. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7017. * Returns the updated Path2.
  7018. */
  7019. Path2.prototype.addLineTo = function (x, y) {
  7020. if (this.closed) {
  7021. return this;
  7022. }
  7023. var newPoint = new Vector2(x, y);
  7024. var previousPoint = this._points[this._points.length - 1];
  7025. this._points.push(newPoint);
  7026. this._length += newPoint.subtract(previousPoint).length();
  7027. return this;
  7028. };
  7029. /**
  7030. * 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.
  7031. * Returns the updated Path2.
  7032. */
  7033. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7034. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7035. if (this.closed) {
  7036. return this;
  7037. }
  7038. var startPoint = this._points[this._points.length - 1];
  7039. var midPoint = new Vector2(midX, midY);
  7040. var endPoint = new Vector2(endX, endY);
  7041. var arc = new Arc2(startPoint, midPoint, endPoint);
  7042. var increment = arc.angle.radians() / numberOfSegments;
  7043. if (arc.orientation === Orientation.CW)
  7044. increment *= -1;
  7045. var currentAngle = arc.startAngle.radians() + increment;
  7046. for (var i = 0; i < numberOfSegments; i++) {
  7047. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7048. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7049. this.addLineTo(x, y);
  7050. currentAngle += increment;
  7051. }
  7052. return this;
  7053. };
  7054. /**
  7055. * Closes the Path2.
  7056. * Returns the Path2.
  7057. */
  7058. Path2.prototype.close = function () {
  7059. this.closed = true;
  7060. return this;
  7061. };
  7062. /**
  7063. * Returns the Path2 total length (float).
  7064. */
  7065. Path2.prototype.length = function () {
  7066. var result = this._length;
  7067. if (!this.closed) {
  7068. var lastPoint = this._points[this._points.length - 1];
  7069. var firstPoint = this._points[0];
  7070. result += (firstPoint.subtract(lastPoint).length());
  7071. }
  7072. return result;
  7073. };
  7074. /**
  7075. * Returns the Path2 internal array of points.
  7076. */
  7077. Path2.prototype.getPoints = function () {
  7078. return this._points;
  7079. };
  7080. /**
  7081. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7082. */
  7083. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7084. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7085. return Vector2.Zero();
  7086. }
  7087. var lengthPosition = normalizedLengthPosition * this.length();
  7088. var previousOffset = 0;
  7089. for (var i = 0; i < this._points.length; i++) {
  7090. var j = (i + 1) % this._points.length;
  7091. var a = this._points[i];
  7092. var b = this._points[j];
  7093. var bToA = b.subtract(a);
  7094. var nextOffset = (bToA.length() + previousOffset);
  7095. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7096. var dir = bToA.normalize();
  7097. var localOffset = lengthPosition - previousOffset;
  7098. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7099. }
  7100. previousOffset = nextOffset;
  7101. }
  7102. return Vector2.Zero();
  7103. };
  7104. /**
  7105. * Returns a new Path2 starting at the coordinates (x, y).
  7106. */
  7107. Path2.StartingAt = function (x, y) {
  7108. return new Path2(x, y);
  7109. };
  7110. return Path2;
  7111. }());
  7112. BABYLON.Path2 = Path2;
  7113. var Path3D = /** @class */ (function () {
  7114. /**
  7115. * new Path3D(path, normal, raw)
  7116. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7117. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7118. * path : an array of Vector3, the curve axis of the Path3D
  7119. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7120. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7121. */
  7122. function Path3D(path, firstNormal, raw) {
  7123. if (firstNormal === void 0) { firstNormal = null; }
  7124. this.path = path;
  7125. this._curve = new Array();
  7126. this._distances = new Array();
  7127. this._tangents = new Array();
  7128. this._normals = new Array();
  7129. this._binormals = new Array();
  7130. for (var p = 0; p < path.length; p++) {
  7131. this._curve[p] = path[p].clone(); // hard copy
  7132. }
  7133. this._raw = raw || false;
  7134. this._compute(firstNormal);
  7135. }
  7136. /**
  7137. * Returns the Path3D array of successive Vector3 designing its curve.
  7138. */
  7139. Path3D.prototype.getCurve = function () {
  7140. return this._curve;
  7141. };
  7142. /**
  7143. * Returns an array populated with tangent vectors on each Path3D curve point.
  7144. */
  7145. Path3D.prototype.getTangents = function () {
  7146. return this._tangents;
  7147. };
  7148. /**
  7149. * Returns an array populated with normal vectors on each Path3D curve point.
  7150. */
  7151. Path3D.prototype.getNormals = function () {
  7152. return this._normals;
  7153. };
  7154. /**
  7155. * Returns an array populated with binormal vectors on each Path3D curve point.
  7156. */
  7157. Path3D.prototype.getBinormals = function () {
  7158. return this._binormals;
  7159. };
  7160. /**
  7161. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7162. */
  7163. Path3D.prototype.getDistances = function () {
  7164. return this._distances;
  7165. };
  7166. /**
  7167. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7168. * Returns the same object updated.
  7169. */
  7170. Path3D.prototype.update = function (path, firstNormal) {
  7171. if (firstNormal === void 0) { firstNormal = null; }
  7172. for (var p = 0; p < path.length; p++) {
  7173. this._curve[p].x = path[p].x;
  7174. this._curve[p].y = path[p].y;
  7175. this._curve[p].z = path[p].z;
  7176. }
  7177. this._compute(firstNormal);
  7178. return this;
  7179. };
  7180. // private function compute() : computes tangents, normals and binormals
  7181. Path3D.prototype._compute = function (firstNormal) {
  7182. var l = this._curve.length;
  7183. // first and last tangents
  7184. this._tangents[0] = this._getFirstNonNullVector(0);
  7185. if (!this._raw) {
  7186. this._tangents[0].normalize();
  7187. }
  7188. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7189. if (!this._raw) {
  7190. this._tangents[l - 1].normalize();
  7191. }
  7192. // normals and binormals at first point : arbitrary vector with _normalVector()
  7193. var tg0 = this._tangents[0];
  7194. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7195. this._normals[0] = pp0;
  7196. if (!this._raw) {
  7197. this._normals[0].normalize();
  7198. }
  7199. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7200. if (!this._raw) {
  7201. this._binormals[0].normalize();
  7202. }
  7203. this._distances[0] = 0.0;
  7204. // normals and binormals : next points
  7205. var prev; // previous vector (segment)
  7206. var cur; // current vector (segment)
  7207. var curTang; // current tangent
  7208. // previous normal
  7209. var prevBinor; // previous binormal
  7210. for (var i = 1; i < l; i++) {
  7211. // tangents
  7212. prev = this._getLastNonNullVector(i);
  7213. if (i < l - 1) {
  7214. cur = this._getFirstNonNullVector(i);
  7215. this._tangents[i] = prev.add(cur);
  7216. this._tangents[i].normalize();
  7217. }
  7218. this._distances[i] = this._distances[i - 1] + prev.length();
  7219. // normals and binormals
  7220. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7221. curTang = this._tangents[i];
  7222. prevBinor = this._binormals[i - 1];
  7223. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7224. if (!this._raw) {
  7225. this._normals[i].normalize();
  7226. }
  7227. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7228. if (!this._raw) {
  7229. this._binormals[i].normalize();
  7230. }
  7231. }
  7232. };
  7233. // private function getFirstNonNullVector(index)
  7234. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7235. Path3D.prototype._getFirstNonNullVector = function (index) {
  7236. var i = 1;
  7237. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7238. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7239. i++;
  7240. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7241. }
  7242. return nNVector;
  7243. };
  7244. // private function getLastNonNullVector(index)
  7245. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7246. Path3D.prototype._getLastNonNullVector = function (index) {
  7247. var i = 1;
  7248. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7249. while (nLVector.length() === 0 && index > i + 1) {
  7250. i++;
  7251. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7252. }
  7253. return nLVector;
  7254. };
  7255. // private function normalVector(v0, vt, va) :
  7256. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7257. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7258. Path3D.prototype._normalVector = function (v0, vt, va) {
  7259. var normal0;
  7260. var tgl = vt.length();
  7261. if (tgl === 0.0) {
  7262. tgl = 1.0;
  7263. }
  7264. if (va === undefined || va === null) {
  7265. var point;
  7266. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7267. point = new Vector3(0.0, -1.0, 0.0);
  7268. }
  7269. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7270. point = new Vector3(1.0, 0.0, 0.0);
  7271. }
  7272. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7273. point = new Vector3(0.0, 0.0, 1.0);
  7274. }
  7275. else {
  7276. point = Vector3.Zero();
  7277. }
  7278. normal0 = Vector3.Cross(vt, point);
  7279. }
  7280. else {
  7281. normal0 = Vector3.Cross(vt, va);
  7282. Vector3.CrossToRef(normal0, vt, normal0);
  7283. }
  7284. normal0.normalize();
  7285. return normal0;
  7286. };
  7287. return Path3D;
  7288. }());
  7289. BABYLON.Path3D = Path3D;
  7290. var Curve3 = /** @class */ (function () {
  7291. /**
  7292. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7293. * A Curve3 is designed from a series of successive Vector3.
  7294. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7295. */
  7296. function Curve3(points) {
  7297. this._length = 0.0;
  7298. this._points = points;
  7299. this._length = this._computeLength(points);
  7300. }
  7301. /**
  7302. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7303. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7304. * @param v1 (Vector3) the control point
  7305. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7306. * @param nbPoints (integer) the wanted number of points in the curve
  7307. */
  7308. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7309. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7310. var bez = new Array();
  7311. var equation = function (t, val0, val1, val2) {
  7312. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7313. return res;
  7314. };
  7315. for (var i = 0; i <= nbPoints; i++) {
  7316. 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)));
  7317. }
  7318. return new Curve3(bez);
  7319. };
  7320. /**
  7321. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7322. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7323. * @param v1 (Vector3) the first control point
  7324. * @param v2 (Vector3) the second control point
  7325. * @param v3 (Vector3) the end point of the Cubic Bezier
  7326. * @param nbPoints (integer) the wanted number of points in the curve
  7327. */
  7328. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7329. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7330. var bez = new Array();
  7331. var equation = function (t, val0, val1, val2, val3) {
  7332. 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;
  7333. return res;
  7334. };
  7335. for (var i = 0; i <= nbPoints; i++) {
  7336. 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)));
  7337. }
  7338. return new Curve3(bez);
  7339. };
  7340. /**
  7341. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7342. * @param p1 (Vector3) the origin point of the Hermite Spline
  7343. * @param t1 (Vector3) the tangent vector at the origin point
  7344. * @param p2 (Vector3) the end point of the Hermite Spline
  7345. * @param t2 (Vector3) the tangent vector at the end point
  7346. * @param nbPoints (integer) the wanted number of points in the curve
  7347. */
  7348. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7349. var hermite = new Array();
  7350. var step = 1.0 / nbPoints;
  7351. for (var i = 0; i <= nbPoints; i++) {
  7352. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7353. }
  7354. return new Curve3(hermite);
  7355. };
  7356. /**
  7357. * Returns a Curve3 object along a CatmullRom Spline curve :
  7358. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7359. * @param nbPoints (integer) the wanted number of points between each curve control points
  7360. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7361. */
  7362. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7363. var catmullRom = new Array();
  7364. var step = 1.0 / nbPoints;
  7365. var amount = 0.0;
  7366. if (closed) {
  7367. var pointsCount = points.length;
  7368. for (var i = 0; i < pointsCount; i++) {
  7369. amount = 0;
  7370. for (var c = 0; c < nbPoints; c++) {
  7371. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7372. amount += step;
  7373. }
  7374. }
  7375. catmullRom.push(catmullRom[0]);
  7376. }
  7377. else {
  7378. var totalPoints = new Array();
  7379. totalPoints.push(points[0].clone());
  7380. Array.prototype.push.apply(totalPoints, points);
  7381. totalPoints.push(points[points.length - 1].clone());
  7382. for (var i = 0; i < totalPoints.length - 3; i++) {
  7383. amount = 0;
  7384. for (var c = 0; c < nbPoints; c++) {
  7385. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7386. amount += step;
  7387. }
  7388. }
  7389. i--;
  7390. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7391. }
  7392. return new Curve3(catmullRom);
  7393. };
  7394. /**
  7395. * Returns the Curve3 stored array of successive Vector3
  7396. */
  7397. Curve3.prototype.getPoints = function () {
  7398. return this._points;
  7399. };
  7400. /**
  7401. * Returns the computed length (float) of the curve.
  7402. */
  7403. Curve3.prototype.length = function () {
  7404. return this._length;
  7405. };
  7406. /**
  7407. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7408. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7409. * curveA and curveB keep unchanged.
  7410. */
  7411. Curve3.prototype.continue = function (curve) {
  7412. var lastPoint = this._points[this._points.length - 1];
  7413. var continuedPoints = this._points.slice();
  7414. var curvePoints = curve.getPoints();
  7415. for (var i = 1; i < curvePoints.length; i++) {
  7416. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7417. }
  7418. var continuedCurve = new Curve3(continuedPoints);
  7419. return continuedCurve;
  7420. };
  7421. Curve3.prototype._computeLength = function (path) {
  7422. var l = 0;
  7423. for (var i = 1; i < path.length; i++) {
  7424. l += (path[i].subtract(path[i - 1])).length();
  7425. }
  7426. return l;
  7427. };
  7428. return Curve3;
  7429. }());
  7430. BABYLON.Curve3 = Curve3;
  7431. // Vertex formats
  7432. var PositionNormalVertex = /** @class */ (function () {
  7433. function PositionNormalVertex(position, normal) {
  7434. if (position === void 0) { position = Vector3.Zero(); }
  7435. if (normal === void 0) { normal = Vector3.Up(); }
  7436. this.position = position;
  7437. this.normal = normal;
  7438. }
  7439. PositionNormalVertex.prototype.clone = function () {
  7440. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7441. };
  7442. return PositionNormalVertex;
  7443. }());
  7444. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7445. var PositionNormalTextureVertex = /** @class */ (function () {
  7446. function PositionNormalTextureVertex(position, normal, uv) {
  7447. if (position === void 0) { position = Vector3.Zero(); }
  7448. if (normal === void 0) { normal = Vector3.Up(); }
  7449. if (uv === void 0) { uv = Vector2.Zero(); }
  7450. this.position = position;
  7451. this.normal = normal;
  7452. this.uv = uv;
  7453. }
  7454. PositionNormalTextureVertex.prototype.clone = function () {
  7455. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7456. };
  7457. return PositionNormalTextureVertex;
  7458. }());
  7459. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7460. // Temporary pre-allocated objects for engine internal use
  7461. // usage in any internal function :
  7462. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7463. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7464. var Tmp = /** @class */ (function () {
  7465. function Tmp() {
  7466. }
  7467. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7468. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7469. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7470. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7471. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7472. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7473. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7474. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7475. Matrix.Zero(), Matrix.Zero(),
  7476. Matrix.Zero(), Matrix.Zero(),
  7477. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7478. return Tmp;
  7479. }());
  7480. BABYLON.Tmp = Tmp;
  7481. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7482. var MathTmp = /** @class */ (function () {
  7483. function MathTmp() {
  7484. }
  7485. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7486. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7487. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7488. return MathTmp;
  7489. }());
  7490. })(BABYLON || (BABYLON = {}));
  7491. //# sourceMappingURL=babylon.math.js.map
  7492. var BABYLON;
  7493. (function (BABYLON) {
  7494. var Scalar = /** @class */ (function () {
  7495. function Scalar() {
  7496. }
  7497. /**
  7498. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7499. */
  7500. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7501. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7502. var num = a - b;
  7503. return -epsilon <= num && num <= epsilon;
  7504. };
  7505. /**
  7506. * Returns a string : the upper case translation of the number i to hexadecimal.
  7507. */
  7508. Scalar.ToHex = function (i) {
  7509. var str = i.toString(16);
  7510. if (i <= 15) {
  7511. return ("0" + str).toUpperCase();
  7512. }
  7513. return str.toUpperCase();
  7514. };
  7515. /**
  7516. * Returns -1 if value is negative and +1 is value is positive.
  7517. * Returns the value itself if it's equal to zero.
  7518. */
  7519. Scalar.Sign = function (value) {
  7520. value = +value; // convert to a number
  7521. if (value === 0 || isNaN(value))
  7522. return value;
  7523. return value > 0 ? 1 : -1;
  7524. };
  7525. /**
  7526. * Returns the value itself if it's between min and max.
  7527. * Returns min if the value is lower than min.
  7528. * Returns max if the value is greater than max.
  7529. */
  7530. Scalar.Clamp = function (value, min, max) {
  7531. if (min === void 0) { min = 0; }
  7532. if (max === void 0) { max = 1; }
  7533. return Math.min(max, Math.max(min, value));
  7534. };
  7535. /**
  7536. * Returns the log2 of value.
  7537. */
  7538. Scalar.Log2 = function (value) {
  7539. return Math.log(value) * Math.LOG2E;
  7540. };
  7541. /**
  7542. * Loops the value, so that it is never larger than length and never smaller than 0.
  7543. *
  7544. * This is similar to the modulo operator but it works with floating point numbers.
  7545. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7546. * With t = 5 and length = 2.5, the result would be 0.0.
  7547. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7548. */
  7549. Scalar.Repeat = function (value, length) {
  7550. return value - Math.floor(value / length) * length;
  7551. };
  7552. /**
  7553. * Normalize the value between 0.0 and 1.0 using min and max values
  7554. */
  7555. Scalar.Normalize = function (value, min, max) {
  7556. return (value - min) / (max - min);
  7557. };
  7558. /**
  7559. * Denormalize the value from 0.0 and 1.0 using min and max values
  7560. */
  7561. Scalar.Denormalize = function (normalized, min, max) {
  7562. return (normalized * (max - min) + min);
  7563. };
  7564. /**
  7565. * Calculates the shortest difference between two given angles given in degrees.
  7566. */
  7567. Scalar.DeltaAngle = function (current, target) {
  7568. var num = Scalar.Repeat(target - current, 360.0);
  7569. if (num > 180.0) {
  7570. num -= 360.0;
  7571. }
  7572. return num;
  7573. };
  7574. /**
  7575. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7576. *
  7577. * The returned value will move back and forth between 0 and length
  7578. */
  7579. Scalar.PingPong = function (tx, length) {
  7580. var t = Scalar.Repeat(tx, length * 2.0);
  7581. return length - Math.abs(t - length);
  7582. };
  7583. /**
  7584. * Interpolates between min and max with smoothing at the limits.
  7585. *
  7586. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7587. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7588. */
  7589. Scalar.SmoothStep = function (from, to, tx) {
  7590. var t = Scalar.Clamp(tx);
  7591. t = -2.0 * t * t * t + 3.0 * t * t;
  7592. return to * t + from * (1.0 - t);
  7593. };
  7594. /**
  7595. * Moves a value current towards target.
  7596. *
  7597. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7598. * Negative values of maxDelta pushes the value away from target.
  7599. */
  7600. Scalar.MoveTowards = function (current, target, maxDelta) {
  7601. var result = 0;
  7602. if (Math.abs(target - current) <= maxDelta) {
  7603. result = target;
  7604. }
  7605. else {
  7606. result = current + Scalar.Sign(target - current) * maxDelta;
  7607. }
  7608. return result;
  7609. };
  7610. /**
  7611. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7612. *
  7613. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7614. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7615. */
  7616. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7617. var num = Scalar.DeltaAngle(current, target);
  7618. var result = 0;
  7619. if (-maxDelta < num && num < maxDelta) {
  7620. result = target;
  7621. }
  7622. else {
  7623. target = current + num;
  7624. result = Scalar.MoveTowards(current, target, maxDelta);
  7625. }
  7626. return result;
  7627. };
  7628. /**
  7629. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7630. */
  7631. Scalar.Lerp = function (start, end, amount) {
  7632. return start + ((end - start) * amount);
  7633. };
  7634. /**
  7635. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7636. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7637. */
  7638. Scalar.LerpAngle = function (start, end, amount) {
  7639. var num = Scalar.Repeat(end - start, 360.0);
  7640. if (num > 180.0) {
  7641. num -= 360.0;
  7642. }
  7643. return start + num * Scalar.Clamp(amount);
  7644. };
  7645. /**
  7646. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7647. */
  7648. Scalar.InverseLerp = function (a, b, value) {
  7649. var result = 0;
  7650. if (a != b) {
  7651. result = Scalar.Clamp((value - a) / (b - a));
  7652. }
  7653. else {
  7654. result = 0.0;
  7655. }
  7656. return result;
  7657. };
  7658. /**
  7659. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7660. */
  7661. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7662. var squared = amount * amount;
  7663. var cubed = amount * squared;
  7664. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7665. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7666. var part3 = (cubed - (2.0 * squared)) + amount;
  7667. var part4 = cubed - squared;
  7668. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7669. };
  7670. /**
  7671. * Returns a random float number between and min and max values
  7672. */
  7673. Scalar.RandomRange = function (min, max) {
  7674. if (min === max)
  7675. return min;
  7676. return ((Math.random() * (max - min)) + min);
  7677. };
  7678. /**
  7679. * This function returns percentage of a number in a given range.
  7680. *
  7681. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7682. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7683. */
  7684. Scalar.RangeToPercent = function (number, min, max) {
  7685. return ((number - min) / (max - min));
  7686. };
  7687. /**
  7688. * This function returns number that corresponds to the percentage in a given range.
  7689. *
  7690. * PercentToRange(0.34,0,100) will return 34.
  7691. */
  7692. Scalar.PercentToRange = function (percent, min, max) {
  7693. return ((max - min) * percent + min);
  7694. };
  7695. /**
  7696. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7697. * @param angle The angle to normalize in radian.
  7698. * @return The converted angle.
  7699. */
  7700. Scalar.NormalizeRadians = function (angle) {
  7701. // More precise but slower version kept for reference.
  7702. // angle = angle % Tools.TwoPi;
  7703. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7704. //if (angle > Math.PI) {
  7705. // angle -= Tools.TwoPi;
  7706. //}
  7707. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7708. return angle;
  7709. };
  7710. /**
  7711. * Two pi constants convenient for computation.
  7712. */
  7713. Scalar.TwoPi = Math.PI * 2;
  7714. return Scalar;
  7715. }());
  7716. BABYLON.Scalar = Scalar;
  7717. })(BABYLON || (BABYLON = {}));
  7718. //# sourceMappingURL=babylon.math.scalar.js.map
  7719. //# sourceMappingURL=babylon.mixins.js.map
  7720. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7721. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7722. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7723. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7724. //# sourceMappingURL=babylon.webgl2.js.map
  7725. var BABYLON;
  7726. (function (BABYLON) {
  7727. var __decoratorInitialStore = {};
  7728. var __mergedStore = {};
  7729. var _copySource = function (creationFunction, source, instanciate) {
  7730. var destination = creationFunction();
  7731. // Tags
  7732. if (BABYLON.Tags) {
  7733. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7734. }
  7735. var classStore = getMergedStore(destination);
  7736. // Properties
  7737. for (var property in classStore) {
  7738. var propertyDescriptor = classStore[property];
  7739. var sourceProperty = source[property];
  7740. var propertyType = propertyDescriptor.type;
  7741. if (sourceProperty !== undefined && sourceProperty !== null) {
  7742. switch (propertyType) {
  7743. case 0: // Value
  7744. case 6: // Mesh reference
  7745. case 11: // Camera reference
  7746. destination[property] = sourceProperty;
  7747. break;
  7748. case 1: // Texture
  7749. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7750. break;
  7751. case 2: // Color3
  7752. case 3: // FresnelParameters
  7753. case 4: // Vector2
  7754. case 5: // Vector3
  7755. case 7: // Color Curves
  7756. case 10: // Quaternion
  7757. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7758. break;
  7759. }
  7760. }
  7761. }
  7762. return destination;
  7763. };
  7764. function getDirectStore(target) {
  7765. var classKey = target.getClassName();
  7766. if (!__decoratorInitialStore[classKey]) {
  7767. __decoratorInitialStore[classKey] = {};
  7768. }
  7769. return __decoratorInitialStore[classKey];
  7770. }
  7771. /**
  7772. * Return the list of properties flagged as serializable
  7773. * @param target: host object
  7774. */
  7775. function getMergedStore(target) {
  7776. var classKey = target.getClassName();
  7777. if (__mergedStore[classKey]) {
  7778. return __mergedStore[classKey];
  7779. }
  7780. __mergedStore[classKey] = {};
  7781. var store = __mergedStore[classKey];
  7782. var currentTarget = target;
  7783. var currentKey = classKey;
  7784. while (currentKey) {
  7785. var initialStore = __decoratorInitialStore[currentKey];
  7786. for (var property in initialStore) {
  7787. store[property] = initialStore[property];
  7788. }
  7789. var parent_1 = void 0;
  7790. var done = false;
  7791. do {
  7792. parent_1 = Object.getPrototypeOf(currentTarget);
  7793. if (!parent_1.getClassName) {
  7794. done = true;
  7795. break;
  7796. }
  7797. if (parent_1.getClassName() !== currentKey) {
  7798. break;
  7799. }
  7800. currentTarget = parent_1;
  7801. } while (parent_1);
  7802. if (done) {
  7803. break;
  7804. }
  7805. currentKey = parent_1.getClassName();
  7806. currentTarget = parent_1;
  7807. }
  7808. return store;
  7809. }
  7810. function generateSerializableMember(type, sourceName) {
  7811. return function (target, propertyKey) {
  7812. var classStore = getDirectStore(target);
  7813. if (!classStore[propertyKey]) {
  7814. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7815. }
  7816. };
  7817. }
  7818. function generateExpandMember(setCallback, targetKey) {
  7819. if (targetKey === void 0) { targetKey = null; }
  7820. return function (target, propertyKey) {
  7821. var key = targetKey || ("_" + propertyKey);
  7822. Object.defineProperty(target, propertyKey, {
  7823. get: function () {
  7824. return this[key];
  7825. },
  7826. set: function (value) {
  7827. if (this[key] === value) {
  7828. return;
  7829. }
  7830. this[key] = value;
  7831. target[setCallback].apply(this);
  7832. },
  7833. enumerable: true,
  7834. configurable: true
  7835. });
  7836. };
  7837. }
  7838. function expandToProperty(callback, targetKey) {
  7839. if (targetKey === void 0) { targetKey = null; }
  7840. return generateExpandMember(callback, targetKey);
  7841. }
  7842. BABYLON.expandToProperty = expandToProperty;
  7843. function serialize(sourceName) {
  7844. return generateSerializableMember(0, sourceName); // value member
  7845. }
  7846. BABYLON.serialize = serialize;
  7847. function serializeAsTexture(sourceName) {
  7848. return generateSerializableMember(1, sourceName); // texture member
  7849. }
  7850. BABYLON.serializeAsTexture = serializeAsTexture;
  7851. function serializeAsColor3(sourceName) {
  7852. return generateSerializableMember(2, sourceName); // color3 member
  7853. }
  7854. BABYLON.serializeAsColor3 = serializeAsColor3;
  7855. function serializeAsFresnelParameters(sourceName) {
  7856. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7857. }
  7858. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7859. function serializeAsVector2(sourceName) {
  7860. return generateSerializableMember(4, sourceName); // vector2 member
  7861. }
  7862. BABYLON.serializeAsVector2 = serializeAsVector2;
  7863. function serializeAsVector3(sourceName) {
  7864. return generateSerializableMember(5, sourceName); // vector3 member
  7865. }
  7866. BABYLON.serializeAsVector3 = serializeAsVector3;
  7867. function serializeAsMeshReference(sourceName) {
  7868. return generateSerializableMember(6, sourceName); // mesh reference member
  7869. }
  7870. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7871. function serializeAsColorCurves(sourceName) {
  7872. return generateSerializableMember(7, sourceName); // color curves
  7873. }
  7874. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7875. function serializeAsColor4(sourceName) {
  7876. return generateSerializableMember(8, sourceName); // color 4
  7877. }
  7878. BABYLON.serializeAsColor4 = serializeAsColor4;
  7879. function serializeAsImageProcessingConfiguration(sourceName) {
  7880. return generateSerializableMember(9, sourceName); // image processing
  7881. }
  7882. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7883. function serializeAsQuaternion(sourceName) {
  7884. return generateSerializableMember(10, sourceName); // quaternion member
  7885. }
  7886. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7887. /**
  7888. * Decorator used to define property that can be serialized as reference to a camera
  7889. * @param sourceName defines the name of the property to decorate
  7890. */
  7891. function serializeAsCameraReference(sourceName) {
  7892. return generateSerializableMember(11, sourceName); // camera reference member
  7893. }
  7894. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7895. var SerializationHelper = /** @class */ (function () {
  7896. function SerializationHelper() {
  7897. }
  7898. SerializationHelper.Serialize = function (entity, serializationObject) {
  7899. if (!serializationObject) {
  7900. serializationObject = {};
  7901. }
  7902. // Tags
  7903. if (BABYLON.Tags) {
  7904. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7905. }
  7906. var serializedProperties = getMergedStore(entity);
  7907. // Properties
  7908. for (var property in serializedProperties) {
  7909. var propertyDescriptor = serializedProperties[property];
  7910. var targetPropertyName = propertyDescriptor.sourceName || property;
  7911. var propertyType = propertyDescriptor.type;
  7912. var sourceProperty = entity[property];
  7913. if (sourceProperty !== undefined && sourceProperty !== null) {
  7914. switch (propertyType) {
  7915. case 0: // Value
  7916. serializationObject[targetPropertyName] = sourceProperty;
  7917. break;
  7918. case 1: // Texture
  7919. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7920. break;
  7921. case 2: // Color3
  7922. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7923. break;
  7924. case 3: // FresnelParameters
  7925. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7926. break;
  7927. case 4: // Vector2
  7928. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7929. break;
  7930. case 5: // Vector3
  7931. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7932. break;
  7933. case 6: // Mesh reference
  7934. serializationObject[targetPropertyName] = sourceProperty.id;
  7935. break;
  7936. case 7: // Color Curves
  7937. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7938. break;
  7939. case 8: // Color 4
  7940. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7941. break;
  7942. case 9: // Image Processing
  7943. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7944. break;
  7945. case 10: // Quaternion
  7946. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7947. break;
  7948. case 11: // Camera reference
  7949. serializationObject[targetPropertyName] = sourceProperty.id;
  7950. break;
  7951. }
  7952. }
  7953. }
  7954. return serializationObject;
  7955. };
  7956. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7957. if (rootUrl === void 0) { rootUrl = null; }
  7958. var destination = creationFunction();
  7959. if (!rootUrl) {
  7960. rootUrl = "";
  7961. }
  7962. // Tags
  7963. if (BABYLON.Tags) {
  7964. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7965. }
  7966. var classStore = getMergedStore(destination);
  7967. // Properties
  7968. for (var property in classStore) {
  7969. var propertyDescriptor = classStore[property];
  7970. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7971. var propertyType = propertyDescriptor.type;
  7972. if (sourceProperty !== undefined && sourceProperty !== null) {
  7973. var dest = destination;
  7974. switch (propertyType) {
  7975. case 0: // Value
  7976. dest[property] = sourceProperty;
  7977. break;
  7978. case 1: // Texture
  7979. if (scene) {
  7980. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7981. }
  7982. break;
  7983. case 2: // Color3
  7984. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7985. break;
  7986. case 3: // FresnelParameters
  7987. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7988. break;
  7989. case 4: // Vector2
  7990. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7991. break;
  7992. case 5: // Vector3
  7993. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7994. break;
  7995. case 6: // Mesh reference
  7996. if (scene) {
  7997. dest[property] = scene.getLastMeshByID(sourceProperty);
  7998. }
  7999. break;
  8000. case 7: // Color Curves
  8001. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8002. break;
  8003. case 8: // Color 4
  8004. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8005. break;
  8006. case 9: // Image Processing
  8007. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8008. break;
  8009. case 10: // Quaternion
  8010. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8011. break;
  8012. case 11: // Camera reference
  8013. if (scene) {
  8014. dest[property] = scene.getCameraByID(sourceProperty);
  8015. }
  8016. break;
  8017. }
  8018. }
  8019. }
  8020. return destination;
  8021. };
  8022. SerializationHelper.Clone = function (creationFunction, source) {
  8023. return _copySource(creationFunction, source, false);
  8024. };
  8025. SerializationHelper.Instanciate = function (creationFunction, source) {
  8026. return _copySource(creationFunction, source, true);
  8027. };
  8028. return SerializationHelper;
  8029. }());
  8030. BABYLON.SerializationHelper = SerializationHelper;
  8031. })(BABYLON || (BABYLON = {}));
  8032. //# sourceMappingURL=babylon.decorators.js.map
  8033. var BABYLON;
  8034. (function (BABYLON) {
  8035. /**
  8036. * Wrapper class for promise with external resolve and reject.
  8037. */
  8038. var Deferred = /** @class */ (function () {
  8039. /**
  8040. * Constructor for this deferred object.
  8041. */
  8042. function Deferred() {
  8043. var _this = this;
  8044. this.promise = new Promise(function (resolve, reject) {
  8045. _this._resolve = resolve;
  8046. _this._reject = reject;
  8047. });
  8048. }
  8049. Object.defineProperty(Deferred.prototype, "resolve", {
  8050. /**
  8051. * The resolve method of the promise associated with this deferred object.
  8052. */
  8053. get: function () {
  8054. return this._resolve;
  8055. },
  8056. enumerable: true,
  8057. configurable: true
  8058. });
  8059. Object.defineProperty(Deferred.prototype, "reject", {
  8060. /**
  8061. * The reject method of the promise associated with this deferred object.
  8062. */
  8063. get: function () {
  8064. return this._reject;
  8065. },
  8066. enumerable: true,
  8067. configurable: true
  8068. });
  8069. return Deferred;
  8070. }());
  8071. BABYLON.Deferred = Deferred;
  8072. })(BABYLON || (BABYLON = {}));
  8073. //# sourceMappingURL=babylon.deferred.js.map
  8074. var BABYLON;
  8075. (function (BABYLON) {
  8076. /**
  8077. * A class serves as a medium between the observable and its observers
  8078. */
  8079. var EventState = /** @class */ (function () {
  8080. /**
  8081. * Create a new EventState
  8082. * @param mask defines the mask associated with this state
  8083. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8084. * @param target defines the original target of the state
  8085. * @param currentTarget defines the current target of the state
  8086. */
  8087. function EventState(mask, skipNextObservers, target, currentTarget) {
  8088. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8089. this.initalize(mask, skipNextObservers, target, currentTarget);
  8090. }
  8091. /**
  8092. * Initialize the current event state
  8093. * @param mask defines the mask associated with this state
  8094. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8095. * @param target defines the original target of the state
  8096. * @param currentTarget defines the current target of the state
  8097. * @returns the current event state
  8098. */
  8099. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8100. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8101. this.mask = mask;
  8102. this.skipNextObservers = skipNextObservers;
  8103. this.target = target;
  8104. this.currentTarget = currentTarget;
  8105. return this;
  8106. };
  8107. return EventState;
  8108. }());
  8109. BABYLON.EventState = EventState;
  8110. /**
  8111. * Represent an Observer registered to a given Observable object.
  8112. */
  8113. var Observer = /** @class */ (function () {
  8114. /**
  8115. * Creates a new observer
  8116. * @param callback defines the callback to call when the observer is notified
  8117. * @param mask defines the mask of the observer (used to filter notifications)
  8118. * @param scope defines the current scope used to restore the JS context
  8119. */
  8120. function Observer(
  8121. /**
  8122. * Defines the callback to call when the observer is notified
  8123. */
  8124. callback,
  8125. /**
  8126. * Defines the mask of the observer (used to filter notifications)
  8127. */
  8128. mask,
  8129. /**
  8130. * Defines the current scope used to restore the JS context
  8131. */
  8132. scope) {
  8133. if (scope === void 0) { scope = null; }
  8134. this.callback = callback;
  8135. this.mask = mask;
  8136. this.scope = scope;
  8137. /** @hidden */
  8138. this._willBeUnregistered = false;
  8139. /**
  8140. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8141. */
  8142. this.unregisterOnNextCall = false;
  8143. }
  8144. return Observer;
  8145. }());
  8146. BABYLON.Observer = Observer;
  8147. /**
  8148. * Represent a list of observers registered to multiple Observables object.
  8149. */
  8150. var MultiObserver = /** @class */ (function () {
  8151. function MultiObserver() {
  8152. }
  8153. /**
  8154. * Release associated resources
  8155. */
  8156. MultiObserver.prototype.dispose = function () {
  8157. if (this._observers && this._observables) {
  8158. for (var index = 0; index < this._observers.length; index++) {
  8159. this._observables[index].remove(this._observers[index]);
  8160. }
  8161. }
  8162. this._observers = null;
  8163. this._observables = null;
  8164. };
  8165. /**
  8166. * Raise a callback when one of the observable will notify
  8167. * @param observables defines a list of observables to watch
  8168. * @param callback defines the callback to call on notification
  8169. * @param mask defines the mask used to filter notifications
  8170. * @param scope defines the current scope used to restore the JS context
  8171. * @returns the new MultiObserver
  8172. */
  8173. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8174. if (mask === void 0) { mask = -1; }
  8175. if (scope === void 0) { scope = null; }
  8176. var result = new MultiObserver();
  8177. result._observers = new Array();
  8178. result._observables = observables;
  8179. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8180. var observable = observables_1[_i];
  8181. var observer = observable.add(callback, mask, false, scope);
  8182. if (observer) {
  8183. result._observers.push(observer);
  8184. }
  8185. }
  8186. return result;
  8187. };
  8188. return MultiObserver;
  8189. }());
  8190. BABYLON.MultiObserver = MultiObserver;
  8191. /**
  8192. * The Observable class is a simple implementation of the Observable pattern.
  8193. *
  8194. * 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.
  8195. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8196. * 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).
  8197. * 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.
  8198. */
  8199. var Observable = /** @class */ (function () {
  8200. /**
  8201. * Creates a new observable
  8202. * @param onObserverAdded defines a callback to call when a new observer is added
  8203. */
  8204. function Observable(onObserverAdded) {
  8205. this._observers = new Array();
  8206. this._eventState = new EventState(0);
  8207. if (onObserverAdded) {
  8208. this._onObserverAdded = onObserverAdded;
  8209. }
  8210. }
  8211. /**
  8212. * Create a new Observer with the specified callback
  8213. * @param callback the callback that will be executed for that Observer
  8214. * @param mask the mask used to filter observers
  8215. * @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.
  8216. * @param scope optional scope for the callback to be called from
  8217. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8218. * @returns the new observer created for the callback
  8219. */
  8220. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8221. if (mask === void 0) { mask = -1; }
  8222. if (insertFirst === void 0) { insertFirst = false; }
  8223. if (scope === void 0) { scope = null; }
  8224. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8225. if (!callback) {
  8226. return null;
  8227. }
  8228. var observer = new Observer(callback, mask, scope);
  8229. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8230. if (insertFirst) {
  8231. this._observers.unshift(observer);
  8232. }
  8233. else {
  8234. this._observers.push(observer);
  8235. }
  8236. if (this._onObserverAdded) {
  8237. this._onObserverAdded(observer);
  8238. }
  8239. return observer;
  8240. };
  8241. /**
  8242. * Create a new Observer with the specified callback and unregisters after the next notification
  8243. * @param callback the callback that will be executed for that Observer
  8244. * @returns the new observer created for the callback
  8245. */
  8246. Observable.prototype.addOnce = function (callback) {
  8247. return this.add(callback, undefined, undefined, undefined, true);
  8248. };
  8249. /**
  8250. * Remove an Observer from the Observable object
  8251. * @param observer the instance of the Observer to remove
  8252. * @returns false if it doesn't belong to this Observable
  8253. */
  8254. Observable.prototype.remove = function (observer) {
  8255. if (!observer) {
  8256. return false;
  8257. }
  8258. var index = this._observers.indexOf(observer);
  8259. if (index !== -1) {
  8260. this._deferUnregister(observer);
  8261. return true;
  8262. }
  8263. return false;
  8264. };
  8265. /**
  8266. * Remove a callback from the Observable object
  8267. * @param callback the callback to remove
  8268. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8269. * @returns false if it doesn't belong to this Observable
  8270. */
  8271. Observable.prototype.removeCallback = function (callback, scope) {
  8272. for (var index = 0; index < this._observers.length; index++) {
  8273. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8274. this._deferUnregister(this._observers[index]);
  8275. return true;
  8276. }
  8277. }
  8278. return false;
  8279. };
  8280. Observable.prototype._deferUnregister = function (observer) {
  8281. var _this = this;
  8282. observer.unregisterOnNextCall = false;
  8283. observer._willBeUnregistered = true;
  8284. BABYLON.Tools.SetImmediate(function () {
  8285. _this._remove(observer);
  8286. });
  8287. };
  8288. // This should only be called when not iterating over _observers to avoid callback skipping.
  8289. // Removes an observer from the _observer Array.
  8290. Observable.prototype._remove = function (observer) {
  8291. if (!observer) {
  8292. return false;
  8293. }
  8294. var index = this._observers.indexOf(observer);
  8295. if (index !== -1) {
  8296. this._observers.splice(index, 1);
  8297. return true;
  8298. }
  8299. return false;
  8300. };
  8301. /**
  8302. * Notify all Observers by calling their respective callback with the given data
  8303. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8304. * @param eventData defines the data to send to all observers
  8305. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8306. * @param target defines the original target of the state
  8307. * @param currentTarget defines the current target of the state
  8308. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8309. */
  8310. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8311. if (mask === void 0) { mask = -1; }
  8312. if (!this._observers.length) {
  8313. return true;
  8314. }
  8315. var state = this._eventState;
  8316. state.mask = mask;
  8317. state.target = target;
  8318. state.currentTarget = currentTarget;
  8319. state.skipNextObservers = false;
  8320. state.lastReturnValue = eventData;
  8321. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8322. var obs = _a[_i];
  8323. if (obs._willBeUnregistered) {
  8324. continue;
  8325. }
  8326. if (obs.mask & mask) {
  8327. if (obs.scope) {
  8328. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8329. }
  8330. else {
  8331. state.lastReturnValue = obs.callback(eventData, state);
  8332. }
  8333. if (obs.unregisterOnNextCall) {
  8334. this._deferUnregister(obs);
  8335. }
  8336. }
  8337. if (state.skipNextObservers) {
  8338. return false;
  8339. }
  8340. }
  8341. return true;
  8342. };
  8343. /**
  8344. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8345. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8346. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8347. * and it is crucial that all callbacks will be executed.
  8348. * The order of the callbacks is kept, callbacks are not executed parallel.
  8349. *
  8350. * @param eventData The data to be sent to each callback
  8351. * @param mask is used to filter observers defaults to -1
  8352. * @param target defines the callback target (see EventState)
  8353. * @param currentTarget defines he current object in the bubbling phase
  8354. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8355. */
  8356. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8357. var _this = this;
  8358. if (mask === void 0) { mask = -1; }
  8359. // create an empty promise
  8360. var p = Promise.resolve(eventData);
  8361. // no observers? return this promise.
  8362. if (!this._observers.length) {
  8363. return p;
  8364. }
  8365. var state = this._eventState;
  8366. state.mask = mask;
  8367. state.target = target;
  8368. state.currentTarget = currentTarget;
  8369. state.skipNextObservers = false;
  8370. // execute one callback after another (not using Promise.all, the order is important)
  8371. this._observers.forEach(function (obs) {
  8372. if (state.skipNextObservers) {
  8373. return;
  8374. }
  8375. if (obs._willBeUnregistered) {
  8376. return;
  8377. }
  8378. if (obs.mask & mask) {
  8379. if (obs.scope) {
  8380. p = p.then(function (lastReturnedValue) {
  8381. state.lastReturnValue = lastReturnedValue;
  8382. return obs.callback.apply(obs.scope, [eventData, state]);
  8383. });
  8384. }
  8385. else {
  8386. p = p.then(function (lastReturnedValue) {
  8387. state.lastReturnValue = lastReturnedValue;
  8388. return obs.callback(eventData, state);
  8389. });
  8390. }
  8391. if (obs.unregisterOnNextCall) {
  8392. _this._deferUnregister(obs);
  8393. }
  8394. }
  8395. });
  8396. // return the eventData
  8397. return p.then(function () { return eventData; });
  8398. };
  8399. /**
  8400. * Notify a specific observer
  8401. * @param observer defines the observer to notify
  8402. * @param eventData defines the data to be sent to each callback
  8403. * @param mask is used to filter observers defaults to -1
  8404. */
  8405. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8406. if (mask === void 0) { mask = -1; }
  8407. var state = this._eventState;
  8408. state.mask = mask;
  8409. state.skipNextObservers = false;
  8410. observer.callback(eventData, state);
  8411. };
  8412. /**
  8413. * Gets a boolean indicating if the observable has at least one observer
  8414. * @returns true is the Observable has at least one Observer registered
  8415. */
  8416. Observable.prototype.hasObservers = function () {
  8417. return this._observers.length > 0;
  8418. };
  8419. /**
  8420. * Clear the list of observers
  8421. */
  8422. Observable.prototype.clear = function () {
  8423. this._observers = new Array();
  8424. this._onObserverAdded = null;
  8425. };
  8426. /**
  8427. * Clone the current observable
  8428. * @returns a new observable
  8429. */
  8430. Observable.prototype.clone = function () {
  8431. var result = new Observable();
  8432. result._observers = this._observers.slice(0);
  8433. return result;
  8434. };
  8435. /**
  8436. * Does this observable handles observer registered with a given mask
  8437. * @param mask defines the mask to be tested
  8438. * @return whether or not one observer registered with the given mask is handeled
  8439. **/
  8440. Observable.prototype.hasSpecificMask = function (mask) {
  8441. if (mask === void 0) { mask = -1; }
  8442. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8443. var obs = _a[_i];
  8444. if (obs.mask & mask || obs.mask === mask) {
  8445. return true;
  8446. }
  8447. }
  8448. return false;
  8449. };
  8450. return Observable;
  8451. }());
  8452. BABYLON.Observable = Observable;
  8453. })(BABYLON || (BABYLON = {}));
  8454. //# sourceMappingURL=babylon.observable.js.map
  8455. var BABYLON;
  8456. (function (BABYLON) {
  8457. var SmartArray = /** @class */ (function () {
  8458. function SmartArray(capacity) {
  8459. this.length = 0;
  8460. this.data = new Array(capacity);
  8461. this._id = SmartArray._GlobalId++;
  8462. }
  8463. SmartArray.prototype.push = function (value) {
  8464. this.data[this.length++] = value;
  8465. if (this.length > this.data.length) {
  8466. this.data.length *= 2;
  8467. }
  8468. };
  8469. SmartArray.prototype.forEach = function (func) {
  8470. for (var index = 0; index < this.length; index++) {
  8471. func(this.data[index]);
  8472. }
  8473. };
  8474. SmartArray.prototype.sort = function (compareFn) {
  8475. this.data.sort(compareFn);
  8476. };
  8477. SmartArray.prototype.reset = function () {
  8478. this.length = 0;
  8479. };
  8480. SmartArray.prototype.dispose = function () {
  8481. this.reset();
  8482. if (this.data) {
  8483. this.data.length = 0;
  8484. this.data = [];
  8485. }
  8486. };
  8487. SmartArray.prototype.concat = function (array) {
  8488. if (array.length === 0) {
  8489. return;
  8490. }
  8491. if (this.length + array.length > this.data.length) {
  8492. this.data.length = (this.length + array.length) * 2;
  8493. }
  8494. for (var index = 0; index < array.length; index++) {
  8495. this.data[this.length++] = (array.data || array)[index];
  8496. }
  8497. };
  8498. SmartArray.prototype.indexOf = function (value) {
  8499. var position = this.data.indexOf(value);
  8500. if (position >= this.length) {
  8501. return -1;
  8502. }
  8503. return position;
  8504. };
  8505. SmartArray.prototype.contains = function (value) {
  8506. return this.data.indexOf(value) !== -1;
  8507. };
  8508. // Statics
  8509. SmartArray._GlobalId = 0;
  8510. return SmartArray;
  8511. }());
  8512. BABYLON.SmartArray = SmartArray;
  8513. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8514. __extends(SmartArrayNoDuplicate, _super);
  8515. function SmartArrayNoDuplicate() {
  8516. var _this = _super !== null && _super.apply(this, arguments) || this;
  8517. _this._duplicateId = 0;
  8518. return _this;
  8519. }
  8520. SmartArrayNoDuplicate.prototype.push = function (value) {
  8521. _super.prototype.push.call(this, value);
  8522. if (!value.__smartArrayFlags) {
  8523. value.__smartArrayFlags = {};
  8524. }
  8525. value.__smartArrayFlags[this._id] = this._duplicateId;
  8526. };
  8527. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8528. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8529. return false;
  8530. }
  8531. this.push(value);
  8532. return true;
  8533. };
  8534. SmartArrayNoDuplicate.prototype.reset = function () {
  8535. _super.prototype.reset.call(this);
  8536. this._duplicateId++;
  8537. };
  8538. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8539. if (array.length === 0) {
  8540. return;
  8541. }
  8542. if (this.length + array.length > this.data.length) {
  8543. this.data.length = (this.length + array.length) * 2;
  8544. }
  8545. for (var index = 0; index < array.length; index++) {
  8546. var item = (array.data || array)[index];
  8547. this.pushNoDuplicate(item);
  8548. }
  8549. };
  8550. return SmartArrayNoDuplicate;
  8551. }(SmartArray));
  8552. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8553. })(BABYLON || (BABYLON = {}));
  8554. //# sourceMappingURL=babylon.smartArray.js.map
  8555. var BABYLON;
  8556. (function (BABYLON) {
  8557. /** Class used to store color gradient */
  8558. var ColorGradient = /** @class */ (function () {
  8559. function ColorGradient() {
  8560. }
  8561. /**
  8562. * Will get a color picked randomly between color1 and color2.
  8563. * If color2 is undefined then color1 will be used
  8564. * @param result defines the target Color4 to store the result in
  8565. */
  8566. ColorGradient.prototype.getColorToRef = function (result) {
  8567. if (!this.color2) {
  8568. result.copyFrom(this.color1);
  8569. return;
  8570. }
  8571. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8572. };
  8573. return ColorGradient;
  8574. }());
  8575. BABYLON.ColorGradient = ColorGradient;
  8576. /** Class used to store factor gradient */
  8577. var FactorGradient = /** @class */ (function () {
  8578. function FactorGradient() {
  8579. }
  8580. /**
  8581. * Will get a number picked randomly between factor1 and factor2.
  8582. * If factor2 is undefined then factor1 will be used
  8583. * @returns the picked number
  8584. */
  8585. FactorGradient.prototype.getFactor = function () {
  8586. if (this.factor2 === undefined) {
  8587. return this.factor1;
  8588. }
  8589. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8590. };
  8591. return FactorGradient;
  8592. }());
  8593. BABYLON.FactorGradient = FactorGradient;
  8594. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8595. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8596. var LoadFileError = /** @class */ (function (_super) {
  8597. __extends(LoadFileError, _super);
  8598. function LoadFileError(message, request) {
  8599. var _this = _super.call(this, message) || this;
  8600. _this.request = request;
  8601. _this.name = "LoadFileError";
  8602. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8603. return _this;
  8604. }
  8605. // Polyfill for Object.setPrototypeOf if necessary.
  8606. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8607. return LoadFileError;
  8608. }(Error));
  8609. BABYLON.LoadFileError = LoadFileError;
  8610. var RetryStrategy = /** @class */ (function () {
  8611. function RetryStrategy() {
  8612. }
  8613. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8614. if (maxRetries === void 0) { maxRetries = 3; }
  8615. if (baseInterval === void 0) { baseInterval = 500; }
  8616. return function (url, request, retryIndex) {
  8617. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8618. return -1;
  8619. }
  8620. return Math.pow(2, retryIndex) * baseInterval;
  8621. };
  8622. };
  8623. return RetryStrategy;
  8624. }());
  8625. BABYLON.RetryStrategy = RetryStrategy;
  8626. // Screenshots
  8627. var screenshotCanvas;
  8628. var cloneValue = function (source, destinationObject) {
  8629. if (!source)
  8630. return null;
  8631. if (source instanceof BABYLON.Mesh) {
  8632. return null;
  8633. }
  8634. if (source instanceof BABYLON.SubMesh) {
  8635. return source.clone(destinationObject);
  8636. }
  8637. else if (source.clone) {
  8638. return source.clone();
  8639. }
  8640. return null;
  8641. };
  8642. var Tools = /** @class */ (function () {
  8643. function Tools() {
  8644. }
  8645. /**
  8646. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8647. * @param u defines the coordinate on X axis
  8648. * @param v defines the coordinate on Y axis
  8649. * @param width defines the width of the source data
  8650. * @param height defines the height of the source data
  8651. * @param pixels defines the source byte array
  8652. * @param color defines the output color
  8653. */
  8654. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8655. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8656. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8657. var position = (wrappedU + wrappedV * width) * 4;
  8658. color.r = pixels[position] / 255;
  8659. color.g = pixels[position + 1] / 255;
  8660. color.b = pixels[position + 2] / 255;
  8661. color.a = pixels[position + 3] / 255;
  8662. };
  8663. /**
  8664. * Interpolates between a and b via alpha
  8665. * @param a The lower value (returned when alpha = 0)
  8666. * @param b The upper value (returned when alpha = 1)
  8667. * @param alpha The interpolation-factor
  8668. * @return The mixed value
  8669. */
  8670. Tools.Mix = function (a, b, alpha) {
  8671. return a * (1 - alpha) + b * alpha;
  8672. };
  8673. Tools.Instantiate = function (className) {
  8674. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8675. return Tools.RegisteredExternalClasses[className];
  8676. }
  8677. var arr = className.split(".");
  8678. var fn = (window || this);
  8679. for (var i = 0, len = arr.length; i < len; i++) {
  8680. fn = fn[arr[i]];
  8681. }
  8682. if (typeof fn !== "function") {
  8683. return null;
  8684. }
  8685. return fn;
  8686. };
  8687. /**
  8688. * Provides a slice function that will work even on IE
  8689. * @param data defines the array to slice
  8690. * @param start defines the start of the data (optional)
  8691. * @param end defines the end of the data (optional)
  8692. * @returns the new sliced array
  8693. */
  8694. Tools.Slice = function (data, start, end) {
  8695. if (data.slice) {
  8696. return data.slice(start, end);
  8697. }
  8698. return Array.prototype.slice.call(data, start, end);
  8699. };
  8700. Tools.SetImmediate = function (action) {
  8701. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8702. window.setImmediate(action);
  8703. }
  8704. else {
  8705. setTimeout(action, 1);
  8706. }
  8707. };
  8708. Tools.IsExponentOfTwo = function (value) {
  8709. var count = 1;
  8710. do {
  8711. count *= 2;
  8712. } while (count < value);
  8713. return count === value;
  8714. };
  8715. /**
  8716. * Returns the nearest 32-bit single precision float representation of a Number
  8717. * @param value A Number. If the parameter is of a different type, it will get converted
  8718. * to a number or to NaN if it cannot be converted
  8719. * @returns number
  8720. */
  8721. Tools.FloatRound = function (value) {
  8722. if (Math.fround) {
  8723. return Math.fround(value);
  8724. }
  8725. return (Tools._tmpFloatArray[0] = value);
  8726. };
  8727. /**
  8728. * Find the next highest power of two.
  8729. * @param x Number to start search from.
  8730. * @return Next highest power of two.
  8731. */
  8732. Tools.CeilingPOT = function (x) {
  8733. x--;
  8734. x |= x >> 1;
  8735. x |= x >> 2;
  8736. x |= x >> 4;
  8737. x |= x >> 8;
  8738. x |= x >> 16;
  8739. x++;
  8740. return x;
  8741. };
  8742. /**
  8743. * Find the next lowest power of two.
  8744. * @param x Number to start search from.
  8745. * @return Next lowest power of two.
  8746. */
  8747. Tools.FloorPOT = function (x) {
  8748. x = x | (x >> 1);
  8749. x = x | (x >> 2);
  8750. x = x | (x >> 4);
  8751. x = x | (x >> 8);
  8752. x = x | (x >> 16);
  8753. return x - (x >> 1);
  8754. };
  8755. /**
  8756. * Find the nearest power of two.
  8757. * @param x Number to start search from.
  8758. * @return Next nearest power of two.
  8759. */
  8760. Tools.NearestPOT = function (x) {
  8761. var c = Tools.CeilingPOT(x);
  8762. var f = Tools.FloorPOT(x);
  8763. return (c - x) > (x - f) ? f : c;
  8764. };
  8765. Tools.GetExponentOfTwo = function (value, max, mode) {
  8766. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8767. var pot;
  8768. switch (mode) {
  8769. case BABYLON.Engine.SCALEMODE_FLOOR:
  8770. pot = Tools.FloorPOT(value);
  8771. break;
  8772. case BABYLON.Engine.SCALEMODE_NEAREST:
  8773. pot = Tools.NearestPOT(value);
  8774. break;
  8775. case BABYLON.Engine.SCALEMODE_CEILING:
  8776. default:
  8777. pot = Tools.CeilingPOT(value);
  8778. break;
  8779. }
  8780. return Math.min(pot, max);
  8781. };
  8782. Tools.GetFilename = function (path) {
  8783. var index = path.lastIndexOf("/");
  8784. if (index < 0)
  8785. return path;
  8786. return path.substring(index + 1);
  8787. };
  8788. /**
  8789. * Extracts the "folder" part of a path (everything before the filename).
  8790. * @param uri The URI to extract the info from
  8791. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8792. * @returns The "folder" part of the path
  8793. */
  8794. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8795. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8796. var index = uri.lastIndexOf("/");
  8797. if (index < 0) {
  8798. if (returnUnchangedIfNoSlash) {
  8799. return uri;
  8800. }
  8801. return "";
  8802. }
  8803. return uri.substring(0, index + 1);
  8804. };
  8805. Tools.GetDOMTextContent = function (element) {
  8806. var result = "";
  8807. var child = element.firstChild;
  8808. while (child) {
  8809. if (child.nodeType === 3) {
  8810. result += child.textContent;
  8811. }
  8812. child = child.nextSibling;
  8813. }
  8814. return result;
  8815. };
  8816. Tools.ToDegrees = function (angle) {
  8817. return angle * 180 / Math.PI;
  8818. };
  8819. Tools.ToRadians = function (angle) {
  8820. return angle * Math.PI / 180;
  8821. };
  8822. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8823. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8824. var output = "";
  8825. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8826. var i = 0;
  8827. var bytes = new Uint8Array(buffer);
  8828. while (i < bytes.length) {
  8829. chr1 = bytes[i++];
  8830. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8831. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8832. enc1 = chr1 >> 2;
  8833. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8834. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8835. enc4 = chr3 & 63;
  8836. if (isNaN(chr2)) {
  8837. enc3 = enc4 = 64;
  8838. }
  8839. else if (isNaN(chr3)) {
  8840. enc4 = 64;
  8841. }
  8842. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8843. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8844. }
  8845. return "data:image/png;base64," + output;
  8846. };
  8847. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8848. if (bias === void 0) { bias = null; }
  8849. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8850. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8851. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8852. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8853. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8854. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8855. }
  8856. if (bias) {
  8857. minimum.x -= minimum.x * bias.x + bias.y;
  8858. minimum.y -= minimum.y * bias.x + bias.y;
  8859. minimum.z -= minimum.z * bias.x + bias.y;
  8860. maximum.x += maximum.x * bias.x + bias.y;
  8861. maximum.y += maximum.y * bias.x + bias.y;
  8862. maximum.z += maximum.z * bias.x + bias.y;
  8863. }
  8864. return {
  8865. minimum: minimum,
  8866. maximum: maximum
  8867. };
  8868. };
  8869. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8870. if (bias === void 0) { bias = null; }
  8871. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8872. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8873. if (!stride) {
  8874. stride = 3;
  8875. }
  8876. for (var index = start; index < start + count; index++) {
  8877. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8878. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8879. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8880. }
  8881. if (bias) {
  8882. minimum.x -= minimum.x * bias.x + bias.y;
  8883. minimum.y -= minimum.y * bias.x + bias.y;
  8884. minimum.z -= minimum.z * bias.x + bias.y;
  8885. maximum.x += maximum.x * bias.x + bias.y;
  8886. maximum.y += maximum.y * bias.x + bias.y;
  8887. maximum.z += maximum.z * bias.x + bias.y;
  8888. }
  8889. return {
  8890. minimum: minimum,
  8891. maximum: maximum
  8892. };
  8893. };
  8894. Tools.Vector2ArrayFeeder = function (array) {
  8895. return function (index) {
  8896. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8897. var length = isFloatArray ? array.length / 2 : array.length;
  8898. if (index >= length) {
  8899. return null;
  8900. }
  8901. if (isFloatArray) {
  8902. var fa = array;
  8903. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8904. }
  8905. var a = array;
  8906. return a[index];
  8907. };
  8908. };
  8909. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8910. if (bias === void 0) { bias = null; }
  8911. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8912. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8913. var i = 0;
  8914. var cur = feeder(i++);
  8915. while (cur) {
  8916. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8917. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8918. cur = feeder(i++);
  8919. }
  8920. if (bias) {
  8921. minimum.x -= minimum.x * bias.x + bias.y;
  8922. minimum.y -= minimum.y * bias.x + bias.y;
  8923. maximum.x += maximum.x * bias.x + bias.y;
  8924. maximum.y += maximum.y * bias.x + bias.y;
  8925. }
  8926. return {
  8927. minimum: minimum,
  8928. maximum: maximum
  8929. };
  8930. };
  8931. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8932. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8933. return null;
  8934. return Array.isArray(obj) ? obj : [obj];
  8935. };
  8936. // Misc.
  8937. Tools.GetPointerPrefix = function () {
  8938. var eventPrefix = "pointer";
  8939. // Check if pointer events are supported
  8940. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8941. eventPrefix = "mouse";
  8942. }
  8943. return eventPrefix;
  8944. };
  8945. /**
  8946. * @param func - the function to be called
  8947. * @param requester - the object that will request the next frame. Falls back to window.
  8948. */
  8949. Tools.QueueNewFrame = function (func, requester) {
  8950. if (!Tools.IsWindowObjectExist()) {
  8951. return setTimeout(func, 16);
  8952. }
  8953. if (!requester) {
  8954. requester = window;
  8955. }
  8956. if (requester.requestAnimationFrame) {
  8957. return requester.requestAnimationFrame(func);
  8958. }
  8959. else if (requester.msRequestAnimationFrame) {
  8960. return requester.msRequestAnimationFrame(func);
  8961. }
  8962. else if (requester.webkitRequestAnimationFrame) {
  8963. return requester.webkitRequestAnimationFrame(func);
  8964. }
  8965. else if (requester.mozRequestAnimationFrame) {
  8966. return requester.mozRequestAnimationFrame(func);
  8967. }
  8968. else if (requester.oRequestAnimationFrame) {
  8969. return requester.oRequestAnimationFrame(func);
  8970. }
  8971. else {
  8972. return window.setTimeout(func, 16);
  8973. }
  8974. };
  8975. Tools.RequestFullscreen = function (element) {
  8976. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8977. if (!requestFunction)
  8978. return;
  8979. requestFunction.call(element);
  8980. };
  8981. Tools.ExitFullscreen = function () {
  8982. if (document.exitFullscreen) {
  8983. document.exitFullscreen();
  8984. }
  8985. else if (document.mozCancelFullScreen) {
  8986. document.mozCancelFullScreen();
  8987. }
  8988. else if (document.webkitCancelFullScreen) {
  8989. document.webkitCancelFullScreen();
  8990. }
  8991. else if (document.msCancelFullScreen) {
  8992. document.msCancelFullScreen();
  8993. }
  8994. };
  8995. Tools.SetCorsBehavior = function (url, element) {
  8996. if (url && url.indexOf("data:") === 0) {
  8997. return;
  8998. }
  8999. if (Tools.CorsBehavior) {
  9000. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9001. element.crossOrigin = Tools.CorsBehavior;
  9002. }
  9003. else {
  9004. var result = Tools.CorsBehavior(url);
  9005. if (result) {
  9006. element.crossOrigin = result;
  9007. }
  9008. }
  9009. }
  9010. };
  9011. // External files
  9012. Tools.CleanUrl = function (url) {
  9013. url = url.replace(/#/mg, "%23");
  9014. return url;
  9015. };
  9016. /**
  9017. * Loads an image as an HTMLImageElement.
  9018. * @param input url string, ArrayBuffer, or Blob to load
  9019. * @param onLoad callback called when the image successfully loads
  9020. * @param onError callback called when the image fails to load
  9021. * @param database database for caching
  9022. * @returns the HTMLImageElement of the loaded image
  9023. */
  9024. Tools.LoadImage = function (input, onLoad, onError, database) {
  9025. var url;
  9026. var usingObjectURL = false;
  9027. if (input instanceof ArrayBuffer) {
  9028. url = URL.createObjectURL(new Blob([input]));
  9029. usingObjectURL = true;
  9030. }
  9031. else if (input instanceof Blob) {
  9032. url = URL.createObjectURL(input);
  9033. usingObjectURL = true;
  9034. }
  9035. else {
  9036. url = Tools.CleanUrl(input);
  9037. url = Tools.PreprocessUrl(input);
  9038. }
  9039. var img = new Image();
  9040. Tools.SetCorsBehavior(url, img);
  9041. var loadHandler = function () {
  9042. if (usingObjectURL && img.src) {
  9043. URL.revokeObjectURL(img.src);
  9044. }
  9045. img.removeEventListener("load", loadHandler);
  9046. img.removeEventListener("error", errorHandler);
  9047. onLoad(img);
  9048. };
  9049. var errorHandler = function (err) {
  9050. if (usingObjectURL && img.src) {
  9051. URL.revokeObjectURL(img.src);
  9052. }
  9053. img.removeEventListener("load", loadHandler);
  9054. img.removeEventListener("error", errorHandler);
  9055. Tools.Error("Error while trying to load image: " + input);
  9056. if (onError) {
  9057. onError("Error while trying to load image: " + input, err);
  9058. }
  9059. };
  9060. img.addEventListener("load", loadHandler);
  9061. img.addEventListener("error", errorHandler);
  9062. var noIndexedDB = function () {
  9063. img.src = url;
  9064. };
  9065. var loadFromIndexedDB = function () {
  9066. if (database) {
  9067. database.loadImageFromDB(url, img);
  9068. }
  9069. };
  9070. //ANY database to do!
  9071. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9072. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9073. }
  9074. else {
  9075. if (url.indexOf("file:") !== -1) {
  9076. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9077. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9078. try {
  9079. var blobURL;
  9080. try {
  9081. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9082. }
  9083. catch (ex) {
  9084. // Chrome doesn't support oneTimeOnly parameter
  9085. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9086. }
  9087. img.src = blobURL;
  9088. usingObjectURL = true;
  9089. }
  9090. catch (e) {
  9091. img.src = "";
  9092. }
  9093. return img;
  9094. }
  9095. }
  9096. noIndexedDB();
  9097. }
  9098. return img;
  9099. };
  9100. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9101. url = Tools.CleanUrl(url);
  9102. url = Tools.PreprocessUrl(url);
  9103. // If file and file input are set
  9104. if (url.indexOf("file:") !== -1) {
  9105. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9106. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9107. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9108. }
  9109. }
  9110. var loadUrl = Tools.BaseUrl + url;
  9111. var aborted = false;
  9112. var fileRequest = {
  9113. onCompleteObservable: new BABYLON.Observable(),
  9114. abort: function () { return aborted = true; },
  9115. };
  9116. var requestFile = function () {
  9117. var request = new XMLHttpRequest();
  9118. var retryHandle = null;
  9119. fileRequest.abort = function () {
  9120. aborted = true;
  9121. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9122. request.abort();
  9123. }
  9124. if (retryHandle !== null) {
  9125. clearTimeout(retryHandle);
  9126. retryHandle = null;
  9127. }
  9128. };
  9129. var retryLoop = function (retryIndex) {
  9130. request.open('GET', loadUrl, true);
  9131. if (useArrayBuffer) {
  9132. request.responseType = "arraybuffer";
  9133. }
  9134. if (onProgress) {
  9135. request.addEventListener("progress", onProgress);
  9136. }
  9137. var onLoadEnd = function () {
  9138. request.removeEventListener("loadend", onLoadEnd);
  9139. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9140. fileRequest.onCompleteObservable.clear();
  9141. };
  9142. request.addEventListener("loadend", onLoadEnd);
  9143. var onReadyStateChange = function () {
  9144. if (aborted) {
  9145. return;
  9146. }
  9147. // In case of undefined state in some browsers.
  9148. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9149. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9150. request.removeEventListener("readystatechange", onReadyStateChange);
  9151. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9152. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9153. return;
  9154. }
  9155. var retryStrategy = Tools.DefaultRetryStrategy;
  9156. if (retryStrategy) {
  9157. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9158. if (waitTime !== -1) {
  9159. // Prevent the request from completing for retry.
  9160. request.removeEventListener("loadend", onLoadEnd);
  9161. request = new XMLHttpRequest();
  9162. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9163. return;
  9164. }
  9165. }
  9166. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9167. if (onError) {
  9168. onError(request, e);
  9169. }
  9170. else {
  9171. throw e;
  9172. }
  9173. }
  9174. };
  9175. request.addEventListener("readystatechange", onReadyStateChange);
  9176. request.send();
  9177. };
  9178. retryLoop(0);
  9179. };
  9180. // Caching all files
  9181. if (database && database.enableSceneOffline) {
  9182. var noIndexedDB_1 = function (request) {
  9183. if (request && request.status > 400) {
  9184. if (onError) {
  9185. onError(request);
  9186. }
  9187. }
  9188. else {
  9189. if (!aborted) {
  9190. requestFile();
  9191. }
  9192. }
  9193. };
  9194. var loadFromIndexedDB = function () {
  9195. // TODO: database needs to support aborting and should return a IFileRequest
  9196. if (aborted) {
  9197. return;
  9198. }
  9199. if (database) {
  9200. database.loadFileFromDB(url, function (data) {
  9201. if (!aborted) {
  9202. onSuccess(data);
  9203. }
  9204. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9205. }, onProgress ? function (event) {
  9206. if (!aborted) {
  9207. onProgress(event);
  9208. }
  9209. } : undefined, noIndexedDB_1, useArrayBuffer);
  9210. }
  9211. };
  9212. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9213. }
  9214. else {
  9215. requestFile();
  9216. }
  9217. return fileRequest;
  9218. };
  9219. /**
  9220. * Load a script (identified by an url). When the url returns, the
  9221. * content of this file is added into a new script element, attached to the DOM (body element)
  9222. */
  9223. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9224. if (!Tools.IsWindowObjectExist()) {
  9225. return;
  9226. }
  9227. var head = document.getElementsByTagName('head')[0];
  9228. var script = document.createElement('script');
  9229. script.type = 'text/javascript';
  9230. script.src = scriptUrl;
  9231. script.onload = function () {
  9232. if (onSuccess) {
  9233. onSuccess();
  9234. }
  9235. };
  9236. script.onerror = function (e) {
  9237. if (onError) {
  9238. onError("Unable to load script '" + scriptUrl + "'", e);
  9239. }
  9240. };
  9241. head.appendChild(script);
  9242. };
  9243. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9244. var reader = new FileReader();
  9245. var request = {
  9246. onCompleteObservable: new BABYLON.Observable(),
  9247. abort: function () { return reader.abort(); },
  9248. };
  9249. reader.onloadend = function (e) {
  9250. request.onCompleteObservable.notifyObservers(request);
  9251. };
  9252. reader.onload = function (e) {
  9253. //target doesn't have result from ts 1.3
  9254. callback(e.target['result']);
  9255. };
  9256. reader.onprogress = progressCallback;
  9257. reader.readAsDataURL(fileToLoad);
  9258. return request;
  9259. };
  9260. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9261. var reader = new FileReader();
  9262. var request = {
  9263. onCompleteObservable: new BABYLON.Observable(),
  9264. abort: function () { return reader.abort(); },
  9265. };
  9266. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9267. reader.onerror = function (e) {
  9268. Tools.Log("Error while reading file: " + fileToLoad.name);
  9269. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9270. };
  9271. reader.onload = function (e) {
  9272. //target doesn't have result from ts 1.3
  9273. callback(e.target['result']);
  9274. };
  9275. if (progressCallBack) {
  9276. reader.onprogress = progressCallBack;
  9277. }
  9278. if (!useArrayBuffer) {
  9279. // Asynchronous read
  9280. reader.readAsText(fileToLoad);
  9281. }
  9282. else {
  9283. reader.readAsArrayBuffer(fileToLoad);
  9284. }
  9285. return request;
  9286. };
  9287. //returns a downloadable url to a file content.
  9288. Tools.FileAsURL = function (content) {
  9289. var fileBlob = new Blob([content]);
  9290. var url = window.URL || window.webkitURL;
  9291. var link = url.createObjectURL(fileBlob);
  9292. return link;
  9293. };
  9294. // Misc.
  9295. Tools.Format = function (value, decimals) {
  9296. if (decimals === void 0) { decimals = 2; }
  9297. return value.toFixed(decimals);
  9298. };
  9299. Tools.CheckExtends = function (v, min, max) {
  9300. if (v.x < min.x)
  9301. min.x = v.x;
  9302. if (v.y < min.y)
  9303. min.y = v.y;
  9304. if (v.z < min.z)
  9305. min.z = v.z;
  9306. if (v.x > max.x)
  9307. max.x = v.x;
  9308. if (v.y > max.y)
  9309. max.y = v.y;
  9310. if (v.z > max.z)
  9311. max.z = v.z;
  9312. };
  9313. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9314. for (var prop in source) {
  9315. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9316. continue;
  9317. }
  9318. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9319. continue;
  9320. }
  9321. var sourceValue = source[prop];
  9322. var typeOfSourceValue = typeof sourceValue;
  9323. if (typeOfSourceValue === "function") {
  9324. continue;
  9325. }
  9326. try {
  9327. if (typeOfSourceValue === "object") {
  9328. if (sourceValue instanceof Array) {
  9329. destination[prop] = [];
  9330. if (sourceValue.length > 0) {
  9331. if (typeof sourceValue[0] == "object") {
  9332. for (var index = 0; index < sourceValue.length; index++) {
  9333. var clonedValue = cloneValue(sourceValue[index], destination);
  9334. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9335. destination[prop].push(clonedValue);
  9336. }
  9337. }
  9338. }
  9339. else {
  9340. destination[prop] = sourceValue.slice(0);
  9341. }
  9342. }
  9343. }
  9344. else {
  9345. destination[prop] = cloneValue(sourceValue, destination);
  9346. }
  9347. }
  9348. else {
  9349. destination[prop] = sourceValue;
  9350. }
  9351. }
  9352. catch (e) {
  9353. // Just ignore error (it could be because of a read-only property)
  9354. }
  9355. }
  9356. };
  9357. Tools.IsEmpty = function (obj) {
  9358. for (var i in obj) {
  9359. if (obj.hasOwnProperty(i)) {
  9360. return false;
  9361. }
  9362. }
  9363. return true;
  9364. };
  9365. Tools.RegisterTopRootEvents = function (events) {
  9366. for (var index = 0; index < events.length; index++) {
  9367. var event = events[index];
  9368. window.addEventListener(event.name, event.handler, false);
  9369. try {
  9370. if (window.parent) {
  9371. window.parent.addEventListener(event.name, event.handler, false);
  9372. }
  9373. }
  9374. catch (e) {
  9375. // Silently fails...
  9376. }
  9377. }
  9378. };
  9379. Tools.UnregisterTopRootEvents = function (events) {
  9380. for (var index = 0; index < events.length; index++) {
  9381. var event = events[index];
  9382. window.removeEventListener(event.name, event.handler);
  9383. try {
  9384. if (window.parent) {
  9385. window.parent.removeEventListener(event.name, event.handler);
  9386. }
  9387. }
  9388. catch (e) {
  9389. // Silently fails...
  9390. }
  9391. }
  9392. };
  9393. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9394. if (mimeType === void 0) { mimeType = "image/png"; }
  9395. // Read the contents of the framebuffer
  9396. var numberOfChannelsByLine = width * 4;
  9397. var halfHeight = height / 2;
  9398. //Reading datas from WebGL
  9399. var data = engine.readPixels(0, 0, width, height);
  9400. //To flip image on Y axis.
  9401. for (var i = 0; i < halfHeight; i++) {
  9402. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9403. var currentCell = j + i * numberOfChannelsByLine;
  9404. var targetLine = height - i - 1;
  9405. var targetCell = j + targetLine * numberOfChannelsByLine;
  9406. var temp = data[currentCell];
  9407. data[currentCell] = data[targetCell];
  9408. data[targetCell] = temp;
  9409. }
  9410. }
  9411. // Create a 2D canvas to store the result
  9412. if (!screenshotCanvas) {
  9413. screenshotCanvas = document.createElement('canvas');
  9414. }
  9415. screenshotCanvas.width = width;
  9416. screenshotCanvas.height = height;
  9417. var context = screenshotCanvas.getContext('2d');
  9418. if (context) {
  9419. // Copy the pixels to a 2D canvas
  9420. var imageData = context.createImageData(width, height);
  9421. var castData = (imageData.data);
  9422. castData.set(data);
  9423. context.putImageData(imageData, 0, 0);
  9424. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9425. }
  9426. };
  9427. /**
  9428. * Converts the canvas data to blob.
  9429. * This acts as a polyfill for browsers not supporting the to blob function.
  9430. * @param canvas Defines the canvas to extract the data from
  9431. * @param successCallback Defines the callback triggered once the data are available
  9432. * @param mimeType Defines the mime type of the result
  9433. */
  9434. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9435. if (mimeType === void 0) { mimeType = "image/png"; }
  9436. // We need HTMLCanvasElement.toBlob for HD screenshots
  9437. if (!canvas.toBlob) {
  9438. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9439. canvas.toBlob = function (callback, type, quality) {
  9440. var _this = this;
  9441. setTimeout(function () {
  9442. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9443. for (var i = 0; i < len; i++) {
  9444. arr[i] = binStr.charCodeAt(i);
  9445. }
  9446. callback(new Blob([arr]));
  9447. });
  9448. };
  9449. }
  9450. canvas.toBlob(function (blob) {
  9451. successCallback(blob);
  9452. }, mimeType);
  9453. };
  9454. /**
  9455. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9456. * @param successCallback Defines the callback triggered once the data are available
  9457. * @param mimeType Defines the mime type of the result
  9458. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9459. */
  9460. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9461. if (mimeType === void 0) { mimeType = "image/png"; }
  9462. if (successCallback) {
  9463. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9464. successCallback(base64Image);
  9465. }
  9466. else {
  9467. this.ToBlob(screenshotCanvas, function (blob) {
  9468. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9469. if (("download" in document.createElement("a"))) {
  9470. if (!fileName) {
  9471. var date = new Date();
  9472. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9473. fileName = "screenshot_" + stringDate + ".png";
  9474. }
  9475. Tools.Download(blob, fileName);
  9476. }
  9477. else {
  9478. var url = URL.createObjectURL(blob);
  9479. var newWindow = window.open("");
  9480. if (!newWindow)
  9481. return;
  9482. var img = newWindow.document.createElement("img");
  9483. img.onload = function () {
  9484. // no longer need to read the blob so it's revoked
  9485. URL.revokeObjectURL(url);
  9486. };
  9487. img.src = url;
  9488. newWindow.document.body.appendChild(img);
  9489. }
  9490. }, mimeType);
  9491. }
  9492. };
  9493. /**
  9494. * Downloads a blob in the browser
  9495. * @param blob defines the blob to download
  9496. * @param fileName defines the name of the downloaded file
  9497. */
  9498. Tools.Download = function (blob, fileName) {
  9499. if (navigator && navigator.msSaveBlob) {
  9500. navigator.msSaveBlob(blob, fileName);
  9501. return;
  9502. }
  9503. var url = window.URL.createObjectURL(blob);
  9504. var a = document.createElement("a");
  9505. document.body.appendChild(a);
  9506. a.style.display = "none";
  9507. a.href = url;
  9508. a.download = fileName;
  9509. a.addEventListener("click", function () {
  9510. if (a.parentElement) {
  9511. a.parentElement.removeChild(a);
  9512. }
  9513. });
  9514. a.click();
  9515. window.URL.revokeObjectURL(url);
  9516. };
  9517. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9518. if (mimeType === void 0) { mimeType = "image/png"; }
  9519. var width;
  9520. var height;
  9521. // If a precision value is specified
  9522. if (size.precision) {
  9523. width = Math.round(engine.getRenderWidth() * size.precision);
  9524. height = Math.round(width / engine.getAspectRatio(camera));
  9525. }
  9526. else if (size.width && size.height) {
  9527. width = size.width;
  9528. height = size.height;
  9529. }
  9530. //If passing only width, computing height to keep display canvas ratio.
  9531. else if (size.width && !size.height) {
  9532. width = size.width;
  9533. height = Math.round(width / engine.getAspectRatio(camera));
  9534. }
  9535. //If passing only height, computing width to keep display canvas ratio.
  9536. else if (size.height && !size.width) {
  9537. height = size.height;
  9538. width = Math.round(height * engine.getAspectRatio(camera));
  9539. }
  9540. //Assuming here that "size" parameter is a number
  9541. else if (!isNaN(size)) {
  9542. height = size;
  9543. width = size;
  9544. }
  9545. else {
  9546. Tools.Error("Invalid 'size' parameter !");
  9547. return;
  9548. }
  9549. if (!screenshotCanvas) {
  9550. screenshotCanvas = document.createElement('canvas');
  9551. }
  9552. screenshotCanvas.width = width;
  9553. screenshotCanvas.height = height;
  9554. var renderContext = screenshotCanvas.getContext("2d");
  9555. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9556. var newWidth = width;
  9557. var newHeight = newWidth / ratio;
  9558. if (newHeight > height) {
  9559. newHeight = height;
  9560. newWidth = newHeight * ratio;
  9561. }
  9562. var offsetX = Math.max(0, width - newWidth) / 2;
  9563. var offsetY = Math.max(0, height - newHeight) / 2;
  9564. var renderingCanvas = engine.getRenderingCanvas();
  9565. if (renderContext && renderingCanvas) {
  9566. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9567. }
  9568. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9569. };
  9570. /**
  9571. * Generates an image screenshot from the specified camera.
  9572. *
  9573. * @param engine The engine to use for rendering
  9574. * @param camera The camera to use for rendering
  9575. * @param size This parameter can be set to a single number or to an object with the
  9576. * following (optional) properties: precision, width, height. If a single number is passed,
  9577. * it will be used for both width and height. If an object is passed, the screenshot size
  9578. * will be derived from the parameters. The precision property is a multiplier allowing
  9579. * rendering at a higher or lower resolution.
  9580. * @param successCallback The callback receives a single parameter which contains the
  9581. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9582. * src parameter of an <img> to display it.
  9583. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9584. * Check your browser for supported MIME types.
  9585. * @param samples Texture samples (default: 1)
  9586. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9587. * @param fileName A name for for the downloaded file.
  9588. * @constructor
  9589. */
  9590. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9591. if (mimeType === void 0) { mimeType = "image/png"; }
  9592. if (samples === void 0) { samples = 1; }
  9593. if (antialiasing === void 0) { antialiasing = false; }
  9594. var width;
  9595. var height;
  9596. //If a precision value is specified
  9597. if (size.precision) {
  9598. width = Math.round(engine.getRenderWidth() * size.precision);
  9599. height = Math.round(width / engine.getAspectRatio(camera));
  9600. size = { width: width, height: height };
  9601. }
  9602. else if (size.width && size.height) {
  9603. width = size.width;
  9604. height = size.height;
  9605. }
  9606. //If passing only width, computing height to keep display canvas ratio.
  9607. else if (size.width && !size.height) {
  9608. width = size.width;
  9609. height = Math.round(width / engine.getAspectRatio(camera));
  9610. size = { width: width, height: height };
  9611. }
  9612. //If passing only height, computing width to keep display canvas ratio.
  9613. else if (size.height && !size.width) {
  9614. height = size.height;
  9615. width = Math.round(height * engine.getAspectRatio(camera));
  9616. size = { width: width, height: height };
  9617. }
  9618. //Assuming here that "size" parameter is a number
  9619. else if (!isNaN(size)) {
  9620. height = size;
  9621. width = size;
  9622. }
  9623. else {
  9624. Tools.Error("Invalid 'size' parameter !");
  9625. return;
  9626. }
  9627. var scene = camera.getScene();
  9628. var previousCamera = null;
  9629. if (scene.activeCamera !== camera) {
  9630. previousCamera = scene.activeCamera;
  9631. scene.activeCamera = camera;
  9632. }
  9633. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9634. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9635. texture.renderList = null;
  9636. texture.samples = samples;
  9637. if (antialiasing) {
  9638. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9639. }
  9640. texture.onAfterRenderObservable.add(function () {
  9641. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9642. });
  9643. scene.incrementRenderId();
  9644. scene.resetCachedMaterial();
  9645. texture.render(true);
  9646. texture.dispose();
  9647. if (previousCamera) {
  9648. scene.activeCamera = previousCamera;
  9649. }
  9650. camera.getProjectionMatrix(true); // Force cache refresh;
  9651. };
  9652. // XHR response validator for local file scenario
  9653. Tools.ValidateXHRData = function (xhr, dataType) {
  9654. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9655. if (dataType === void 0) { dataType = 7; }
  9656. try {
  9657. if (dataType & 1) {
  9658. if (xhr.responseText && xhr.responseText.length > 0) {
  9659. return true;
  9660. }
  9661. else if (dataType === 1) {
  9662. return false;
  9663. }
  9664. }
  9665. if (dataType & 2) {
  9666. // Check header width and height since there is no "TGA" magic number
  9667. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9668. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9669. return true;
  9670. }
  9671. else if (dataType === 2) {
  9672. return false;
  9673. }
  9674. }
  9675. if (dataType & 4) {
  9676. // Check for the "DDS" magic number
  9677. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9678. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9679. return true;
  9680. }
  9681. else {
  9682. return false;
  9683. }
  9684. }
  9685. }
  9686. catch (e) {
  9687. // Global protection
  9688. }
  9689. return false;
  9690. };
  9691. /**
  9692. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9693. * Be aware Math.random() could cause collisions, but:
  9694. * "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"
  9695. */
  9696. Tools.RandomId = function () {
  9697. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9698. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9699. return v.toString(16);
  9700. });
  9701. };
  9702. /**
  9703. * Test if the given uri is a base64 string.
  9704. * @param uri The uri to test
  9705. * @return True if the uri is a base64 string or false otherwise.
  9706. */
  9707. Tools.IsBase64 = function (uri) {
  9708. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9709. };
  9710. /**
  9711. * Decode the given base64 uri.
  9712. * @param uri The uri to decode
  9713. * @return The decoded base64 data.
  9714. */
  9715. Tools.DecodeBase64 = function (uri) {
  9716. var decodedString = atob(uri.split(",")[1]);
  9717. var bufferLength = decodedString.length;
  9718. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9719. for (var i = 0; i < bufferLength; i++) {
  9720. bufferView[i] = decodedString.charCodeAt(i);
  9721. }
  9722. return bufferView.buffer;
  9723. };
  9724. Object.defineProperty(Tools, "NoneLogLevel", {
  9725. get: function () {
  9726. return Tools._NoneLogLevel;
  9727. },
  9728. enumerable: true,
  9729. configurable: true
  9730. });
  9731. Object.defineProperty(Tools, "MessageLogLevel", {
  9732. get: function () {
  9733. return Tools._MessageLogLevel;
  9734. },
  9735. enumerable: true,
  9736. configurable: true
  9737. });
  9738. Object.defineProperty(Tools, "WarningLogLevel", {
  9739. get: function () {
  9740. return Tools._WarningLogLevel;
  9741. },
  9742. enumerable: true,
  9743. configurable: true
  9744. });
  9745. Object.defineProperty(Tools, "ErrorLogLevel", {
  9746. get: function () {
  9747. return Tools._ErrorLogLevel;
  9748. },
  9749. enumerable: true,
  9750. configurable: true
  9751. });
  9752. Object.defineProperty(Tools, "AllLogLevel", {
  9753. get: function () {
  9754. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9755. },
  9756. enumerable: true,
  9757. configurable: true
  9758. });
  9759. Tools._AddLogEntry = function (entry) {
  9760. Tools._LogCache = entry + Tools._LogCache;
  9761. if (Tools.OnNewCacheEntry) {
  9762. Tools.OnNewCacheEntry(entry);
  9763. }
  9764. };
  9765. Tools._FormatMessage = function (message) {
  9766. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9767. var date = new Date();
  9768. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9769. };
  9770. Tools._LogDisabled = function (message) {
  9771. // nothing to do
  9772. };
  9773. Tools._LogEnabled = function (message) {
  9774. var formattedMessage = Tools._FormatMessage(message);
  9775. console.log("BJS - " + formattedMessage);
  9776. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9777. Tools._AddLogEntry(entry);
  9778. };
  9779. Tools._WarnDisabled = function (message) {
  9780. // nothing to do
  9781. };
  9782. Tools._WarnEnabled = function (message) {
  9783. var formattedMessage = Tools._FormatMessage(message);
  9784. console.warn("BJS - " + formattedMessage);
  9785. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9786. Tools._AddLogEntry(entry);
  9787. };
  9788. Tools._ErrorDisabled = function (message) {
  9789. // nothing to do
  9790. };
  9791. Tools._ErrorEnabled = function (message) {
  9792. Tools.errorsCount++;
  9793. var formattedMessage = Tools._FormatMessage(message);
  9794. console.error("BJS - " + formattedMessage);
  9795. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9796. Tools._AddLogEntry(entry);
  9797. };
  9798. Object.defineProperty(Tools, "LogCache", {
  9799. get: function () {
  9800. return Tools._LogCache;
  9801. },
  9802. enumerable: true,
  9803. configurable: true
  9804. });
  9805. Tools.ClearLogCache = function () {
  9806. Tools._LogCache = "";
  9807. Tools.errorsCount = 0;
  9808. };
  9809. Object.defineProperty(Tools, "LogLevels", {
  9810. set: function (level) {
  9811. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9812. Tools.Log = Tools._LogEnabled;
  9813. }
  9814. else {
  9815. Tools.Log = Tools._LogDisabled;
  9816. }
  9817. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9818. Tools.Warn = Tools._WarnEnabled;
  9819. }
  9820. else {
  9821. Tools.Warn = Tools._WarnDisabled;
  9822. }
  9823. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9824. Tools.Error = Tools._ErrorEnabled;
  9825. }
  9826. else {
  9827. Tools.Error = Tools._ErrorDisabled;
  9828. }
  9829. },
  9830. enumerable: true,
  9831. configurable: true
  9832. });
  9833. /**
  9834. * Check if the loaded document was accessed via `file:`-Protocol.
  9835. * @returns boolean
  9836. */
  9837. Tools.IsFileURL = function () {
  9838. return location.protocol === "file:";
  9839. };
  9840. Tools.IsWindowObjectExist = function () {
  9841. return (typeof window) !== "undefined";
  9842. };
  9843. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9844. get: function () {
  9845. return Tools._PerformanceNoneLogLevel;
  9846. },
  9847. enumerable: true,
  9848. configurable: true
  9849. });
  9850. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9851. get: function () {
  9852. return Tools._PerformanceUserMarkLogLevel;
  9853. },
  9854. enumerable: true,
  9855. configurable: true
  9856. });
  9857. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9858. get: function () {
  9859. return Tools._PerformanceConsoleLogLevel;
  9860. },
  9861. enumerable: true,
  9862. configurable: true
  9863. });
  9864. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9865. set: function (level) {
  9866. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9867. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9868. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9869. return;
  9870. }
  9871. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9872. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9873. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9874. return;
  9875. }
  9876. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9877. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9878. },
  9879. enumerable: true,
  9880. configurable: true
  9881. });
  9882. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9883. };
  9884. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9885. };
  9886. Tools._StartUserMark = function (counterName, condition) {
  9887. if (condition === void 0) { condition = true; }
  9888. if (!Tools._performance) {
  9889. if (!Tools.IsWindowObjectExist()) {
  9890. return;
  9891. }
  9892. Tools._performance = window.performance;
  9893. }
  9894. if (!condition || !Tools._performance.mark) {
  9895. return;
  9896. }
  9897. Tools._performance.mark(counterName + "-Begin");
  9898. };
  9899. Tools._EndUserMark = function (counterName, condition) {
  9900. if (condition === void 0) { condition = true; }
  9901. if (!condition || !Tools._performance.mark) {
  9902. return;
  9903. }
  9904. Tools._performance.mark(counterName + "-End");
  9905. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9906. };
  9907. Tools._StartPerformanceConsole = function (counterName, condition) {
  9908. if (condition === void 0) { condition = true; }
  9909. if (!condition) {
  9910. return;
  9911. }
  9912. Tools._StartUserMark(counterName, condition);
  9913. if (console.time) {
  9914. console.time(counterName);
  9915. }
  9916. };
  9917. Tools._EndPerformanceConsole = function (counterName, condition) {
  9918. if (condition === void 0) { condition = true; }
  9919. if (!condition) {
  9920. return;
  9921. }
  9922. Tools._EndUserMark(counterName, condition);
  9923. if (console.time) {
  9924. console.timeEnd(counterName);
  9925. }
  9926. };
  9927. Object.defineProperty(Tools, "Now", {
  9928. get: function () {
  9929. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9930. return window.performance.now();
  9931. }
  9932. return Date.now();
  9933. },
  9934. enumerable: true,
  9935. configurable: true
  9936. });
  9937. /**
  9938. * This method will return the name of the class used to create the instance of the given object.
  9939. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9940. * @param object the object to get the class name from
  9941. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9942. */
  9943. Tools.GetClassName = function (object, isType) {
  9944. if (isType === void 0) { isType = false; }
  9945. var name = null;
  9946. if (!isType && object.getClassName) {
  9947. name = object.getClassName();
  9948. }
  9949. else {
  9950. if (object instanceof Object) {
  9951. var classObj = isType ? object : Object.getPrototypeOf(object);
  9952. name = classObj.constructor["__bjsclassName__"];
  9953. }
  9954. if (!name) {
  9955. name = typeof object;
  9956. }
  9957. }
  9958. return name;
  9959. };
  9960. Tools.First = function (array, predicate) {
  9961. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9962. var el = array_1[_i];
  9963. if (predicate(el)) {
  9964. return el;
  9965. }
  9966. }
  9967. return null;
  9968. };
  9969. /**
  9970. * This method will return the name of the full name of the class, including its owning module (if any).
  9971. * 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).
  9972. * @param object the object to get the class name from
  9973. * @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.
  9974. */
  9975. Tools.getFullClassName = function (object, isType) {
  9976. if (isType === void 0) { isType = false; }
  9977. var className = null;
  9978. var moduleName = null;
  9979. if (!isType && object.getClassName) {
  9980. className = object.getClassName();
  9981. }
  9982. else {
  9983. if (object instanceof Object) {
  9984. var classObj = isType ? object : Object.getPrototypeOf(object);
  9985. className = classObj.constructor["__bjsclassName__"];
  9986. moduleName = classObj.constructor["__bjsmoduleName__"];
  9987. }
  9988. if (!className) {
  9989. className = typeof object;
  9990. }
  9991. }
  9992. if (!className) {
  9993. return null;
  9994. }
  9995. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9996. };
  9997. /**
  9998. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  9999. * @param array
  10000. */
  10001. Tools.arrayOrStringFeeder = function (array) {
  10002. return function (index) {
  10003. if (index >= array.length) {
  10004. return null;
  10005. }
  10006. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10007. if (val && val.getHashCode) {
  10008. val = val.getHashCode();
  10009. }
  10010. if (typeof val === "string") {
  10011. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10012. }
  10013. return val;
  10014. };
  10015. };
  10016. /**
  10017. * Compute the hashCode of a stream of number
  10018. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10019. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10020. * @return the hash code computed
  10021. */
  10022. Tools.hashCodeFromStream = function (feeder) {
  10023. // Based from here: http://stackoverflow.com/a/7616484/802124
  10024. var hash = 0;
  10025. var index = 0;
  10026. var chr = feeder(index++);
  10027. while (chr != null) {
  10028. hash = ((hash << 5) - hash) + chr;
  10029. hash |= 0; // Convert to 32bit integer
  10030. chr = feeder(index++);
  10031. }
  10032. return hash;
  10033. };
  10034. /**
  10035. * Returns a promise that resolves after the given amount of time.
  10036. * @param delay Number of milliseconds to delay
  10037. * @returns Promise that resolves after the given amount of time
  10038. */
  10039. Tools.DelayAsync = function (delay) {
  10040. return new Promise(function (resolve) {
  10041. setTimeout(function () {
  10042. resolve();
  10043. }, delay);
  10044. });
  10045. };
  10046. /**
  10047. * Gets the current gradient from an array of IValueGradient
  10048. * @param ratio defines the current ratio to get
  10049. * @param gradients defines the array of IValueGradient
  10050. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10051. */
  10052. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10053. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10054. var currentGradient = gradients[gradientIndex];
  10055. var nextGradient = gradients[gradientIndex + 1];
  10056. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10057. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10058. updateFunc(currentGradient, nextGradient, scale);
  10059. return;
  10060. }
  10061. }
  10062. // Use last index if over
  10063. var lastIndex = gradients.length - 1;
  10064. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10065. };
  10066. Tools.BaseUrl = "";
  10067. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10068. /**
  10069. * Default behaviour for cors in the application.
  10070. * It can be a string if the expected behavior is identical in the entire app.
  10071. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10072. */
  10073. Tools.CorsBehavior = "anonymous";
  10074. Tools.UseFallbackTexture = true;
  10075. /**
  10076. * Use this object to register external classes like custom textures or material
  10077. * to allow the laoders to instantiate them
  10078. */
  10079. Tools.RegisteredExternalClasses = {};
  10080. // Used in case of a texture loading problem
  10081. 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";
  10082. Tools._tmpFloatArray = new Float32Array(1);
  10083. Tools.PreprocessUrl = function (url) {
  10084. return url;
  10085. };
  10086. // Logs
  10087. Tools._NoneLogLevel = 0;
  10088. Tools._MessageLogLevel = 1;
  10089. Tools._WarningLogLevel = 2;
  10090. Tools._ErrorLogLevel = 4;
  10091. Tools._LogCache = "";
  10092. Tools.errorsCount = 0;
  10093. Tools.Log = Tools._LogEnabled;
  10094. Tools.Warn = Tools._WarnEnabled;
  10095. Tools.Error = Tools._ErrorEnabled;
  10096. // Performances
  10097. Tools._PerformanceNoneLogLevel = 0;
  10098. Tools._PerformanceUserMarkLogLevel = 1;
  10099. Tools._PerformanceConsoleLogLevel = 2;
  10100. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10101. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10102. return Tools;
  10103. }());
  10104. BABYLON.Tools = Tools;
  10105. /**
  10106. * This class is used to track a performance counter which is number based.
  10107. * The user has access to many properties which give statistics of different nature
  10108. *
  10109. * The implementer can track two kinds of Performance Counter: time and count
  10110. * 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.
  10111. * 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.
  10112. */
  10113. var PerfCounter = /** @class */ (function () {
  10114. function PerfCounter() {
  10115. this._startMonitoringTime = 0;
  10116. this._min = 0;
  10117. this._max = 0;
  10118. this._average = 0;
  10119. this._lastSecAverage = 0;
  10120. this._current = 0;
  10121. this._totalValueCount = 0;
  10122. this._totalAccumulated = 0;
  10123. this._lastSecAccumulated = 0;
  10124. this._lastSecTime = 0;
  10125. this._lastSecValueCount = 0;
  10126. }
  10127. Object.defineProperty(PerfCounter.prototype, "min", {
  10128. /**
  10129. * Returns the smallest value ever
  10130. */
  10131. get: function () {
  10132. return this._min;
  10133. },
  10134. enumerable: true,
  10135. configurable: true
  10136. });
  10137. Object.defineProperty(PerfCounter.prototype, "max", {
  10138. /**
  10139. * Returns the biggest value ever
  10140. */
  10141. get: function () {
  10142. return this._max;
  10143. },
  10144. enumerable: true,
  10145. configurable: true
  10146. });
  10147. Object.defineProperty(PerfCounter.prototype, "average", {
  10148. /**
  10149. * Returns the average value since the performance counter is running
  10150. */
  10151. get: function () {
  10152. return this._average;
  10153. },
  10154. enumerable: true,
  10155. configurable: true
  10156. });
  10157. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10158. /**
  10159. * Returns the average value of the last second the counter was monitored
  10160. */
  10161. get: function () {
  10162. return this._lastSecAverage;
  10163. },
  10164. enumerable: true,
  10165. configurable: true
  10166. });
  10167. Object.defineProperty(PerfCounter.prototype, "current", {
  10168. /**
  10169. * Returns the current value
  10170. */
  10171. get: function () {
  10172. return this._current;
  10173. },
  10174. enumerable: true,
  10175. configurable: true
  10176. });
  10177. Object.defineProperty(PerfCounter.prototype, "total", {
  10178. get: function () {
  10179. return this._totalAccumulated;
  10180. },
  10181. enumerable: true,
  10182. configurable: true
  10183. });
  10184. Object.defineProperty(PerfCounter.prototype, "count", {
  10185. get: function () {
  10186. return this._totalValueCount;
  10187. },
  10188. enumerable: true,
  10189. configurable: true
  10190. });
  10191. /**
  10192. * Call this method to start monitoring a new frame.
  10193. * 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.
  10194. */
  10195. PerfCounter.prototype.fetchNewFrame = function () {
  10196. this._totalValueCount++;
  10197. this._current = 0;
  10198. this._lastSecValueCount++;
  10199. };
  10200. /**
  10201. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10202. * @param newCount the count value to add to the monitored count
  10203. * @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.
  10204. */
  10205. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10206. if (!PerfCounter.Enabled) {
  10207. return;
  10208. }
  10209. this._current += newCount;
  10210. if (fetchResult) {
  10211. this._fetchResult();
  10212. }
  10213. };
  10214. /**
  10215. * Start monitoring this performance counter
  10216. */
  10217. PerfCounter.prototype.beginMonitoring = function () {
  10218. if (!PerfCounter.Enabled) {
  10219. return;
  10220. }
  10221. this._startMonitoringTime = Tools.Now;
  10222. };
  10223. /**
  10224. * Compute the time lapsed since the previous beginMonitoring() call.
  10225. * @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
  10226. */
  10227. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10228. if (newFrame === void 0) { newFrame = true; }
  10229. if (!PerfCounter.Enabled) {
  10230. return;
  10231. }
  10232. if (newFrame) {
  10233. this.fetchNewFrame();
  10234. }
  10235. var currentTime = Tools.Now;
  10236. this._current = currentTime - this._startMonitoringTime;
  10237. if (newFrame) {
  10238. this._fetchResult();
  10239. }
  10240. };
  10241. PerfCounter.prototype._fetchResult = function () {
  10242. this._totalAccumulated += this._current;
  10243. this._lastSecAccumulated += this._current;
  10244. // Min/Max update
  10245. this._min = Math.min(this._min, this._current);
  10246. this._max = Math.max(this._max, this._current);
  10247. this._average = this._totalAccumulated / this._totalValueCount;
  10248. // Reset last sec?
  10249. var now = Tools.Now;
  10250. if ((now - this._lastSecTime) > 1000) {
  10251. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10252. this._lastSecTime = now;
  10253. this._lastSecAccumulated = 0;
  10254. this._lastSecValueCount = 0;
  10255. }
  10256. };
  10257. PerfCounter.Enabled = true;
  10258. return PerfCounter;
  10259. }());
  10260. BABYLON.PerfCounter = PerfCounter;
  10261. /**
  10262. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10263. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10264. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10265. * @param name The name of the class, case should be preserved
  10266. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10267. */
  10268. function className(name, module) {
  10269. return function (target) {
  10270. target["__bjsclassName__"] = name;
  10271. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10272. };
  10273. }
  10274. BABYLON.className = className;
  10275. /**
  10276. * An implementation of a loop for asynchronous functions.
  10277. */
  10278. var AsyncLoop = /** @class */ (function () {
  10279. /**
  10280. * Constroctor.
  10281. * @param iterations the number of iterations.
  10282. * @param _fn the function to run each iteration
  10283. * @param _successCallback the callback that will be called upon succesful execution
  10284. * @param offset starting offset.
  10285. */
  10286. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10287. if (offset === void 0) { offset = 0; }
  10288. this.iterations = iterations;
  10289. this._fn = _fn;
  10290. this._successCallback = _successCallback;
  10291. this.index = offset - 1;
  10292. this._done = false;
  10293. }
  10294. /**
  10295. * Execute the next iteration. Must be called after the last iteration was finished.
  10296. */
  10297. AsyncLoop.prototype.executeNext = function () {
  10298. if (!this._done) {
  10299. if (this.index + 1 < this.iterations) {
  10300. ++this.index;
  10301. this._fn(this);
  10302. }
  10303. else {
  10304. this.breakLoop();
  10305. }
  10306. }
  10307. };
  10308. /**
  10309. * Break the loop and run the success callback.
  10310. */
  10311. AsyncLoop.prototype.breakLoop = function () {
  10312. this._done = true;
  10313. this._successCallback();
  10314. };
  10315. /**
  10316. * Helper function
  10317. */
  10318. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10319. if (offset === void 0) { offset = 0; }
  10320. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10321. loop.executeNext();
  10322. return loop;
  10323. };
  10324. /**
  10325. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10326. * @param iterations total number of iterations
  10327. * @param syncedIterations number of synchronous iterations in each async iteration.
  10328. * @param fn the function to call each iteration.
  10329. * @param callback a success call back that will be called when iterating stops.
  10330. * @param breakFunction a break condition (optional)
  10331. * @param timeout timeout settings for the setTimeout function. default - 0.
  10332. * @constructor
  10333. */
  10334. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10335. if (timeout === void 0) { timeout = 0; }
  10336. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10337. if (breakFunction && breakFunction())
  10338. loop.breakLoop();
  10339. else {
  10340. setTimeout(function () {
  10341. for (var i = 0; i < syncedIterations; ++i) {
  10342. var iteration = (loop.index * syncedIterations) + i;
  10343. if (iteration >= iterations)
  10344. break;
  10345. fn(iteration);
  10346. if (breakFunction && breakFunction()) {
  10347. loop.breakLoop();
  10348. break;
  10349. }
  10350. }
  10351. loop.executeNext();
  10352. }, timeout);
  10353. }
  10354. }, callback);
  10355. };
  10356. return AsyncLoop;
  10357. }());
  10358. BABYLON.AsyncLoop = AsyncLoop;
  10359. })(BABYLON || (BABYLON = {}));
  10360. //# sourceMappingURL=babylon.tools.js.map
  10361. var BABYLON;
  10362. (function (BABYLON) {
  10363. var PromiseStates;
  10364. (function (PromiseStates) {
  10365. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10366. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10367. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10368. })(PromiseStates || (PromiseStates = {}));
  10369. var FulFillmentAgregator = /** @class */ (function () {
  10370. function FulFillmentAgregator() {
  10371. this.count = 0;
  10372. this.target = 0;
  10373. this.results = [];
  10374. }
  10375. return FulFillmentAgregator;
  10376. }());
  10377. var InternalPromise = /** @class */ (function () {
  10378. function InternalPromise(resolver) {
  10379. var _this = this;
  10380. this._state = PromiseStates.Pending;
  10381. this._children = new Array();
  10382. this._rejectWasConsumed = false;
  10383. if (!resolver) {
  10384. return;
  10385. }
  10386. try {
  10387. resolver(function (value) {
  10388. _this._resolve(value);
  10389. }, function (reason) {
  10390. _this._reject(reason);
  10391. });
  10392. }
  10393. catch (e) {
  10394. this._reject(e);
  10395. }
  10396. }
  10397. Object.defineProperty(InternalPromise.prototype, "_result", {
  10398. get: function () {
  10399. return this._resultValue;
  10400. },
  10401. set: function (value) {
  10402. this._resultValue = value;
  10403. if (this._parent && this._parent._result === undefined) {
  10404. this._parent._result = value;
  10405. }
  10406. },
  10407. enumerable: true,
  10408. configurable: true
  10409. });
  10410. InternalPromise.prototype.catch = function (onRejected) {
  10411. return this.then(undefined, onRejected);
  10412. };
  10413. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10414. var _this = this;
  10415. var newPromise = new InternalPromise();
  10416. newPromise._onFulfilled = onFulfilled;
  10417. newPromise._onRejected = onRejected;
  10418. // Composition
  10419. this._children.push(newPromise);
  10420. newPromise._parent = this;
  10421. if (this._state !== PromiseStates.Pending) {
  10422. BABYLON.Tools.SetImmediate(function () {
  10423. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10424. var returnedValue = newPromise._resolve(_this._result);
  10425. if (returnedValue !== undefined && returnedValue !== null) {
  10426. if (returnedValue._state !== undefined) {
  10427. var returnedPromise = returnedValue;
  10428. newPromise._children.push(returnedPromise);
  10429. returnedPromise._parent = newPromise;
  10430. newPromise = returnedPromise;
  10431. }
  10432. else {
  10433. newPromise._result = returnedValue;
  10434. }
  10435. }
  10436. }
  10437. else {
  10438. newPromise._reject(_this._reason);
  10439. }
  10440. });
  10441. }
  10442. return newPromise;
  10443. };
  10444. InternalPromise.prototype._moveChildren = function (children) {
  10445. var _this = this;
  10446. var _a;
  10447. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10448. this._children.forEach(function (child) {
  10449. child._parent = _this;
  10450. });
  10451. if (this._state === PromiseStates.Fulfilled) {
  10452. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10453. var child = _b[_i];
  10454. child._resolve(this._result);
  10455. }
  10456. }
  10457. else if (this._state === PromiseStates.Rejected) {
  10458. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10459. var child = _d[_c];
  10460. child._reject(this._reason);
  10461. }
  10462. }
  10463. };
  10464. InternalPromise.prototype._resolve = function (value) {
  10465. try {
  10466. this._state = PromiseStates.Fulfilled;
  10467. var returnedValue = null;
  10468. if (this._onFulfilled) {
  10469. returnedValue = this._onFulfilled(value);
  10470. }
  10471. if (returnedValue !== undefined && returnedValue !== null) {
  10472. if (returnedValue._state !== undefined) {
  10473. // Transmit children
  10474. var returnedPromise = returnedValue;
  10475. returnedPromise._parent = this;
  10476. returnedPromise._moveChildren(this._children);
  10477. value = returnedPromise._result;
  10478. }
  10479. else {
  10480. value = returnedValue;
  10481. }
  10482. }
  10483. this._result = value;
  10484. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10485. var child = _a[_i];
  10486. child._resolve(value);
  10487. }
  10488. this._children.length = 0;
  10489. delete this._onFulfilled;
  10490. delete this._onRejected;
  10491. }
  10492. catch (e) {
  10493. this._reject(e, true);
  10494. }
  10495. };
  10496. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10497. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10498. this._state = PromiseStates.Rejected;
  10499. this._reason = reason;
  10500. if (this._onRejected && !onLocalThrow) {
  10501. try {
  10502. this._onRejected(reason);
  10503. this._rejectWasConsumed = true;
  10504. }
  10505. catch (e) {
  10506. reason = e;
  10507. }
  10508. }
  10509. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10510. var child = _a[_i];
  10511. if (this._rejectWasConsumed) {
  10512. child._resolve(null);
  10513. }
  10514. else {
  10515. child._reject(reason);
  10516. }
  10517. }
  10518. this._children.length = 0;
  10519. delete this._onFulfilled;
  10520. delete this._onRejected;
  10521. };
  10522. InternalPromise.resolve = function (value) {
  10523. var newPromise = new InternalPromise();
  10524. newPromise._resolve(value);
  10525. return newPromise;
  10526. };
  10527. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10528. promise.then(function (value) {
  10529. agregator.results[index] = value;
  10530. agregator.count++;
  10531. if (agregator.count === agregator.target) {
  10532. agregator.rootPromise._resolve(agregator.results);
  10533. }
  10534. return null;
  10535. }, function (reason) {
  10536. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10537. agregator.rootPromise._reject(reason);
  10538. }
  10539. });
  10540. };
  10541. InternalPromise.all = function (promises) {
  10542. var newPromise = new InternalPromise();
  10543. var agregator = new FulFillmentAgregator();
  10544. agregator.target = promises.length;
  10545. agregator.rootPromise = newPromise;
  10546. if (promises.length) {
  10547. for (var index = 0; index < promises.length; index++) {
  10548. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10549. }
  10550. }
  10551. else {
  10552. newPromise._resolve([]);
  10553. }
  10554. return newPromise;
  10555. };
  10556. InternalPromise.race = function (promises) {
  10557. var newPromise = new InternalPromise();
  10558. if (promises.length) {
  10559. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10560. var promise = promises_1[_i];
  10561. promise.then(function (value) {
  10562. if (newPromise) {
  10563. newPromise._resolve(value);
  10564. newPromise = null;
  10565. }
  10566. return null;
  10567. }, function (reason) {
  10568. if (newPromise) {
  10569. newPromise._reject(reason);
  10570. newPromise = null;
  10571. }
  10572. });
  10573. }
  10574. }
  10575. return newPromise;
  10576. };
  10577. return InternalPromise;
  10578. }());
  10579. /**
  10580. * Helper class that provides a small promise polyfill
  10581. */
  10582. var PromisePolyfill = /** @class */ (function () {
  10583. function PromisePolyfill() {
  10584. }
  10585. /**
  10586. * Static function used to check if the polyfill is required
  10587. * If this is the case then the function will inject the polyfill to window.Promise
  10588. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10589. */
  10590. PromisePolyfill.Apply = function (force) {
  10591. if (force === void 0) { force = false; }
  10592. if (force || typeof Promise === 'undefined') {
  10593. var root = window;
  10594. root.Promise = InternalPromise;
  10595. }
  10596. };
  10597. return PromisePolyfill;
  10598. }());
  10599. BABYLON.PromisePolyfill = PromisePolyfill;
  10600. })(BABYLON || (BABYLON = {}));
  10601. //# sourceMappingURL=babylon.promise.js.map
  10602. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10603. var BABYLON;
  10604. (function (BABYLON) {
  10605. /**
  10606. * Helper class to push actions to a pool of workers.
  10607. */
  10608. var WorkerPool = /** @class */ (function () {
  10609. /**
  10610. * Constructor
  10611. * @param workers Array of workers to use for actions
  10612. */
  10613. function WorkerPool(workers) {
  10614. this._pendingActions = new Array();
  10615. this._workerInfos = workers.map(function (worker) { return ({
  10616. worker: worker,
  10617. active: false
  10618. }); });
  10619. }
  10620. /**
  10621. * Terminates all workers and clears any pending actions.
  10622. */
  10623. WorkerPool.prototype.dispose = function () {
  10624. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10625. var workerInfo = _a[_i];
  10626. workerInfo.worker.terminate();
  10627. }
  10628. delete this._workerInfos;
  10629. delete this._pendingActions;
  10630. };
  10631. /**
  10632. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10633. * pended until a worker has completed its action.
  10634. * @param action The action to perform. Call onComplete when the action is complete.
  10635. */
  10636. WorkerPool.prototype.push = function (action) {
  10637. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10638. var workerInfo = _a[_i];
  10639. if (!workerInfo.active) {
  10640. this._execute(workerInfo, action);
  10641. return;
  10642. }
  10643. }
  10644. this._pendingActions.push(action);
  10645. };
  10646. WorkerPool.prototype._execute = function (workerInfo, action) {
  10647. var _this = this;
  10648. workerInfo.active = true;
  10649. action(workerInfo.worker, function () {
  10650. workerInfo.active = false;
  10651. var nextAction = _this._pendingActions.shift();
  10652. if (nextAction) {
  10653. _this._execute(workerInfo, nextAction);
  10654. }
  10655. });
  10656. };
  10657. return WorkerPool;
  10658. }());
  10659. BABYLON.WorkerPool = WorkerPool;
  10660. })(BABYLON || (BABYLON = {}));
  10661. //# sourceMappingURL=babylon.workerPool.js.map
  10662. var BABYLON;
  10663. (function (BABYLON) {
  10664. /**
  10665. * @hidden
  10666. **/
  10667. var _AlphaState = /** @class */ (function () {
  10668. /**
  10669. * Initializes the state.
  10670. */
  10671. function _AlphaState() {
  10672. this._isAlphaBlendDirty = false;
  10673. this._isBlendFunctionParametersDirty = false;
  10674. this._isBlendEquationParametersDirty = false;
  10675. this._isBlendConstantsDirty = false;
  10676. this._alphaBlend = false;
  10677. this._blendFunctionParameters = new Array(4);
  10678. this._blendEquationParameters = new Array(2);
  10679. this._blendConstants = new Array(4);
  10680. this.reset();
  10681. }
  10682. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10683. get: function () {
  10684. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10685. },
  10686. enumerable: true,
  10687. configurable: true
  10688. });
  10689. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10690. get: function () {
  10691. return this._alphaBlend;
  10692. },
  10693. set: function (value) {
  10694. if (this._alphaBlend === value) {
  10695. return;
  10696. }
  10697. this._alphaBlend = value;
  10698. this._isAlphaBlendDirty = true;
  10699. },
  10700. enumerable: true,
  10701. configurable: true
  10702. });
  10703. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10704. if (this._blendConstants[0] === r &&
  10705. this._blendConstants[1] === g &&
  10706. this._blendConstants[2] === b &&
  10707. this._blendConstants[3] === a) {
  10708. return;
  10709. }
  10710. this._blendConstants[0] = r;
  10711. this._blendConstants[1] = g;
  10712. this._blendConstants[2] = b;
  10713. this._blendConstants[3] = a;
  10714. this._isBlendConstantsDirty = true;
  10715. };
  10716. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10717. if (this._blendFunctionParameters[0] === value0 &&
  10718. this._blendFunctionParameters[1] === value1 &&
  10719. this._blendFunctionParameters[2] === value2 &&
  10720. this._blendFunctionParameters[3] === value3) {
  10721. return;
  10722. }
  10723. this._blendFunctionParameters[0] = value0;
  10724. this._blendFunctionParameters[1] = value1;
  10725. this._blendFunctionParameters[2] = value2;
  10726. this._blendFunctionParameters[3] = value3;
  10727. this._isBlendFunctionParametersDirty = true;
  10728. };
  10729. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10730. if (this._blendEquationParameters[0] === rgb &&
  10731. this._blendEquationParameters[1] === alpha) {
  10732. return;
  10733. }
  10734. this._blendEquationParameters[0] = rgb;
  10735. this._blendEquationParameters[1] = alpha;
  10736. this._isBlendEquationParametersDirty = true;
  10737. };
  10738. _AlphaState.prototype.reset = function () {
  10739. this._alphaBlend = false;
  10740. this._blendFunctionParameters[0] = null;
  10741. this._blendFunctionParameters[1] = null;
  10742. this._blendFunctionParameters[2] = null;
  10743. this._blendFunctionParameters[3] = null;
  10744. this._blendEquationParameters[0] = null;
  10745. this._blendEquationParameters[1] = null;
  10746. this._blendConstants[0] = null;
  10747. this._blendConstants[1] = null;
  10748. this._blendConstants[2] = null;
  10749. this._blendConstants[3] = null;
  10750. this._isAlphaBlendDirty = true;
  10751. this._isBlendFunctionParametersDirty = false;
  10752. this._isBlendEquationParametersDirty = false;
  10753. this._isBlendConstantsDirty = false;
  10754. };
  10755. _AlphaState.prototype.apply = function (gl) {
  10756. if (!this.isDirty) {
  10757. return;
  10758. }
  10759. // Alpha blend
  10760. if (this._isAlphaBlendDirty) {
  10761. if (this._alphaBlend) {
  10762. gl.enable(gl.BLEND);
  10763. }
  10764. else {
  10765. gl.disable(gl.BLEND);
  10766. }
  10767. this._isAlphaBlendDirty = false;
  10768. }
  10769. // Alpha function
  10770. if (this._isBlendFunctionParametersDirty) {
  10771. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10772. this._isBlendFunctionParametersDirty = false;
  10773. }
  10774. // Alpha equation
  10775. if (this._isBlendEquationParametersDirty) {
  10776. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10777. this._isBlendEquationParametersDirty = false;
  10778. }
  10779. // Constants
  10780. if (this._isBlendConstantsDirty) {
  10781. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10782. this._isBlendConstantsDirty = false;
  10783. }
  10784. };
  10785. return _AlphaState;
  10786. }());
  10787. BABYLON._AlphaState = _AlphaState;
  10788. })(BABYLON || (BABYLON = {}));
  10789. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10790. var BABYLON;
  10791. (function (BABYLON) {
  10792. /**
  10793. * @hidden
  10794. **/
  10795. var _DepthCullingState = /** @class */ (function () {
  10796. /**
  10797. * Initializes the state.
  10798. */
  10799. function _DepthCullingState() {
  10800. this._isDepthTestDirty = false;
  10801. this._isDepthMaskDirty = false;
  10802. this._isDepthFuncDirty = false;
  10803. this._isCullFaceDirty = false;
  10804. this._isCullDirty = false;
  10805. this._isZOffsetDirty = false;
  10806. this._isFrontFaceDirty = false;
  10807. this.reset();
  10808. }
  10809. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10810. get: function () {
  10811. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10817. get: function () {
  10818. return this._zOffset;
  10819. },
  10820. set: function (value) {
  10821. if (this._zOffset === value) {
  10822. return;
  10823. }
  10824. this._zOffset = value;
  10825. this._isZOffsetDirty = true;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10831. get: function () {
  10832. return this._cullFace;
  10833. },
  10834. set: function (value) {
  10835. if (this._cullFace === value) {
  10836. return;
  10837. }
  10838. this._cullFace = value;
  10839. this._isCullFaceDirty = true;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10845. get: function () {
  10846. return this._cull;
  10847. },
  10848. set: function (value) {
  10849. if (this._cull === value) {
  10850. return;
  10851. }
  10852. this._cull = value;
  10853. this._isCullDirty = true;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10859. get: function () {
  10860. return this._depthFunc;
  10861. },
  10862. set: function (value) {
  10863. if (this._depthFunc === value) {
  10864. return;
  10865. }
  10866. this._depthFunc = value;
  10867. this._isDepthFuncDirty = true;
  10868. },
  10869. enumerable: true,
  10870. configurable: true
  10871. });
  10872. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10873. get: function () {
  10874. return this._depthMask;
  10875. },
  10876. set: function (value) {
  10877. if (this._depthMask === value) {
  10878. return;
  10879. }
  10880. this._depthMask = value;
  10881. this._isDepthMaskDirty = true;
  10882. },
  10883. enumerable: true,
  10884. configurable: true
  10885. });
  10886. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10887. get: function () {
  10888. return this._depthTest;
  10889. },
  10890. set: function (value) {
  10891. if (this._depthTest === value) {
  10892. return;
  10893. }
  10894. this._depthTest = value;
  10895. this._isDepthTestDirty = true;
  10896. },
  10897. enumerable: true,
  10898. configurable: true
  10899. });
  10900. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10901. get: function () {
  10902. return this._frontFace;
  10903. },
  10904. set: function (value) {
  10905. if (this._frontFace === value) {
  10906. return;
  10907. }
  10908. this._frontFace = value;
  10909. this._isFrontFaceDirty = true;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. _DepthCullingState.prototype.reset = function () {
  10915. this._depthMask = true;
  10916. this._depthTest = true;
  10917. this._depthFunc = null;
  10918. this._cullFace = null;
  10919. this._cull = null;
  10920. this._zOffset = 0;
  10921. this._frontFace = null;
  10922. this._isDepthTestDirty = true;
  10923. this._isDepthMaskDirty = true;
  10924. this._isDepthFuncDirty = false;
  10925. this._isCullFaceDirty = false;
  10926. this._isCullDirty = false;
  10927. this._isZOffsetDirty = false;
  10928. this._isFrontFaceDirty = false;
  10929. };
  10930. _DepthCullingState.prototype.apply = function (gl) {
  10931. if (!this.isDirty) {
  10932. return;
  10933. }
  10934. // Cull
  10935. if (this._isCullDirty) {
  10936. if (this.cull) {
  10937. gl.enable(gl.CULL_FACE);
  10938. }
  10939. else {
  10940. gl.disable(gl.CULL_FACE);
  10941. }
  10942. this._isCullDirty = false;
  10943. }
  10944. // Cull face
  10945. if (this._isCullFaceDirty) {
  10946. gl.cullFace(this.cullFace);
  10947. this._isCullFaceDirty = false;
  10948. }
  10949. // Depth mask
  10950. if (this._isDepthMaskDirty) {
  10951. gl.depthMask(this.depthMask);
  10952. this._isDepthMaskDirty = false;
  10953. }
  10954. // Depth test
  10955. if (this._isDepthTestDirty) {
  10956. if (this.depthTest) {
  10957. gl.enable(gl.DEPTH_TEST);
  10958. }
  10959. else {
  10960. gl.disable(gl.DEPTH_TEST);
  10961. }
  10962. this._isDepthTestDirty = false;
  10963. }
  10964. // Depth func
  10965. if (this._isDepthFuncDirty) {
  10966. gl.depthFunc(this.depthFunc);
  10967. this._isDepthFuncDirty = false;
  10968. }
  10969. // zOffset
  10970. if (this._isZOffsetDirty) {
  10971. if (this.zOffset) {
  10972. gl.enable(gl.POLYGON_OFFSET_FILL);
  10973. gl.polygonOffset(this.zOffset, 0);
  10974. }
  10975. else {
  10976. gl.disable(gl.POLYGON_OFFSET_FILL);
  10977. }
  10978. this._isZOffsetDirty = false;
  10979. }
  10980. // Front face
  10981. if (this._isFrontFaceDirty) {
  10982. gl.frontFace(this.frontFace);
  10983. this._isFrontFaceDirty = false;
  10984. }
  10985. };
  10986. return _DepthCullingState;
  10987. }());
  10988. BABYLON._DepthCullingState = _DepthCullingState;
  10989. })(BABYLON || (BABYLON = {}));
  10990. //# sourceMappingURL=babylon.depthCullingState.js.map
  10991. var BABYLON;
  10992. (function (BABYLON) {
  10993. /**
  10994. * @hidden
  10995. **/
  10996. var _StencilState = /** @class */ (function () {
  10997. function _StencilState() {
  10998. this._isStencilTestDirty = false;
  10999. this._isStencilMaskDirty = false;
  11000. this._isStencilFuncDirty = false;
  11001. this._isStencilOpDirty = false;
  11002. this.reset();
  11003. }
  11004. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11005. get: function () {
  11006. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11007. },
  11008. enumerable: true,
  11009. configurable: true
  11010. });
  11011. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11012. get: function () {
  11013. return this._stencilFunc;
  11014. },
  11015. set: function (value) {
  11016. if (this._stencilFunc === value) {
  11017. return;
  11018. }
  11019. this._stencilFunc = value;
  11020. this._isStencilFuncDirty = true;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11026. get: function () {
  11027. return this._stencilFuncRef;
  11028. },
  11029. set: function (value) {
  11030. if (this._stencilFuncRef === value) {
  11031. return;
  11032. }
  11033. this._stencilFuncRef = value;
  11034. this._isStencilFuncDirty = true;
  11035. },
  11036. enumerable: true,
  11037. configurable: true
  11038. });
  11039. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11040. get: function () {
  11041. return this._stencilFuncMask;
  11042. },
  11043. set: function (value) {
  11044. if (this._stencilFuncMask === value) {
  11045. return;
  11046. }
  11047. this._stencilFuncMask = value;
  11048. this._isStencilFuncDirty = true;
  11049. },
  11050. enumerable: true,
  11051. configurable: true
  11052. });
  11053. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11054. get: function () {
  11055. return this._stencilOpStencilFail;
  11056. },
  11057. set: function (value) {
  11058. if (this._stencilOpStencilFail === value) {
  11059. return;
  11060. }
  11061. this._stencilOpStencilFail = value;
  11062. this._isStencilOpDirty = true;
  11063. },
  11064. enumerable: true,
  11065. configurable: true
  11066. });
  11067. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11068. get: function () {
  11069. return this._stencilOpDepthFail;
  11070. },
  11071. set: function (value) {
  11072. if (this._stencilOpDepthFail === value) {
  11073. return;
  11074. }
  11075. this._stencilOpDepthFail = value;
  11076. this._isStencilOpDirty = true;
  11077. },
  11078. enumerable: true,
  11079. configurable: true
  11080. });
  11081. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11082. get: function () {
  11083. return this._stencilOpStencilDepthPass;
  11084. },
  11085. set: function (value) {
  11086. if (this._stencilOpStencilDepthPass === value) {
  11087. return;
  11088. }
  11089. this._stencilOpStencilDepthPass = value;
  11090. this._isStencilOpDirty = true;
  11091. },
  11092. enumerable: true,
  11093. configurable: true
  11094. });
  11095. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11096. get: function () {
  11097. return this._stencilMask;
  11098. },
  11099. set: function (value) {
  11100. if (this._stencilMask === value) {
  11101. return;
  11102. }
  11103. this._stencilMask = value;
  11104. this._isStencilMaskDirty = true;
  11105. },
  11106. enumerable: true,
  11107. configurable: true
  11108. });
  11109. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11110. get: function () {
  11111. return this._stencilTest;
  11112. },
  11113. set: function (value) {
  11114. if (this._stencilTest === value) {
  11115. return;
  11116. }
  11117. this._stencilTest = value;
  11118. this._isStencilTestDirty = true;
  11119. },
  11120. enumerable: true,
  11121. configurable: true
  11122. });
  11123. _StencilState.prototype.reset = function () {
  11124. this._stencilTest = false;
  11125. this._stencilMask = 0xFF;
  11126. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11127. this._stencilFuncRef = 1;
  11128. this._stencilFuncMask = 0xFF;
  11129. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11130. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11131. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11132. this._isStencilTestDirty = true;
  11133. this._isStencilMaskDirty = true;
  11134. this._isStencilFuncDirty = true;
  11135. this._isStencilOpDirty = true;
  11136. };
  11137. _StencilState.prototype.apply = function (gl) {
  11138. if (!this.isDirty) {
  11139. return;
  11140. }
  11141. // Stencil test
  11142. if (this._isStencilTestDirty) {
  11143. if (this.stencilTest) {
  11144. gl.enable(gl.STENCIL_TEST);
  11145. }
  11146. else {
  11147. gl.disable(gl.STENCIL_TEST);
  11148. }
  11149. this._isStencilTestDirty = false;
  11150. }
  11151. // Stencil mask
  11152. if (this._isStencilMaskDirty) {
  11153. gl.stencilMask(this.stencilMask);
  11154. this._isStencilMaskDirty = false;
  11155. }
  11156. // Stencil func
  11157. if (this._isStencilFuncDirty) {
  11158. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11159. this._isStencilFuncDirty = false;
  11160. }
  11161. // Stencil op
  11162. if (this._isStencilOpDirty) {
  11163. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11164. this._isStencilOpDirty = false;
  11165. }
  11166. };
  11167. return _StencilState;
  11168. }());
  11169. BABYLON._StencilState = _StencilState;
  11170. })(BABYLON || (BABYLON = {}));
  11171. //# sourceMappingURL=babylon.stencilState.js.map
  11172. var __assign = (this && this.__assign) || function () {
  11173. __assign = Object.assign || function(t) {
  11174. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11175. s = arguments[i];
  11176. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11177. t[p] = s[p];
  11178. }
  11179. return t;
  11180. };
  11181. return __assign.apply(this, arguments);
  11182. };
  11183. var BABYLON;
  11184. (function (BABYLON) {
  11185. /**
  11186. * Keeps track of all the buffer info used in engine.
  11187. */
  11188. var BufferPointer = /** @class */ (function () {
  11189. function BufferPointer() {
  11190. }
  11191. return BufferPointer;
  11192. }());
  11193. /**
  11194. * Interface for attribute information associated with buffer instanciation
  11195. */
  11196. var InstancingAttributeInfo = /** @class */ (function () {
  11197. function InstancingAttributeInfo() {
  11198. }
  11199. return InstancingAttributeInfo;
  11200. }());
  11201. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11202. /**
  11203. * Define options used to create a render target texture
  11204. */
  11205. var RenderTargetCreationOptions = /** @class */ (function () {
  11206. function RenderTargetCreationOptions() {
  11207. }
  11208. return RenderTargetCreationOptions;
  11209. }());
  11210. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11211. /**
  11212. * Define options used to create a depth texture
  11213. */
  11214. var DepthTextureCreationOptions = /** @class */ (function () {
  11215. function DepthTextureCreationOptions() {
  11216. }
  11217. return DepthTextureCreationOptions;
  11218. }());
  11219. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11220. /**
  11221. * Class used to describe the capabilities of the engine relatively to the current browser
  11222. */
  11223. var EngineCapabilities = /** @class */ (function () {
  11224. function EngineCapabilities() {
  11225. }
  11226. return EngineCapabilities;
  11227. }());
  11228. BABYLON.EngineCapabilities = EngineCapabilities;
  11229. /**
  11230. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11231. */
  11232. var Engine = /** @class */ (function () {
  11233. /**
  11234. * Creates a new engine
  11235. * @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
  11236. * @param antialias defines enable antialiasing (default: false)
  11237. * @param options defines further options to be sent to the getContext() function
  11238. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11239. */
  11240. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11241. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11242. var _this = this;
  11243. // Public members
  11244. /**
  11245. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11246. */
  11247. this.forcePOTTextures = false;
  11248. /**
  11249. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11250. */
  11251. this.isFullscreen = false;
  11252. /**
  11253. * Gets a boolean indicating if the pointer is currently locked
  11254. */
  11255. this.isPointerLock = false;
  11256. /**
  11257. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11258. */
  11259. this.cullBackFaces = true;
  11260. /**
  11261. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11262. */
  11263. this.renderEvenInBackground = true;
  11264. /**
  11265. * Gets or sets a boolean indicating that cache can be kept between frames
  11266. */
  11267. this.preventCacheWipeBetweenFrames = false;
  11268. /**
  11269. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11270. **/
  11271. this.enableOfflineSupport = false;
  11272. /**
  11273. * 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)
  11274. **/
  11275. this.disableManifestCheck = false;
  11276. /**
  11277. * Gets the list of created scenes
  11278. */
  11279. this.scenes = new Array();
  11280. /**
  11281. * Gets the list of created postprocesses
  11282. */
  11283. this.postProcesses = new Array();
  11284. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11285. this.validateShaderPrograms = false;
  11286. // Observables
  11287. /**
  11288. * Observable event triggered each time the rendering canvas is resized
  11289. */
  11290. this.onResizeObservable = new BABYLON.Observable();
  11291. /**
  11292. * Observable event triggered each time the canvas loses focus
  11293. */
  11294. this.onCanvasBlurObservable = new BABYLON.Observable();
  11295. /**
  11296. * Observable event triggered each time the canvas gains focus
  11297. */
  11298. this.onCanvasFocusObservable = new BABYLON.Observable();
  11299. /**
  11300. * Observable event triggered each time the canvas receives pointerout event
  11301. */
  11302. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11303. /**
  11304. * Observable event triggered before each texture is initialized
  11305. */
  11306. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11307. //WebVR
  11308. this._vrDisplay = undefined;
  11309. this._vrSupported = false;
  11310. this._vrExclusivePointerMode = false;
  11311. // Uniform buffers list
  11312. /**
  11313. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11314. */
  11315. this.disableUniformBuffers = false;
  11316. /** @hidden */
  11317. this._uniformBuffers = new Array();
  11318. // Observables
  11319. /**
  11320. * Observable raised when the engine begins a new frame
  11321. */
  11322. this.onBeginFrameObservable = new BABYLON.Observable();
  11323. /**
  11324. * Observable raised when the engine ends the current frame
  11325. */
  11326. this.onEndFrameObservable = new BABYLON.Observable();
  11327. /**
  11328. * Observable raised when the engine is about to compile a shader
  11329. */
  11330. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11331. /**
  11332. * Observable raised when the engine has jsut compiled a shader
  11333. */
  11334. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11335. this._windowIsBackground = false;
  11336. this._webGLVersion = 1.0;
  11337. /** @hidden */
  11338. this._badOS = false;
  11339. /** @hidden */
  11340. this._badDesktopOS = false;
  11341. /**
  11342. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11343. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11344. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11345. */
  11346. this.disableTextureBindingOptimization = false;
  11347. /**
  11348. * Observable signaled when VR display mode changes
  11349. */
  11350. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11351. /**
  11352. * Observable signaled when VR request present is complete
  11353. */
  11354. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11355. /**
  11356. * Observable signaled when VR request present starts
  11357. */
  11358. this.onVRRequestPresentStart = new BABYLON.Observable();
  11359. this._colorWrite = true;
  11360. /** @hidden */
  11361. this._drawCalls = new BABYLON.PerfCounter();
  11362. /** @hidden */
  11363. this._textureCollisions = new BABYLON.PerfCounter();
  11364. this._renderingQueueLaunched = false;
  11365. this._activeRenderLoops = new Array();
  11366. // Deterministic lockstepMaxSteps
  11367. this._deterministicLockstep = false;
  11368. this._lockstepMaxSteps = 4;
  11369. // Lost context
  11370. /**
  11371. * Observable signaled when a context lost event is raised
  11372. */
  11373. this.onContextLostObservable = new BABYLON.Observable();
  11374. /**
  11375. * Observable signaled when a context restored event is raised
  11376. */
  11377. this.onContextRestoredObservable = new BABYLON.Observable();
  11378. this._contextWasLost = false;
  11379. this._doNotHandleContextLost = false;
  11380. // FPS
  11381. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11382. this._fps = 60;
  11383. this._deltaTime = 0;
  11384. /**
  11385. * Turn this value on if you want to pause FPS computation when in background
  11386. */
  11387. this.disablePerformanceMonitorInBackground = false;
  11388. // States
  11389. /** @hidden */
  11390. this._depthCullingState = new BABYLON._DepthCullingState();
  11391. /** @hidden */
  11392. this._stencilState = new BABYLON._StencilState();
  11393. /** @hidden */
  11394. this._alphaState = new BABYLON._AlphaState();
  11395. /** @hidden */
  11396. this._alphaMode = Engine.ALPHA_DISABLE;
  11397. // Cache
  11398. this._internalTexturesCache = new Array();
  11399. /** @hidden */
  11400. this._activeChannel = 0;
  11401. this._currentTextureChannel = -1;
  11402. /** @hidden */
  11403. this._boundTexturesCache = {};
  11404. this._compiledEffects = {};
  11405. this._vertexAttribArraysEnabled = [];
  11406. this._uintIndicesCurrentlySet = false;
  11407. this._currentBoundBuffer = new Array();
  11408. /** @hidden */
  11409. this._currentFramebuffer = null;
  11410. this._currentBufferPointers = new Array();
  11411. this._currentInstanceLocations = new Array();
  11412. this._currentInstanceBuffers = new Array();
  11413. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11414. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11415. this._vaoRecordInProgress = false;
  11416. this._mustWipeVertexAttributes = false;
  11417. this._nextFreeTextureSlots = new Array();
  11418. this._maxSimultaneousTextures = 0;
  11419. this._activeRequests = new Array();
  11420. // Hardware supported Compressed Textures
  11421. this._texturesSupported = new Array();
  11422. /**
  11423. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11424. */
  11425. this.premultipliedAlpha = true;
  11426. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11427. this._onVRFullScreenTriggered = function () {
  11428. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11429. //get the old size before we change
  11430. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11431. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11432. //get the width and height, change the render size
  11433. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11434. _this.setHardwareScalingLevel(1);
  11435. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11436. }
  11437. else {
  11438. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11439. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11440. }
  11441. };
  11442. this._unpackFlipYCached = null;
  11443. /**
  11444. * In case you are sharing the context with other applications, it might
  11445. * be interested to not cache the unpack flip y state to ensure a consistent
  11446. * value would be set.
  11447. */
  11448. this.enableUnpackFlipYCached = true;
  11449. this._boundUniforms = {};
  11450. // Register promises
  11451. BABYLON.PromisePolyfill.Apply();
  11452. var canvas = null;
  11453. Engine.Instances.push(this);
  11454. if (!canvasOrContext) {
  11455. return;
  11456. }
  11457. options = options || {};
  11458. if (canvasOrContext.getContext) {
  11459. canvas = canvasOrContext;
  11460. this._renderingCanvas = canvas;
  11461. if (antialias != null) {
  11462. options.antialias = antialias;
  11463. }
  11464. if (options.deterministicLockstep === undefined) {
  11465. options.deterministicLockstep = false;
  11466. }
  11467. if (options.lockstepMaxSteps === undefined) {
  11468. options.lockstepMaxSteps = 4;
  11469. }
  11470. if (options.preserveDrawingBuffer === undefined) {
  11471. options.preserveDrawingBuffer = false;
  11472. }
  11473. if (options.audioEngine === undefined) {
  11474. options.audioEngine = true;
  11475. }
  11476. if (options.stencil === undefined) {
  11477. options.stencil = true;
  11478. }
  11479. if (options.premultipliedAlpha === false) {
  11480. this.premultipliedAlpha = false;
  11481. }
  11482. this._deterministicLockstep = options.deterministicLockstep;
  11483. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11484. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11485. // Exceptions
  11486. if (navigator && navigator.userAgent) {
  11487. var ua = navigator.userAgent;
  11488. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11489. var exception = _a[_i];
  11490. var key = exception.key;
  11491. var targets = exception.targets;
  11492. if (ua.indexOf(key) > -1) {
  11493. if (exception.capture && exception.captureConstraint) {
  11494. var capture = exception.capture;
  11495. var constraint = exception.captureConstraint;
  11496. var regex = new RegExp(capture);
  11497. var matches = regex.exec(ua);
  11498. if (matches && matches.length > 0) {
  11499. var capturedValue = parseInt(matches[matches.length - 1]);
  11500. if (capturedValue >= constraint) {
  11501. continue;
  11502. }
  11503. }
  11504. }
  11505. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11506. var target = targets_1[_b];
  11507. switch (target) {
  11508. case "uniformBuffer":
  11509. this.disableUniformBuffers = true;
  11510. break;
  11511. case "textureBindingOptimization":
  11512. this.disableTextureBindingOptimization = true;
  11513. break;
  11514. }
  11515. }
  11516. }
  11517. }
  11518. }
  11519. // GL
  11520. if (!options.disableWebGL2Support) {
  11521. try {
  11522. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11523. if (this._gl) {
  11524. this._webGLVersion = 2.0;
  11525. }
  11526. }
  11527. catch (e) {
  11528. // Do nothing
  11529. }
  11530. }
  11531. if (!this._gl) {
  11532. if (!canvas) {
  11533. throw new Error("The provided canvas is null or undefined.");
  11534. }
  11535. try {
  11536. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11537. }
  11538. catch (e) {
  11539. throw new Error("WebGL not supported");
  11540. }
  11541. }
  11542. if (!this._gl) {
  11543. throw new Error("WebGL not supported");
  11544. }
  11545. this._onCanvasFocus = function () {
  11546. _this.onCanvasFocusObservable.notifyObservers(_this);
  11547. };
  11548. this._onCanvasBlur = function () {
  11549. _this.onCanvasBlurObservable.notifyObservers(_this);
  11550. };
  11551. canvas.addEventListener("focus", this._onCanvasFocus);
  11552. canvas.addEventListener("blur", this._onCanvasBlur);
  11553. this._onBlur = function () {
  11554. if (_this.disablePerformanceMonitorInBackground) {
  11555. _this._performanceMonitor.disable();
  11556. }
  11557. _this._windowIsBackground = true;
  11558. };
  11559. this._onFocus = function () {
  11560. if (_this.disablePerformanceMonitorInBackground) {
  11561. _this._performanceMonitor.enable();
  11562. }
  11563. _this._windowIsBackground = false;
  11564. };
  11565. this._onCanvasPointerOut = function (ev) {
  11566. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11567. };
  11568. window.addEventListener("blur", this._onBlur);
  11569. window.addEventListener("focus", this._onFocus);
  11570. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11571. // Context lost
  11572. if (!this._doNotHandleContextLost) {
  11573. this._onContextLost = function (evt) {
  11574. evt.preventDefault();
  11575. _this._contextWasLost = true;
  11576. BABYLON.Tools.Warn("WebGL context lost.");
  11577. _this.onContextLostObservable.notifyObservers(_this);
  11578. };
  11579. this._onContextRestored = function (evt) {
  11580. // Adding a timeout to avoid race condition at browser level
  11581. setTimeout(function () {
  11582. // Rebuild gl context
  11583. _this._initGLContext();
  11584. // Rebuild effects
  11585. _this._rebuildEffects();
  11586. // Rebuild textures
  11587. _this._rebuildInternalTextures();
  11588. // Rebuild buffers
  11589. _this._rebuildBuffers();
  11590. // Cache
  11591. _this.wipeCaches(true);
  11592. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11593. _this.onContextRestoredObservable.notifyObservers(_this);
  11594. _this._contextWasLost = false;
  11595. }, 0);
  11596. };
  11597. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11598. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11599. }
  11600. }
  11601. else {
  11602. this._gl = canvasOrContext;
  11603. this._renderingCanvas = this._gl.canvas;
  11604. if (this._gl.renderbufferStorageMultisample) {
  11605. this._webGLVersion = 2.0;
  11606. }
  11607. options.stencil = this._gl.getContextAttributes().stencil;
  11608. }
  11609. // Viewport
  11610. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11611. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11612. this.resize();
  11613. this._isStencilEnable = options.stencil ? true : false;
  11614. this._initGLContext();
  11615. if (canvas) {
  11616. // Fullscreen
  11617. this._onFullscreenChange = function () {
  11618. if (document.fullscreen !== undefined) {
  11619. _this.isFullscreen = document.fullscreen;
  11620. }
  11621. else if (document.mozFullScreen !== undefined) {
  11622. _this.isFullscreen = document.mozFullScreen;
  11623. }
  11624. else if (document.webkitIsFullScreen !== undefined) {
  11625. _this.isFullscreen = document.webkitIsFullScreen;
  11626. }
  11627. else if (document.msIsFullScreen !== undefined) {
  11628. _this.isFullscreen = document.msIsFullScreen;
  11629. }
  11630. // Pointer lock
  11631. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11632. canvas.requestPointerLock = canvas.requestPointerLock ||
  11633. canvas.msRequestPointerLock ||
  11634. canvas.mozRequestPointerLock ||
  11635. canvas.webkitRequestPointerLock;
  11636. if (canvas.requestPointerLock) {
  11637. canvas.requestPointerLock();
  11638. }
  11639. }
  11640. };
  11641. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11642. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11643. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11644. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11645. // Pointer lock
  11646. this._onPointerLockChange = function () {
  11647. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11648. document.webkitPointerLockElement === canvas ||
  11649. document.msPointerLockElement === canvas ||
  11650. document.pointerLockElement === canvas);
  11651. };
  11652. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11653. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11654. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11655. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11656. this._onVRDisplayPointerRestricted = function () {
  11657. if (canvas) {
  11658. canvas.requestPointerLock();
  11659. }
  11660. };
  11661. this._onVRDisplayPointerUnrestricted = function () {
  11662. document.exitPointerLock();
  11663. };
  11664. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11665. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11666. }
  11667. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11668. Engine.audioEngine = new BABYLON.AudioEngine();
  11669. }
  11670. // Prepare buffer pointers
  11671. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11672. this._currentBufferPointers[i] = new BufferPointer();
  11673. }
  11674. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11675. // Load WebVR Devices
  11676. if (options.autoEnableWebVR) {
  11677. this.initWebVR();
  11678. }
  11679. // Detect if we are running on a faulty buggy OS.
  11680. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11681. // Detect if we are running on a faulty buggy desktop OS.
  11682. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11683. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11684. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11685. }
  11686. Object.defineProperty(Engine, "LastCreatedEngine", {
  11687. /**
  11688. * Gets the latest created engine
  11689. */
  11690. get: function () {
  11691. if (Engine.Instances.length === 0) {
  11692. return null;
  11693. }
  11694. return Engine.Instances[Engine.Instances.length - 1];
  11695. },
  11696. enumerable: true,
  11697. configurable: true
  11698. });
  11699. Object.defineProperty(Engine, "LastCreatedScene", {
  11700. /**
  11701. * Gets the latest created scene
  11702. */
  11703. get: function () {
  11704. var lastCreatedEngine = Engine.LastCreatedEngine;
  11705. if (!lastCreatedEngine) {
  11706. return null;
  11707. }
  11708. if (lastCreatedEngine.scenes.length === 0) {
  11709. return null;
  11710. }
  11711. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. /**
  11717. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11718. * @param flag defines which part of the materials must be marked as dirty
  11719. * @param predicate defines a predicate used to filter which materials should be affected
  11720. */
  11721. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11722. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11723. var engine = Engine.Instances[engineIndex];
  11724. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11725. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11726. }
  11727. }
  11728. };
  11729. Object.defineProperty(Engine, "Version", {
  11730. /**
  11731. * Returns the current version of the framework
  11732. */
  11733. get: function () {
  11734. return "3.3.0-beta.5";
  11735. },
  11736. enumerable: true,
  11737. configurable: true
  11738. });
  11739. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11740. /**
  11741. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11742. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11743. */
  11744. get: function () {
  11745. return this._vrExclusivePointerMode;
  11746. },
  11747. enumerable: true,
  11748. configurable: true
  11749. });
  11750. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11751. /**
  11752. * Gets a boolean indicating that the engine supports uniform buffers
  11753. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11754. */
  11755. get: function () {
  11756. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11757. },
  11758. enumerable: true,
  11759. configurable: true
  11760. });
  11761. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11762. /**
  11763. * Gets a boolean indicating that only power of 2 textures are supported
  11764. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11765. */
  11766. get: function () {
  11767. return this._webGLVersion < 2 || this.forcePOTTextures;
  11768. },
  11769. enumerable: true,
  11770. configurable: true
  11771. });
  11772. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11773. /**
  11774. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11775. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11776. */
  11777. get: function () {
  11778. return this._doNotHandleContextLost;
  11779. },
  11780. set: function (value) {
  11781. this._doNotHandleContextLost = value;
  11782. },
  11783. enumerable: true,
  11784. configurable: true
  11785. });
  11786. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11787. /**
  11788. * Gets the performance monitor attached to this engine
  11789. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11790. */
  11791. get: function () {
  11792. return this._performanceMonitor;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11798. /**
  11799. * Gets the list of texture formats supported
  11800. */
  11801. get: function () {
  11802. return this._texturesSupported;
  11803. },
  11804. enumerable: true,
  11805. configurable: true
  11806. });
  11807. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11808. /**
  11809. * Gets the list of texture formats in use
  11810. */
  11811. get: function () {
  11812. return this._textureFormatInUse;
  11813. },
  11814. enumerable: true,
  11815. configurable: true
  11816. });
  11817. Object.defineProperty(Engine.prototype, "currentViewport", {
  11818. /**
  11819. * Gets the current viewport
  11820. */
  11821. get: function () {
  11822. return this._cachedViewport;
  11823. },
  11824. enumerable: true,
  11825. configurable: true
  11826. });
  11827. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11828. /**
  11829. * Gets the default empty texture
  11830. */
  11831. get: function () {
  11832. if (!this._emptyTexture) {
  11833. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11834. }
  11835. return this._emptyTexture;
  11836. },
  11837. enumerable: true,
  11838. configurable: true
  11839. });
  11840. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11841. /**
  11842. * Gets the default empty 3D texture
  11843. */
  11844. get: function () {
  11845. if (!this._emptyTexture3D) {
  11846. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11847. }
  11848. return this._emptyTexture3D;
  11849. },
  11850. enumerable: true,
  11851. configurable: true
  11852. });
  11853. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11854. /**
  11855. * Gets the default empty cube texture
  11856. */
  11857. get: function () {
  11858. if (!this._emptyCubeTexture) {
  11859. var faceData = new Uint8Array(4);
  11860. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11861. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11862. }
  11863. return this._emptyCubeTexture;
  11864. },
  11865. enumerable: true,
  11866. configurable: true
  11867. });
  11868. Engine.prototype._rebuildInternalTextures = function () {
  11869. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11870. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11871. var internalTexture = currentState_1[_i];
  11872. internalTexture._rebuild();
  11873. }
  11874. };
  11875. Engine.prototype._rebuildEffects = function () {
  11876. for (var key in this._compiledEffects) {
  11877. var effect = this._compiledEffects[key];
  11878. effect._prepareEffect();
  11879. }
  11880. BABYLON.Effect.ResetCache();
  11881. };
  11882. Engine.prototype._rebuildBuffers = function () {
  11883. // Index / Vertex
  11884. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11885. var scene = _a[_i];
  11886. scene.resetCachedMaterial();
  11887. scene._rebuildGeometries();
  11888. scene._rebuildTextures();
  11889. }
  11890. // Uniforms
  11891. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11892. var uniformBuffer = _c[_b];
  11893. uniformBuffer._rebuild();
  11894. }
  11895. };
  11896. Engine.prototype._initGLContext = function () {
  11897. // Caps
  11898. this._caps = new EngineCapabilities();
  11899. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11900. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11901. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11902. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11903. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11904. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11905. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11906. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11907. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11908. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11909. // Infos
  11910. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11911. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11912. if (rendererInfo != null) {
  11913. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11914. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11915. }
  11916. if (!this._glVendor) {
  11917. this._glVendor = "Unknown vendor";
  11918. }
  11919. if (!this._glRenderer) {
  11920. this._glRenderer = "Unknown renderer";
  11921. }
  11922. // Constants
  11923. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11924. if (this._gl.RGBA16F !== 0x881A) {
  11925. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11926. }
  11927. if (this._gl.RGBA32F !== 0x8814) {
  11928. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11929. }
  11930. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11931. this._gl.DEPTH24_STENCIL8 = 35056;
  11932. }
  11933. // Extensions
  11934. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11935. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11936. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11937. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11938. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11939. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11940. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11941. 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');
  11942. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11943. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11944. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11945. this._caps.highPrecisionShaderSupported = true;
  11946. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11947. if (this._caps.timerQuery) {
  11948. if (this._webGLVersion === 1) {
  11949. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11950. }
  11951. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11952. }
  11953. // Checks if some of the format renders first to allow the use of webgl inspector.
  11954. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11955. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11956. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11957. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11958. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11959. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11960. if (this._webGLVersion > 1) {
  11961. this._gl.HALF_FLOAT_OES = 0x140B;
  11962. }
  11963. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11964. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11965. // Draw buffers
  11966. if (this._webGLVersion > 1) {
  11967. this._caps.drawBuffersExtension = true;
  11968. }
  11969. else {
  11970. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11971. if (drawBuffersExtension !== null) {
  11972. this._caps.drawBuffersExtension = true;
  11973. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11974. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11975. for (var i = 0; i < 16; i++) {
  11976. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11977. }
  11978. }
  11979. else {
  11980. this._caps.drawBuffersExtension = false;
  11981. }
  11982. }
  11983. // Depth Texture
  11984. if (this._webGLVersion > 1) {
  11985. this._caps.depthTextureExtension = true;
  11986. }
  11987. else {
  11988. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11989. if (depthTextureExtension != null) {
  11990. this._caps.depthTextureExtension = true;
  11991. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11992. }
  11993. }
  11994. // Vertex array object
  11995. if (this._webGLVersion > 1) {
  11996. this._caps.vertexArrayObject = true;
  11997. }
  11998. else {
  11999. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12000. if (vertexArrayObjectExtension != null) {
  12001. this._caps.vertexArrayObject = true;
  12002. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12003. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12004. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12005. }
  12006. else {
  12007. this._caps.vertexArrayObject = false;
  12008. }
  12009. }
  12010. // Instances count
  12011. if (this._webGLVersion > 1) {
  12012. this._caps.instancedArrays = true;
  12013. }
  12014. else {
  12015. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12016. if (instanceExtension != null) {
  12017. this._caps.instancedArrays = true;
  12018. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12019. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12020. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12021. }
  12022. else {
  12023. this._caps.instancedArrays = false;
  12024. }
  12025. }
  12026. // Intelligently add supported compressed formats in order to check for.
  12027. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12028. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12029. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12030. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12031. if (this._caps.astc)
  12032. this.texturesSupported.push('-astc.ktx');
  12033. if (this._caps.s3tc)
  12034. this.texturesSupported.push('-dxt.ktx');
  12035. if (this._caps.pvrtc)
  12036. this.texturesSupported.push('-pvrtc.ktx');
  12037. if (this._caps.etc2)
  12038. this.texturesSupported.push('-etc2.ktx');
  12039. if (this._caps.etc1)
  12040. this.texturesSupported.push('-etc1.ktx');
  12041. if (this._gl.getShaderPrecisionFormat) {
  12042. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12043. if (highp) {
  12044. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12045. }
  12046. }
  12047. // Depth buffer
  12048. this.setDepthBuffer(true);
  12049. this.setDepthFunctionToLessOrEqual();
  12050. this.setDepthWrite(true);
  12051. // Texture maps
  12052. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12053. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12054. this._nextFreeTextureSlots.push(slot);
  12055. }
  12056. };
  12057. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12058. /**
  12059. * Gets version of the current webGL context
  12060. */
  12061. get: function () {
  12062. return this._webGLVersion;
  12063. },
  12064. enumerable: true,
  12065. configurable: true
  12066. });
  12067. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12068. /**
  12069. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12070. */
  12071. get: function () {
  12072. return this._isStencilEnable;
  12073. },
  12074. enumerable: true,
  12075. configurable: true
  12076. });
  12077. Engine.prototype._prepareWorkingCanvas = function () {
  12078. if (this._workingCanvas) {
  12079. return;
  12080. }
  12081. this._workingCanvas = document.createElement("canvas");
  12082. var context = this._workingCanvas.getContext("2d");
  12083. if (context) {
  12084. this._workingContext = context;
  12085. }
  12086. };
  12087. /**
  12088. * Reset the texture cache to empty state
  12089. */
  12090. Engine.prototype.resetTextureCache = function () {
  12091. for (var key in this._boundTexturesCache) {
  12092. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12093. continue;
  12094. }
  12095. var boundTexture = this._boundTexturesCache[key];
  12096. if (boundTexture) {
  12097. this._removeDesignatedSlot(boundTexture);
  12098. }
  12099. this._boundTexturesCache[key] = null;
  12100. }
  12101. if (!this.disableTextureBindingOptimization) {
  12102. this._nextFreeTextureSlots = [];
  12103. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12104. this._nextFreeTextureSlots.push(slot);
  12105. }
  12106. }
  12107. this._currentTextureChannel = -1;
  12108. };
  12109. /**
  12110. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12111. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12112. * @returns true if engine is in deterministic lock step mode
  12113. */
  12114. Engine.prototype.isDeterministicLockStep = function () {
  12115. return this._deterministicLockstep;
  12116. };
  12117. /**
  12118. * Gets the max steps when engine is running in deterministic lock step
  12119. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12120. * @returns the max steps
  12121. */
  12122. Engine.prototype.getLockstepMaxSteps = function () {
  12123. return this._lockstepMaxSteps;
  12124. };
  12125. /**
  12126. * Gets an object containing information about the current webGL context
  12127. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12128. */
  12129. Engine.prototype.getGlInfo = function () {
  12130. return {
  12131. vendor: this._glVendor,
  12132. renderer: this._glRenderer,
  12133. version: this._glVersion
  12134. };
  12135. };
  12136. /**
  12137. * Gets current aspect ratio
  12138. * @param camera defines the camera to use to get the aspect ratio
  12139. * @param useScreen defines if screen size must be used (or the current render target if any)
  12140. * @returns a number defining the aspect ratio
  12141. */
  12142. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12143. if (useScreen === void 0) { useScreen = false; }
  12144. var viewport = camera.viewport;
  12145. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12146. };
  12147. /**
  12148. * Gets current screen aspect ratio
  12149. * @returns a number defining the aspect ratio
  12150. */
  12151. Engine.prototype.getScreenAspectRatio = function () {
  12152. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12153. };
  12154. /**
  12155. * Gets the current render width
  12156. * @param useScreen defines if screen size must be used (or the current render target if any)
  12157. * @returns a number defining the current render width
  12158. */
  12159. Engine.prototype.getRenderWidth = function (useScreen) {
  12160. if (useScreen === void 0) { useScreen = false; }
  12161. if (!useScreen && this._currentRenderTarget) {
  12162. return this._currentRenderTarget.width;
  12163. }
  12164. return this._gl.drawingBufferWidth;
  12165. };
  12166. /**
  12167. * Gets the current render height
  12168. * @param useScreen defines if screen size must be used (or the current render target if any)
  12169. * @returns a number defining the current render height
  12170. */
  12171. Engine.prototype.getRenderHeight = function (useScreen) {
  12172. if (useScreen === void 0) { useScreen = false; }
  12173. if (!useScreen && this._currentRenderTarget) {
  12174. return this._currentRenderTarget.height;
  12175. }
  12176. return this._gl.drawingBufferHeight;
  12177. };
  12178. /**
  12179. * Gets the HTML canvas attached with the current webGL context
  12180. * @returns a HTML canvas
  12181. */
  12182. Engine.prototype.getRenderingCanvas = function () {
  12183. return this._renderingCanvas;
  12184. };
  12185. /**
  12186. * Gets the client rect of the HTML canvas attached with the current webGL context
  12187. * @returns a client rectanglee
  12188. */
  12189. Engine.prototype.getRenderingCanvasClientRect = function () {
  12190. if (!this._renderingCanvas) {
  12191. return null;
  12192. }
  12193. return this._renderingCanvas.getBoundingClientRect();
  12194. };
  12195. /**
  12196. * Defines the hardware scaling level.
  12197. * By default the hardware scaling level is computed from the window device ratio.
  12198. * 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.
  12199. * @param level defines the level to use
  12200. */
  12201. Engine.prototype.setHardwareScalingLevel = function (level) {
  12202. this._hardwareScalingLevel = level;
  12203. this.resize();
  12204. };
  12205. /**
  12206. * Gets the current hardware scaling level.
  12207. * By default the hardware scaling level is computed from the window device ratio.
  12208. * 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.
  12209. * @returns a number indicating the current hardware scaling level
  12210. */
  12211. Engine.prototype.getHardwareScalingLevel = function () {
  12212. return this._hardwareScalingLevel;
  12213. };
  12214. /**
  12215. * Gets the list of loaded textures
  12216. * @returns an array containing all loaded textures
  12217. */
  12218. Engine.prototype.getLoadedTexturesCache = function () {
  12219. return this._internalTexturesCache;
  12220. };
  12221. /**
  12222. * Gets the object containing all engine capabilities
  12223. * @returns the EngineCapabilities object
  12224. */
  12225. Engine.prototype.getCaps = function () {
  12226. return this._caps;
  12227. };
  12228. Object.defineProperty(Engine.prototype, "drawCalls", {
  12229. /** @hidden */
  12230. get: function () {
  12231. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12232. return 0;
  12233. },
  12234. enumerable: true,
  12235. configurable: true
  12236. });
  12237. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12238. /** @hidden */
  12239. get: function () {
  12240. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12241. return null;
  12242. },
  12243. enumerable: true,
  12244. configurable: true
  12245. });
  12246. /**
  12247. * Gets the current depth function
  12248. * @returns a number defining the depth function
  12249. */
  12250. Engine.prototype.getDepthFunction = function () {
  12251. return this._depthCullingState.depthFunc;
  12252. };
  12253. /**
  12254. * Sets the current depth function
  12255. * @param depthFunc defines the function to use
  12256. */
  12257. Engine.prototype.setDepthFunction = function (depthFunc) {
  12258. this._depthCullingState.depthFunc = depthFunc;
  12259. };
  12260. /**
  12261. * Sets the current depth function to GREATER
  12262. */
  12263. Engine.prototype.setDepthFunctionToGreater = function () {
  12264. this._depthCullingState.depthFunc = this._gl.GREATER;
  12265. };
  12266. /**
  12267. * Sets the current depth function to GEQUAL
  12268. */
  12269. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12270. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12271. };
  12272. /**
  12273. * Sets the current depth function to LESS
  12274. */
  12275. Engine.prototype.setDepthFunctionToLess = function () {
  12276. this._depthCullingState.depthFunc = this._gl.LESS;
  12277. };
  12278. /**
  12279. * Sets the current depth function to LEQUAL
  12280. */
  12281. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12282. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12283. };
  12284. /**
  12285. * Gets a boolean indicating if stencil buffer is enabled
  12286. * @returns the current stencil buffer state
  12287. */
  12288. Engine.prototype.getStencilBuffer = function () {
  12289. return this._stencilState.stencilTest;
  12290. };
  12291. /**
  12292. * Enable or disable the stencil buffer
  12293. * @param enable defines if the stencil buffer must be enabled or disabled
  12294. */
  12295. Engine.prototype.setStencilBuffer = function (enable) {
  12296. this._stencilState.stencilTest = enable;
  12297. };
  12298. /**
  12299. * Gets the current stencil mask
  12300. * @returns a number defining the new stencil mask to use
  12301. */
  12302. Engine.prototype.getStencilMask = function () {
  12303. return this._stencilState.stencilMask;
  12304. };
  12305. /**
  12306. * Sets the current stencil mask
  12307. * @param mask defines the new stencil mask to use
  12308. */
  12309. Engine.prototype.setStencilMask = function (mask) {
  12310. this._stencilState.stencilMask = mask;
  12311. };
  12312. /**
  12313. * Gets the current stencil function
  12314. * @returns a number defining the stencil function to use
  12315. */
  12316. Engine.prototype.getStencilFunction = function () {
  12317. return this._stencilState.stencilFunc;
  12318. };
  12319. /**
  12320. * Gets the current stencil reference value
  12321. * @returns a number defining the stencil reference value to use
  12322. */
  12323. Engine.prototype.getStencilFunctionReference = function () {
  12324. return this._stencilState.stencilFuncRef;
  12325. };
  12326. /**
  12327. * Gets the current stencil mask
  12328. * @returns a number defining the stencil mask to use
  12329. */
  12330. Engine.prototype.getStencilFunctionMask = function () {
  12331. return this._stencilState.stencilFuncMask;
  12332. };
  12333. /**
  12334. * Sets the current stencil function
  12335. * @param stencilFunc defines the new stencil function to use
  12336. */
  12337. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12338. this._stencilState.stencilFunc = stencilFunc;
  12339. };
  12340. /**
  12341. * Sets the current stencil reference
  12342. * @param reference defines the new stencil reference to use
  12343. */
  12344. Engine.prototype.setStencilFunctionReference = function (reference) {
  12345. this._stencilState.stencilFuncRef = reference;
  12346. };
  12347. /**
  12348. * Sets the current stencil mask
  12349. * @param mask defines the new stencil mask to use
  12350. */
  12351. Engine.prototype.setStencilFunctionMask = function (mask) {
  12352. this._stencilState.stencilFuncMask = mask;
  12353. };
  12354. /**
  12355. * Gets the current stencil operation when stencil fails
  12356. * @returns a number defining stencil operation to use when stencil fails
  12357. */
  12358. Engine.prototype.getStencilOperationFail = function () {
  12359. return this._stencilState.stencilOpStencilFail;
  12360. };
  12361. /**
  12362. * Gets the current stencil operation when depth fails
  12363. * @returns a number defining stencil operation to use when depth fails
  12364. */
  12365. Engine.prototype.getStencilOperationDepthFail = function () {
  12366. return this._stencilState.stencilOpDepthFail;
  12367. };
  12368. /**
  12369. * Gets the current stencil operation when stencil passes
  12370. * @returns a number defining stencil operation to use when stencil passes
  12371. */
  12372. Engine.prototype.getStencilOperationPass = function () {
  12373. return this._stencilState.stencilOpStencilDepthPass;
  12374. };
  12375. /**
  12376. * Sets the stencil operation to use when stencil fails
  12377. * @param operation defines the stencil operation to use when stencil fails
  12378. */
  12379. Engine.prototype.setStencilOperationFail = function (operation) {
  12380. this._stencilState.stencilOpStencilFail = operation;
  12381. };
  12382. /**
  12383. * Sets the stencil operation to use when depth fails
  12384. * @param operation defines the stencil operation to use when depth fails
  12385. */
  12386. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12387. this._stencilState.stencilOpDepthFail = operation;
  12388. };
  12389. /**
  12390. * Sets the stencil operation to use when stencil passes
  12391. * @param operation defines the stencil operation to use when stencil passes
  12392. */
  12393. Engine.prototype.setStencilOperationPass = function (operation) {
  12394. this._stencilState.stencilOpStencilDepthPass = operation;
  12395. };
  12396. /**
  12397. * Sets a boolean indicating if the dithering state is enabled or disabled
  12398. * @param value defines the dithering state
  12399. */
  12400. Engine.prototype.setDitheringState = function (value) {
  12401. if (value) {
  12402. this._gl.enable(this._gl.DITHER);
  12403. }
  12404. else {
  12405. this._gl.disable(this._gl.DITHER);
  12406. }
  12407. };
  12408. /**
  12409. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12410. * @param value defines the rasterizer state
  12411. */
  12412. Engine.prototype.setRasterizerState = function (value) {
  12413. if (value) {
  12414. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12415. }
  12416. else {
  12417. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12418. }
  12419. };
  12420. /**
  12421. * stop executing a render loop function and remove it from the execution array
  12422. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12423. */
  12424. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12425. if (!renderFunction) {
  12426. this._activeRenderLoops = [];
  12427. return;
  12428. }
  12429. var index = this._activeRenderLoops.indexOf(renderFunction);
  12430. if (index >= 0) {
  12431. this._activeRenderLoops.splice(index, 1);
  12432. }
  12433. };
  12434. /** @hidden */
  12435. Engine.prototype._renderLoop = function () {
  12436. if (!this._contextWasLost) {
  12437. var shouldRender = true;
  12438. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12439. shouldRender = false;
  12440. }
  12441. if (shouldRender) {
  12442. // Start new frame
  12443. this.beginFrame();
  12444. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12445. var renderFunction = this._activeRenderLoops[index];
  12446. renderFunction();
  12447. }
  12448. // Present
  12449. this.endFrame();
  12450. }
  12451. }
  12452. if (this._activeRenderLoops.length > 0) {
  12453. // Register new frame
  12454. var requester = null;
  12455. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12456. requester = this._vrDisplay;
  12457. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12458. }
  12459. else {
  12460. this._renderingQueueLaunched = false;
  12461. }
  12462. };
  12463. /**
  12464. * Register and execute a render loop. The engine can have more than one render function
  12465. * @param renderFunction defines the function to continuously execute
  12466. */
  12467. Engine.prototype.runRenderLoop = function (renderFunction) {
  12468. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12469. return;
  12470. }
  12471. this._activeRenderLoops.push(renderFunction);
  12472. if (!this._renderingQueueLaunched) {
  12473. this._renderingQueueLaunched = true;
  12474. this._bindedRenderFunction = this._renderLoop.bind(this);
  12475. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12476. }
  12477. };
  12478. /**
  12479. * Toggle full screen mode
  12480. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12481. * @param options defines an option object to be sent to the requestFullscreen function
  12482. */
  12483. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12484. if (this.isFullscreen) {
  12485. BABYLON.Tools.ExitFullscreen();
  12486. }
  12487. else {
  12488. this._pointerLockRequested = requestPointerLock;
  12489. if (this._renderingCanvas) {
  12490. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12491. }
  12492. }
  12493. };
  12494. /**
  12495. * Clear the current render buffer or the current render target (if any is set up)
  12496. * @param color defines the color to use
  12497. * @param backBuffer defines if the back buffer must be cleared
  12498. * @param depth defines if the depth buffer must be cleared
  12499. * @param stencil defines if the stencil buffer must be cleared
  12500. */
  12501. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12502. if (stencil === void 0) { stencil = false; }
  12503. this.applyStates();
  12504. var mode = 0;
  12505. if (backBuffer && color) {
  12506. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12507. mode |= this._gl.COLOR_BUFFER_BIT;
  12508. }
  12509. if (depth) {
  12510. this._gl.clearDepth(1.0);
  12511. mode |= this._gl.DEPTH_BUFFER_BIT;
  12512. }
  12513. if (stencil) {
  12514. this._gl.clearStencil(0);
  12515. mode |= this._gl.STENCIL_BUFFER_BIT;
  12516. }
  12517. this._gl.clear(mode);
  12518. };
  12519. /**
  12520. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12521. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12522. * @param y defines the y-coordinate of the corner of the clear rectangle
  12523. * @param width defines the width of the clear rectangle
  12524. * @param height defines the height of the clear rectangle
  12525. * @param clearColor defines the clear color
  12526. */
  12527. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12528. var gl = this._gl;
  12529. // Save state
  12530. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12531. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12532. // Change state
  12533. gl.enable(gl.SCISSOR_TEST);
  12534. gl.scissor(x, y, width, height);
  12535. // Clear
  12536. this.clear(clearColor, true, true, true);
  12537. // Restore state
  12538. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12539. if (curScissor === true) {
  12540. gl.enable(gl.SCISSOR_TEST);
  12541. }
  12542. else {
  12543. gl.disable(gl.SCISSOR_TEST);
  12544. }
  12545. };
  12546. /** @hidden */
  12547. Engine.prototype._viewport = function (x, y, width, height) {
  12548. if (x !== this._viewportCached.x ||
  12549. y !== this._viewportCached.y ||
  12550. width !== this._viewportCached.z ||
  12551. height !== this._viewportCached.w) {
  12552. this._viewportCached.x = x;
  12553. this._viewportCached.y = y;
  12554. this._viewportCached.z = width;
  12555. this._viewportCached.w = height;
  12556. this._gl.viewport(x, y, width, height);
  12557. }
  12558. };
  12559. /**
  12560. * Set the WebGL's viewport
  12561. * @param viewport defines the viewport element to be used
  12562. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12563. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12564. */
  12565. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12566. var width = requiredWidth || this.getRenderWidth();
  12567. var height = requiredHeight || this.getRenderHeight();
  12568. var x = viewport.x || 0;
  12569. var y = viewport.y || 0;
  12570. this._cachedViewport = viewport;
  12571. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12572. };
  12573. /**
  12574. * Directly set the WebGL Viewport
  12575. * @param x defines the x coordinate of the viewport (in screen space)
  12576. * @param y defines the y coordinate of the viewport (in screen space)
  12577. * @param width defines the width of the viewport (in screen space)
  12578. * @param height defines the height of the viewport (in screen space)
  12579. * @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
  12580. */
  12581. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12582. var currentViewport = this._cachedViewport;
  12583. this._cachedViewport = null;
  12584. this._viewport(x, y, width, height);
  12585. return currentViewport;
  12586. };
  12587. /**
  12588. * Begin a new frame
  12589. */
  12590. Engine.prototype.beginFrame = function () {
  12591. this.onBeginFrameObservable.notifyObservers(this);
  12592. this._measureFps();
  12593. };
  12594. /**
  12595. * Enf the current frame
  12596. */
  12597. Engine.prototype.endFrame = function () {
  12598. // Force a flush in case we are using a bad OS.
  12599. if (this._badOS) {
  12600. this.flushFramebuffer();
  12601. }
  12602. // Submit frame to the vr device, if enabled
  12603. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12604. // TODO: We should only submit the frame if we read frameData successfully.
  12605. this._vrDisplay.submitFrame();
  12606. }
  12607. this.onEndFrameObservable.notifyObservers(this);
  12608. };
  12609. /**
  12610. * Resize the view according to the canvas' size
  12611. */
  12612. Engine.prototype.resize = function () {
  12613. // We're not resizing the size of the canvas while in VR mode & presenting
  12614. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12615. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12616. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12617. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12618. }
  12619. };
  12620. /**
  12621. * Force a specific size of the canvas
  12622. * @param width defines the new canvas' width
  12623. * @param height defines the new canvas' height
  12624. */
  12625. Engine.prototype.setSize = function (width, height) {
  12626. if (!this._renderingCanvas) {
  12627. return;
  12628. }
  12629. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12630. return;
  12631. }
  12632. this._renderingCanvas.width = width;
  12633. this._renderingCanvas.height = height;
  12634. for (var index = 0; index < this.scenes.length; index++) {
  12635. var scene = this.scenes[index];
  12636. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12637. var cam = scene.cameras[camIndex];
  12638. cam._currentRenderId = 0;
  12639. }
  12640. }
  12641. if (this.onResizeObservable.hasObservers) {
  12642. this.onResizeObservable.notifyObservers(this);
  12643. }
  12644. };
  12645. // WebVR functions
  12646. /**
  12647. * Gets a boolean indicating if a webVR device was detected
  12648. * @returns true if a webVR device was detected
  12649. */
  12650. Engine.prototype.isVRDevicePresent = function () {
  12651. return !!this._vrDisplay;
  12652. };
  12653. /**
  12654. * Gets the current webVR device
  12655. * @returns the current webVR device (or null)
  12656. */
  12657. Engine.prototype.getVRDevice = function () {
  12658. return this._vrDisplay;
  12659. };
  12660. /**
  12661. * Initializes a webVR display and starts listening to display change events
  12662. * The onVRDisplayChangedObservable will be notified upon these changes
  12663. * @returns The onVRDisplayChangedObservable
  12664. */
  12665. Engine.prototype.initWebVR = function () {
  12666. this.initWebVRAsync();
  12667. return this.onVRDisplayChangedObservable;
  12668. };
  12669. /**
  12670. * Initializes a webVR display and starts listening to display change events
  12671. * The onVRDisplayChangedObservable will be notified upon these changes
  12672. * @returns A promise containing a VRDisplay and if vr is supported
  12673. */
  12674. Engine.prototype.initWebVRAsync = function () {
  12675. var _this = this;
  12676. var notifyObservers = function () {
  12677. var eventArgs = {
  12678. vrDisplay: _this._vrDisplay,
  12679. vrSupported: _this._vrSupported
  12680. };
  12681. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12682. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12683. };
  12684. if (!this._onVrDisplayConnect) {
  12685. this._onVrDisplayConnect = function (event) {
  12686. _this._vrDisplay = event.display;
  12687. notifyObservers();
  12688. };
  12689. this._onVrDisplayDisconnect = function () {
  12690. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12691. _this._vrDisplay = undefined;
  12692. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12693. notifyObservers();
  12694. };
  12695. this._onVrDisplayPresentChange = function () {
  12696. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12697. };
  12698. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12699. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12700. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12701. }
  12702. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12703. this._webVRInitPromise.then(notifyObservers);
  12704. return this._webVRInitPromise;
  12705. };
  12706. /**
  12707. * Call this function to switch to webVR mode
  12708. * Will do nothing if webVR is not supported or if there is no webVR device
  12709. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12710. */
  12711. Engine.prototype.enableVR = function () {
  12712. var _this = this;
  12713. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12714. var onResolved = function () {
  12715. _this.onVRRequestPresentComplete.notifyObservers(true);
  12716. _this._onVRFullScreenTriggered();
  12717. };
  12718. var onRejected = function () {
  12719. _this.onVRRequestPresentComplete.notifyObservers(false);
  12720. };
  12721. this.onVRRequestPresentStart.notifyObservers(this);
  12722. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12723. }
  12724. };
  12725. /**
  12726. * Call this function to leave webVR mode
  12727. * Will do nothing if webVR is not supported or if there is no webVR device
  12728. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12729. */
  12730. Engine.prototype.disableVR = function () {
  12731. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12732. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12733. }
  12734. };
  12735. Engine.prototype._getVRDisplaysAsync = function () {
  12736. var _this = this;
  12737. return new Promise(function (res, rej) {
  12738. if (navigator.getVRDisplays) {
  12739. navigator.getVRDisplays().then(function (devices) {
  12740. _this._vrSupported = true;
  12741. // note that devices may actually be an empty array. This is fine;
  12742. // we expect this._vrDisplay to be undefined in this case.
  12743. _this._vrDisplay = devices[0];
  12744. res({
  12745. vrDisplay: _this._vrDisplay,
  12746. vrSupported: _this._vrSupported
  12747. });
  12748. });
  12749. }
  12750. else {
  12751. _this._vrDisplay = undefined;
  12752. _this._vrSupported = false;
  12753. res({
  12754. vrDisplay: _this._vrDisplay,
  12755. vrSupported: _this._vrSupported
  12756. });
  12757. }
  12758. });
  12759. };
  12760. /**
  12761. * Binds the frame buffer to the specified texture.
  12762. * @param texture The texture to render to or null for the default canvas
  12763. * @param faceIndex The face of the texture to render to in case of cube texture
  12764. * @param requiredWidth The width of the target to render to
  12765. * @param requiredHeight The height of the target to render to
  12766. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12767. * @param depthStencilTexture The depth stencil texture to use to render
  12768. * @param lodLevel defines le lod level to bind to the frame buffer
  12769. */
  12770. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12771. if (lodLevel === void 0) { lodLevel = 0; }
  12772. if (this._currentRenderTarget) {
  12773. this.unBindFramebuffer(this._currentRenderTarget);
  12774. }
  12775. this._currentRenderTarget = texture;
  12776. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12777. var gl = this._gl;
  12778. if (texture.isCube) {
  12779. if (faceIndex === undefined) {
  12780. faceIndex = 0;
  12781. }
  12782. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12783. if (depthStencilTexture) {
  12784. if (depthStencilTexture._generateStencilBuffer) {
  12785. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12786. }
  12787. else {
  12788. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12789. }
  12790. }
  12791. }
  12792. if (this._cachedViewport && !forceFullscreenViewport) {
  12793. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12794. }
  12795. else {
  12796. if (!requiredWidth) {
  12797. requiredWidth = texture.width;
  12798. if (lodLevel) {
  12799. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12800. }
  12801. }
  12802. if (!requiredHeight) {
  12803. requiredHeight = texture.height;
  12804. if (lodLevel) {
  12805. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12806. }
  12807. }
  12808. this._viewport(0, 0, requiredWidth, requiredHeight);
  12809. }
  12810. this.wipeCaches();
  12811. };
  12812. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12813. if (this._currentFramebuffer !== framebuffer) {
  12814. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12815. this._currentFramebuffer = framebuffer;
  12816. }
  12817. };
  12818. /**
  12819. * Unbind the current render target texture from the webGL context
  12820. * @param texture defines the render target texture to unbind
  12821. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12822. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12823. */
  12824. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12825. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12826. this._currentRenderTarget = null;
  12827. // If MSAA, we need to bitblt back to main texture
  12828. var gl = this._gl;
  12829. if (texture._MSAAFramebuffer) {
  12830. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12831. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12832. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12833. }
  12834. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12835. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12836. gl.generateMipmap(gl.TEXTURE_2D);
  12837. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12838. }
  12839. if (onBeforeUnbind) {
  12840. if (texture._MSAAFramebuffer) {
  12841. // Bind the correct framebuffer
  12842. this.bindUnboundFramebuffer(texture._framebuffer);
  12843. }
  12844. onBeforeUnbind();
  12845. }
  12846. this.bindUnboundFramebuffer(null);
  12847. };
  12848. /**
  12849. * Unbind a list of render target textures from the webGL context
  12850. * This is used only when drawBuffer extension or webGL2 are active
  12851. * @param textures defines the render target textures to unbind
  12852. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12853. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12854. */
  12855. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12856. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12857. this._currentRenderTarget = null;
  12858. // If MSAA, we need to bitblt back to main texture
  12859. var gl = this._gl;
  12860. if (textures[0]._MSAAFramebuffer) {
  12861. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12862. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12863. var attachments = textures[0]._attachments;
  12864. if (!attachments) {
  12865. attachments = new Array(textures.length);
  12866. textures[0]._attachments = attachments;
  12867. }
  12868. for (var i = 0; i < textures.length; i++) {
  12869. var texture = textures[i];
  12870. for (var j = 0; j < attachments.length; j++) {
  12871. attachments[j] = gl.NONE;
  12872. }
  12873. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12874. gl.readBuffer(attachments[i]);
  12875. gl.drawBuffers(attachments);
  12876. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12877. }
  12878. for (var i = 0; i < attachments.length; i++) {
  12879. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12880. }
  12881. gl.drawBuffers(attachments);
  12882. }
  12883. for (var i = 0; i < textures.length; i++) {
  12884. var texture = textures[i];
  12885. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12886. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12887. gl.generateMipmap(gl.TEXTURE_2D);
  12888. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12889. }
  12890. }
  12891. if (onBeforeUnbind) {
  12892. if (textures[0]._MSAAFramebuffer) {
  12893. // Bind the correct framebuffer
  12894. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12895. }
  12896. onBeforeUnbind();
  12897. }
  12898. this.bindUnboundFramebuffer(null);
  12899. };
  12900. /**
  12901. * Force the mipmap generation for the given render target texture
  12902. * @param texture defines the render target texture to use
  12903. */
  12904. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12905. if (texture.generateMipMaps) {
  12906. var gl = this._gl;
  12907. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12908. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12909. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12910. }
  12911. };
  12912. /**
  12913. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12914. */
  12915. Engine.prototype.flushFramebuffer = function () {
  12916. this._gl.flush();
  12917. };
  12918. /**
  12919. * Unbind the current render target and bind the default framebuffer
  12920. */
  12921. Engine.prototype.restoreDefaultFramebuffer = function () {
  12922. if (this._currentRenderTarget) {
  12923. this.unBindFramebuffer(this._currentRenderTarget);
  12924. }
  12925. else {
  12926. this.bindUnboundFramebuffer(null);
  12927. }
  12928. if (this._cachedViewport) {
  12929. this.setViewport(this._cachedViewport);
  12930. }
  12931. this.wipeCaches();
  12932. };
  12933. // UBOs
  12934. /**
  12935. * Create an uniform buffer
  12936. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12937. * @param elements defines the content of the uniform buffer
  12938. * @returns the webGL uniform buffer
  12939. */
  12940. Engine.prototype.createUniformBuffer = function (elements) {
  12941. var ubo = this._gl.createBuffer();
  12942. if (!ubo) {
  12943. throw new Error("Unable to create uniform buffer");
  12944. }
  12945. this.bindUniformBuffer(ubo);
  12946. if (elements instanceof Float32Array) {
  12947. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12948. }
  12949. else {
  12950. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12951. }
  12952. this.bindUniformBuffer(null);
  12953. ubo.references = 1;
  12954. return ubo;
  12955. };
  12956. /**
  12957. * Create a dynamic uniform buffer
  12958. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12959. * @param elements defines the content of the uniform buffer
  12960. * @returns the webGL uniform buffer
  12961. */
  12962. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12963. var ubo = this._gl.createBuffer();
  12964. if (!ubo) {
  12965. throw new Error("Unable to create dynamic uniform buffer");
  12966. }
  12967. this.bindUniformBuffer(ubo);
  12968. if (elements instanceof Float32Array) {
  12969. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12970. }
  12971. else {
  12972. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12973. }
  12974. this.bindUniformBuffer(null);
  12975. ubo.references = 1;
  12976. return ubo;
  12977. };
  12978. /**
  12979. * Update an existing uniform buffer
  12980. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12981. * @param uniformBuffer defines the target uniform buffer
  12982. * @param elements defines the content to update
  12983. * @param offset defines the offset in the uniform buffer where update should start
  12984. * @param count defines the size of the data to update
  12985. */
  12986. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12987. this.bindUniformBuffer(uniformBuffer);
  12988. if (offset === undefined) {
  12989. offset = 0;
  12990. }
  12991. if (count === undefined) {
  12992. if (elements instanceof Float32Array) {
  12993. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12994. }
  12995. else {
  12996. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12997. }
  12998. }
  12999. else {
  13000. if (elements instanceof Float32Array) {
  13001. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13002. }
  13003. else {
  13004. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13005. }
  13006. }
  13007. this.bindUniformBuffer(null);
  13008. };
  13009. // VBOs
  13010. Engine.prototype._resetVertexBufferBinding = function () {
  13011. this.bindArrayBuffer(null);
  13012. this._cachedVertexBuffers = null;
  13013. };
  13014. /**
  13015. * Creates a vertex buffer
  13016. * @param data the data for the vertex buffer
  13017. * @returns the new WebGL static buffer
  13018. */
  13019. Engine.prototype.createVertexBuffer = function (data) {
  13020. var vbo = this._gl.createBuffer();
  13021. if (!vbo) {
  13022. throw new Error("Unable to create vertex buffer");
  13023. }
  13024. this.bindArrayBuffer(vbo);
  13025. if (data instanceof Array) {
  13026. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13027. }
  13028. else {
  13029. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13030. }
  13031. this._resetVertexBufferBinding();
  13032. vbo.references = 1;
  13033. return vbo;
  13034. };
  13035. /**
  13036. * Creates a dynamic vertex buffer
  13037. * @param data the data for the dynamic vertex buffer
  13038. * @returns the new WebGL dynamic buffer
  13039. */
  13040. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13041. var vbo = this._gl.createBuffer();
  13042. if (!vbo) {
  13043. throw new Error("Unable to create dynamic vertex buffer");
  13044. }
  13045. this.bindArrayBuffer(vbo);
  13046. if (data instanceof Array) {
  13047. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13048. }
  13049. else {
  13050. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13051. }
  13052. this._resetVertexBufferBinding();
  13053. vbo.references = 1;
  13054. return vbo;
  13055. };
  13056. /**
  13057. * Update a dynamic index buffer
  13058. * @param indexBuffer defines the target index buffer
  13059. * @param indices defines the data to update
  13060. * @param offset defines the offset in the target index buffer where update should start
  13061. */
  13062. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13063. if (offset === void 0) { offset = 0; }
  13064. // Force cache update
  13065. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13066. this.bindIndexBuffer(indexBuffer);
  13067. var arrayBuffer;
  13068. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13069. arrayBuffer = indices;
  13070. }
  13071. else {
  13072. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13073. }
  13074. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13075. this._resetIndexBufferBinding();
  13076. };
  13077. /**
  13078. * Updates a dynamic vertex buffer.
  13079. * @param vertexBuffer the vertex buffer to update
  13080. * @param data the data used to update the vertex buffer
  13081. * @param byteOffset the byte offset of the data
  13082. * @param byteLength the byte length of the data
  13083. */
  13084. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13085. this.bindArrayBuffer(vertexBuffer);
  13086. if (byteOffset === undefined) {
  13087. byteOffset = 0;
  13088. }
  13089. if (byteLength === undefined) {
  13090. if (data instanceof Array) {
  13091. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13092. }
  13093. else {
  13094. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13095. }
  13096. }
  13097. else {
  13098. if (data instanceof Array) {
  13099. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13100. }
  13101. else {
  13102. if (data instanceof ArrayBuffer) {
  13103. data = new Uint8Array(data, byteOffset, byteLength);
  13104. }
  13105. else {
  13106. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13107. }
  13108. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13109. }
  13110. }
  13111. this._resetVertexBufferBinding();
  13112. };
  13113. Engine.prototype._resetIndexBufferBinding = function () {
  13114. this.bindIndexBuffer(null);
  13115. this._cachedIndexBuffer = null;
  13116. };
  13117. /**
  13118. * Creates a new index buffer
  13119. * @param indices defines the content of the index buffer
  13120. * @param updatable defines if the index buffer must be updatable
  13121. * @returns a new webGL buffer
  13122. */
  13123. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13124. var vbo = this._gl.createBuffer();
  13125. if (!vbo) {
  13126. throw new Error("Unable to create index buffer");
  13127. }
  13128. this.bindIndexBuffer(vbo);
  13129. // Check for 32 bits indices
  13130. var arrayBuffer;
  13131. var need32Bits = false;
  13132. if (indices instanceof Uint16Array) {
  13133. arrayBuffer = indices;
  13134. }
  13135. else {
  13136. //check 32 bit support
  13137. if (this._caps.uintIndices) {
  13138. if (indices instanceof Uint32Array) {
  13139. arrayBuffer = indices;
  13140. need32Bits = true;
  13141. }
  13142. else {
  13143. //number[] or Int32Array, check if 32 bit is necessary
  13144. for (var index = 0; index < indices.length; index++) {
  13145. if (indices[index] > 65535) {
  13146. need32Bits = true;
  13147. break;
  13148. }
  13149. }
  13150. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13151. }
  13152. }
  13153. else {
  13154. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13155. arrayBuffer = new Uint16Array(indices);
  13156. }
  13157. }
  13158. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13159. this._resetIndexBufferBinding();
  13160. vbo.references = 1;
  13161. vbo.is32Bits = need32Bits;
  13162. return vbo;
  13163. };
  13164. /**
  13165. * Bind a webGL buffer to the webGL context
  13166. * @param buffer defines the buffer to bind
  13167. */
  13168. Engine.prototype.bindArrayBuffer = function (buffer) {
  13169. if (!this._vaoRecordInProgress) {
  13170. this._unbindVertexArrayObject();
  13171. }
  13172. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13173. };
  13174. /**
  13175. * Bind an uniform buffer to the current webGL context
  13176. * @param buffer defines the buffer to bind
  13177. */
  13178. Engine.prototype.bindUniformBuffer = function (buffer) {
  13179. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13180. };
  13181. /**
  13182. * Bind a buffer to the current webGL context at a given location
  13183. * @param buffer defines the buffer to bind
  13184. * @param location defines the index where to bind the buffer
  13185. */
  13186. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13187. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13188. };
  13189. /**
  13190. * Bind a specific block at a given index in a specific shader program
  13191. * @param shaderProgram defines the shader program
  13192. * @param blockName defines the block name
  13193. * @param index defines the index where to bind the block
  13194. */
  13195. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13196. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13197. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13198. };
  13199. ;
  13200. Engine.prototype.bindIndexBuffer = function (buffer) {
  13201. if (!this._vaoRecordInProgress) {
  13202. this._unbindVertexArrayObject();
  13203. }
  13204. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13205. };
  13206. Engine.prototype.bindBuffer = function (buffer, target) {
  13207. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13208. this._gl.bindBuffer(target, buffer);
  13209. this._currentBoundBuffer[target] = buffer;
  13210. }
  13211. };
  13212. /**
  13213. * update the bound buffer with the given data
  13214. * @param data defines the data to update
  13215. */
  13216. Engine.prototype.updateArrayBuffer = function (data) {
  13217. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13218. };
  13219. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13220. var pointer = this._currentBufferPointers[indx];
  13221. var changed = false;
  13222. if (!pointer.active) {
  13223. changed = true;
  13224. pointer.active = true;
  13225. pointer.index = indx;
  13226. pointer.size = size;
  13227. pointer.type = type;
  13228. pointer.normalized = normalized;
  13229. pointer.stride = stride;
  13230. pointer.offset = offset;
  13231. pointer.buffer = buffer;
  13232. }
  13233. else {
  13234. if (pointer.buffer !== buffer) {
  13235. pointer.buffer = buffer;
  13236. changed = true;
  13237. }
  13238. if (pointer.size !== size) {
  13239. pointer.size = size;
  13240. changed = true;
  13241. }
  13242. if (pointer.type !== type) {
  13243. pointer.type = type;
  13244. changed = true;
  13245. }
  13246. if (pointer.normalized !== normalized) {
  13247. pointer.normalized = normalized;
  13248. changed = true;
  13249. }
  13250. if (pointer.stride !== stride) {
  13251. pointer.stride = stride;
  13252. changed = true;
  13253. }
  13254. if (pointer.offset !== offset) {
  13255. pointer.offset = offset;
  13256. changed = true;
  13257. }
  13258. }
  13259. if (changed || this._vaoRecordInProgress) {
  13260. this.bindArrayBuffer(buffer);
  13261. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13262. }
  13263. };
  13264. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13265. if (indexBuffer == null) {
  13266. return;
  13267. }
  13268. if (this._cachedIndexBuffer !== indexBuffer) {
  13269. this._cachedIndexBuffer = indexBuffer;
  13270. this.bindIndexBuffer(indexBuffer);
  13271. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13272. }
  13273. };
  13274. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13275. var attributes = effect.getAttributesNames();
  13276. if (!this._vaoRecordInProgress) {
  13277. this._unbindVertexArrayObject();
  13278. }
  13279. this.unbindAllAttributes();
  13280. for (var index = 0; index < attributes.length; index++) {
  13281. var order = effect.getAttributeLocation(index);
  13282. if (order >= 0) {
  13283. var vertexBuffer = vertexBuffers[attributes[index]];
  13284. if (!vertexBuffer) {
  13285. continue;
  13286. }
  13287. this._gl.enableVertexAttribArray(order);
  13288. if (!this._vaoRecordInProgress) {
  13289. this._vertexAttribArraysEnabled[order] = true;
  13290. }
  13291. var buffer = vertexBuffer.getBuffer();
  13292. if (buffer) {
  13293. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13294. if (vertexBuffer.getIsInstanced()) {
  13295. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13296. if (!this._vaoRecordInProgress) {
  13297. this._currentInstanceLocations.push(order);
  13298. this._currentInstanceBuffers.push(buffer);
  13299. }
  13300. }
  13301. }
  13302. }
  13303. }
  13304. };
  13305. /**
  13306. * Records a vertex array object
  13307. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13308. * @param vertexBuffers defines the list of vertex buffers to store
  13309. * @param indexBuffer defines the index buffer to store
  13310. * @param effect defines the effect to store
  13311. * @returns the new vertex array object
  13312. */
  13313. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13314. var vao = this._gl.createVertexArray();
  13315. this._vaoRecordInProgress = true;
  13316. this._gl.bindVertexArray(vao);
  13317. this._mustWipeVertexAttributes = true;
  13318. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13319. this.bindIndexBuffer(indexBuffer);
  13320. this._vaoRecordInProgress = false;
  13321. this._gl.bindVertexArray(null);
  13322. return vao;
  13323. };
  13324. /**
  13325. * Bind a specific vertex array object
  13326. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13327. * @param vertexArrayObject defines the vertex array object to bind
  13328. * @param indexBuffer defines the index buffer to bind
  13329. */
  13330. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13331. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13332. this._cachedVertexArrayObject = vertexArrayObject;
  13333. this._gl.bindVertexArray(vertexArrayObject);
  13334. this._cachedVertexBuffers = null;
  13335. this._cachedIndexBuffer = null;
  13336. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13337. this._mustWipeVertexAttributes = true;
  13338. }
  13339. };
  13340. /**
  13341. * Bind webGl buffers directly to the webGL context
  13342. * @param vertexBuffer defines the vertex buffer to bind
  13343. * @param indexBuffer defines the index buffer to bind
  13344. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13345. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13346. * @param effect defines the effect associated with the vertex buffer
  13347. */
  13348. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13349. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13350. this._cachedVertexBuffers = vertexBuffer;
  13351. this._cachedEffectForVertexBuffers = effect;
  13352. var attributesCount = effect.getAttributesCount();
  13353. this._unbindVertexArrayObject();
  13354. this.unbindAllAttributes();
  13355. var offset = 0;
  13356. for (var index = 0; index < attributesCount; index++) {
  13357. if (index < vertexDeclaration.length) {
  13358. var order = effect.getAttributeLocation(index);
  13359. if (order >= 0) {
  13360. this._gl.enableVertexAttribArray(order);
  13361. this._vertexAttribArraysEnabled[order] = true;
  13362. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13363. }
  13364. offset += vertexDeclaration[index] * 4;
  13365. }
  13366. }
  13367. }
  13368. this._bindIndexBufferWithCache(indexBuffer);
  13369. };
  13370. Engine.prototype._unbindVertexArrayObject = function () {
  13371. if (!this._cachedVertexArrayObject) {
  13372. return;
  13373. }
  13374. this._cachedVertexArrayObject = null;
  13375. this._gl.bindVertexArray(null);
  13376. };
  13377. /**
  13378. * Bind a list of vertex buffers to the webGL context
  13379. * @param vertexBuffers defines the list of vertex buffers to bind
  13380. * @param indexBuffer defines the index buffer to bind
  13381. * @param effect defines the effect associated with the vertex buffers
  13382. */
  13383. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13384. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13385. this._cachedVertexBuffers = vertexBuffers;
  13386. this._cachedEffectForVertexBuffers = effect;
  13387. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13388. }
  13389. this._bindIndexBufferWithCache(indexBuffer);
  13390. };
  13391. /**
  13392. * Unbind all instance attributes
  13393. */
  13394. Engine.prototype.unbindInstanceAttributes = function () {
  13395. var boundBuffer;
  13396. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13397. var instancesBuffer = this._currentInstanceBuffers[i];
  13398. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13399. boundBuffer = instancesBuffer;
  13400. this.bindArrayBuffer(instancesBuffer);
  13401. }
  13402. var offsetLocation = this._currentInstanceLocations[i];
  13403. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13404. }
  13405. this._currentInstanceBuffers.length = 0;
  13406. this._currentInstanceLocations.length = 0;
  13407. };
  13408. /**
  13409. * Release and free the memory of a vertex array object
  13410. * @param vao defines the vertex array object to delete
  13411. */
  13412. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13413. this._gl.deleteVertexArray(vao);
  13414. };
  13415. /** @hidden */
  13416. Engine.prototype._releaseBuffer = function (buffer) {
  13417. buffer.references--;
  13418. if (buffer.references === 0) {
  13419. this._gl.deleteBuffer(buffer);
  13420. return true;
  13421. }
  13422. return false;
  13423. };
  13424. /**
  13425. * Creates a webGL buffer to use with instanciation
  13426. * @param capacity defines the size of the buffer
  13427. * @returns the webGL buffer
  13428. */
  13429. Engine.prototype.createInstancesBuffer = function (capacity) {
  13430. var buffer = this._gl.createBuffer();
  13431. if (!buffer) {
  13432. throw new Error("Unable to create instance buffer");
  13433. }
  13434. buffer.capacity = capacity;
  13435. this.bindArrayBuffer(buffer);
  13436. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13437. return buffer;
  13438. };
  13439. /**
  13440. * Delete a webGL buffer used with instanciation
  13441. * @param buffer defines the webGL buffer to delete
  13442. */
  13443. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13444. this._gl.deleteBuffer(buffer);
  13445. };
  13446. /**
  13447. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13448. * @param instancesBuffer defines the webGL buffer to update and bind
  13449. * @param data defines the data to store in the buffer
  13450. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13451. */
  13452. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13453. this.bindArrayBuffer(instancesBuffer);
  13454. if (data) {
  13455. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13456. }
  13457. if (offsetLocations[0].index !== undefined) {
  13458. var stride = 0;
  13459. for (var i = 0; i < offsetLocations.length; i++) {
  13460. var ai = offsetLocations[i];
  13461. stride += ai.attributeSize * 4;
  13462. }
  13463. for (var i = 0; i < offsetLocations.length; i++) {
  13464. var ai = offsetLocations[i];
  13465. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13466. this._gl.enableVertexAttribArray(ai.index);
  13467. this._vertexAttribArraysEnabled[ai.index] = true;
  13468. }
  13469. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13470. this._gl.vertexAttribDivisor(ai.index, 1);
  13471. this._currentInstanceLocations.push(ai.index);
  13472. this._currentInstanceBuffers.push(instancesBuffer);
  13473. }
  13474. }
  13475. else {
  13476. for (var index = 0; index < 4; index++) {
  13477. var offsetLocation = offsetLocations[index];
  13478. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13479. this._gl.enableVertexAttribArray(offsetLocation);
  13480. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13481. }
  13482. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13483. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13484. this._currentInstanceLocations.push(offsetLocation);
  13485. this._currentInstanceBuffers.push(instancesBuffer);
  13486. }
  13487. }
  13488. };
  13489. /**
  13490. * Apply all cached states (depth, culling, stencil and alpha)
  13491. */
  13492. Engine.prototype.applyStates = function () {
  13493. this._depthCullingState.apply(this._gl);
  13494. this._stencilState.apply(this._gl);
  13495. this._alphaState.apply(this._gl);
  13496. };
  13497. /**
  13498. * Send a draw order
  13499. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13500. * @param indexStart defines the starting index
  13501. * @param indexCount defines the number of index to draw
  13502. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13503. */
  13504. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13505. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13506. };
  13507. /**
  13508. * Draw a list of points
  13509. * @param verticesStart defines the index of first vertex to draw
  13510. * @param verticesCount defines the count of vertices to draw
  13511. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13512. */
  13513. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13514. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13515. };
  13516. /**
  13517. * Draw a list of unindexed primitives
  13518. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13519. * @param verticesStart defines the index of first vertex to draw
  13520. * @param verticesCount defines the count of vertices to draw
  13521. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13522. */
  13523. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13524. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13525. };
  13526. /**
  13527. * Draw a list of indexed primitives
  13528. * @param fillMode defines the primitive to use
  13529. * @param indexStart defines the starting index
  13530. * @param indexCount defines the number of index to draw
  13531. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13532. */
  13533. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13534. // Apply states
  13535. this.applyStates();
  13536. this._drawCalls.addCount(1, false);
  13537. // Render
  13538. var drawMode = this._drawMode(fillMode);
  13539. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13540. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13541. if (instancesCount) {
  13542. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13543. }
  13544. else {
  13545. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13546. }
  13547. };
  13548. /**
  13549. * Draw a list of unindexed primitives
  13550. * @param fillMode defines the primitive to use
  13551. * @param verticesStart defines the index of first vertex to draw
  13552. * @param verticesCount defines the count of vertices to draw
  13553. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13554. */
  13555. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13556. // Apply states
  13557. this.applyStates();
  13558. this._drawCalls.addCount(1, false);
  13559. var drawMode = this._drawMode(fillMode);
  13560. if (instancesCount) {
  13561. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13562. }
  13563. else {
  13564. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13565. }
  13566. };
  13567. Engine.prototype._drawMode = function (fillMode) {
  13568. switch (fillMode) {
  13569. // Triangle views
  13570. case BABYLON.Material.TriangleFillMode:
  13571. return this._gl.TRIANGLES;
  13572. case BABYLON.Material.PointFillMode:
  13573. return this._gl.POINTS;
  13574. case BABYLON.Material.WireFrameFillMode:
  13575. return this._gl.LINES;
  13576. // Draw modes
  13577. case BABYLON.Material.PointListDrawMode:
  13578. return this._gl.POINTS;
  13579. case BABYLON.Material.LineListDrawMode:
  13580. return this._gl.LINES;
  13581. case BABYLON.Material.LineLoopDrawMode:
  13582. return this._gl.LINE_LOOP;
  13583. case BABYLON.Material.LineStripDrawMode:
  13584. return this._gl.LINE_STRIP;
  13585. case BABYLON.Material.TriangleStripDrawMode:
  13586. return this._gl.TRIANGLE_STRIP;
  13587. case BABYLON.Material.TriangleFanDrawMode:
  13588. return this._gl.TRIANGLE_FAN;
  13589. default:
  13590. return this._gl.TRIANGLES;
  13591. }
  13592. };
  13593. // Shaders
  13594. /** @hidden */
  13595. Engine.prototype._releaseEffect = function (effect) {
  13596. if (this._compiledEffects[effect._key]) {
  13597. delete this._compiledEffects[effect._key];
  13598. this._deleteProgram(effect.getProgram());
  13599. }
  13600. };
  13601. /** @hidden */
  13602. Engine.prototype._deleteProgram = function (program) {
  13603. if (program) {
  13604. program.__SPECTOR_rebuildProgram = null;
  13605. if (program.transformFeedback) {
  13606. this.deleteTransformFeedback(program.transformFeedback);
  13607. program.transformFeedback = null;
  13608. }
  13609. this._gl.deleteProgram(program);
  13610. }
  13611. };
  13612. /**
  13613. * Create a new effect (used to store vertex/fragment shaders)
  13614. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13615. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13616. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13617. * @param samplers defines an array of string used to represent textures
  13618. * @param defines defines the string containing the defines to use to compile the shaders
  13619. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13620. * @param onCompiled defines a function to call when the effect creation is successful
  13621. * @param onError defines a function to call when the effect creation has failed
  13622. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13623. * @returns the new Effect
  13624. */
  13625. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13626. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13627. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13628. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13629. if (this._compiledEffects[name]) {
  13630. var compiledEffect = this._compiledEffects[name];
  13631. if (onCompiled && compiledEffect.isReady()) {
  13632. onCompiled(compiledEffect);
  13633. }
  13634. return compiledEffect;
  13635. }
  13636. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13637. effect._key = name;
  13638. this._compiledEffects[name] = effect;
  13639. return effect;
  13640. };
  13641. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13642. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13643. };
  13644. ;
  13645. Engine.prototype._compileRawShader = function (source, type) {
  13646. var gl = this._gl;
  13647. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13648. gl.shaderSource(shader, source);
  13649. gl.compileShader(shader);
  13650. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13651. var log = gl.getShaderInfoLog(shader);
  13652. if (log) {
  13653. throw new Error(log);
  13654. }
  13655. }
  13656. if (!shader) {
  13657. throw new Error("Something went wrong while compile the shader.");
  13658. }
  13659. return shader;
  13660. };
  13661. ;
  13662. /**
  13663. * Directly creates a webGL program
  13664. * @param vertexCode defines the vertex shader code to use
  13665. * @param fragmentCode defines the fragment shader code to use
  13666. * @param context defines the webGL context to use (if not set, the current one will be used)
  13667. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13668. * @returns the new webGL program
  13669. */
  13670. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13671. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13672. context = context || this._gl;
  13673. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13674. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13675. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13676. };
  13677. /**
  13678. * Creates a webGL program
  13679. * @param vertexCode defines the vertex shader code to use
  13680. * @param fragmentCode defines the fragment shader code to use
  13681. * @param defines defines the string containing the defines to use to compile the shaders
  13682. * @param context defines the webGL context to use (if not set, the current one will be used)
  13683. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13684. * @returns the new webGL program
  13685. */
  13686. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13687. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13688. context = context || this._gl;
  13689. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13690. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13691. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13692. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13693. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13694. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13695. return program;
  13696. };
  13697. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13698. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13699. var shaderProgram = context.createProgram();
  13700. if (!shaderProgram) {
  13701. throw new Error("Unable to create program");
  13702. }
  13703. context.attachShader(shaderProgram, vertexShader);
  13704. context.attachShader(shaderProgram, fragmentShader);
  13705. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13706. var transformFeedback = this.createTransformFeedback();
  13707. this.bindTransformFeedback(transformFeedback);
  13708. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13709. shaderProgram.transformFeedback = transformFeedback;
  13710. }
  13711. context.linkProgram(shaderProgram);
  13712. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13713. this.bindTransformFeedback(null);
  13714. }
  13715. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13716. if (!linked) {
  13717. var error = context.getProgramInfoLog(shaderProgram);
  13718. if (error) {
  13719. throw new Error(error);
  13720. }
  13721. }
  13722. if (this.validateShaderPrograms) {
  13723. context.validateProgram(shaderProgram);
  13724. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13725. if (!validated) {
  13726. var error = context.getProgramInfoLog(shaderProgram);
  13727. if (error) {
  13728. throw new Error(error);
  13729. }
  13730. }
  13731. }
  13732. context.deleteShader(vertexShader);
  13733. context.deleteShader(fragmentShader);
  13734. return shaderProgram;
  13735. };
  13736. /**
  13737. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13738. * @param shaderProgram defines the webGL program to use
  13739. * @param uniformsNames defines the list of uniform names
  13740. * @returns an array of webGL uniform locations
  13741. */
  13742. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13743. var results = new Array();
  13744. for (var index = 0; index < uniformsNames.length; index++) {
  13745. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13746. }
  13747. return results;
  13748. };
  13749. /**
  13750. * Gets the lsit of active attributes for a given webGL program
  13751. * @param shaderProgram defines the webGL program to use
  13752. * @param attributesNames defines the list of attribute names to get
  13753. * @returns an array of indices indicating the offset of each attribute
  13754. */
  13755. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13756. var results = [];
  13757. for (var index = 0; index < attributesNames.length; index++) {
  13758. try {
  13759. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13760. }
  13761. catch (e) {
  13762. results.push(-1);
  13763. }
  13764. }
  13765. return results;
  13766. };
  13767. /**
  13768. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13769. * @param effect defines the effect to activate
  13770. */
  13771. Engine.prototype.enableEffect = function (effect) {
  13772. if (!effect || effect === this._currentEffect) {
  13773. return;
  13774. }
  13775. // Use program
  13776. this.bindSamplers(effect);
  13777. this._currentEffect = effect;
  13778. if (effect.onBind) {
  13779. effect.onBind(effect);
  13780. }
  13781. if (effect._onBindObservable) {
  13782. effect._onBindObservable.notifyObservers(effect);
  13783. }
  13784. };
  13785. /**
  13786. * Set the value of an uniform to an array of int32
  13787. * @param uniform defines the webGL uniform location where to store the value
  13788. * @param array defines the array of int32 to store
  13789. */
  13790. Engine.prototype.setIntArray = function (uniform, array) {
  13791. if (!uniform)
  13792. return;
  13793. this._gl.uniform1iv(uniform, array);
  13794. };
  13795. /**
  13796. * Set the value of an uniform to an array of int32 (stored as vec2)
  13797. * @param uniform defines the webGL uniform location where to store the value
  13798. * @param array defines the array of int32 to store
  13799. */
  13800. Engine.prototype.setIntArray2 = function (uniform, array) {
  13801. if (!uniform || array.length % 2 !== 0)
  13802. return;
  13803. this._gl.uniform2iv(uniform, array);
  13804. };
  13805. /**
  13806. * Set the value of an uniform to an array of int32 (stored as vec3)
  13807. * @param uniform defines the webGL uniform location where to store the value
  13808. * @param array defines the array of int32 to store
  13809. */
  13810. Engine.prototype.setIntArray3 = function (uniform, array) {
  13811. if (!uniform || array.length % 3 !== 0)
  13812. return;
  13813. this._gl.uniform3iv(uniform, array);
  13814. };
  13815. /**
  13816. * Set the value of an uniform to an array of int32 (stored as vec4)
  13817. * @param uniform defines the webGL uniform location where to store the value
  13818. * @param array defines the array of int32 to store
  13819. */
  13820. Engine.prototype.setIntArray4 = function (uniform, array) {
  13821. if (!uniform || array.length % 4 !== 0)
  13822. return;
  13823. this._gl.uniform4iv(uniform, array);
  13824. };
  13825. /**
  13826. * Set the value of an uniform to an array of float32
  13827. * @param uniform defines the webGL uniform location where to store the value
  13828. * @param array defines the array of float32 to store
  13829. */
  13830. Engine.prototype.setFloatArray = function (uniform, array) {
  13831. if (!uniform)
  13832. return;
  13833. this._gl.uniform1fv(uniform, array);
  13834. };
  13835. /**
  13836. * Set the value of an uniform to an array of float32 (stored as vec2)
  13837. * @param uniform defines the webGL uniform location where to store the value
  13838. * @param array defines the array of float32 to store
  13839. */
  13840. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13841. if (!uniform || array.length % 2 !== 0)
  13842. return;
  13843. this._gl.uniform2fv(uniform, array);
  13844. };
  13845. /**
  13846. * Set the value of an uniform to an array of float32 (stored as vec3)
  13847. * @param uniform defines the webGL uniform location where to store the value
  13848. * @param array defines the array of float32 to store
  13849. */
  13850. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13851. if (!uniform || array.length % 3 !== 0)
  13852. return;
  13853. this._gl.uniform3fv(uniform, array);
  13854. };
  13855. /**
  13856. * Set the value of an uniform to an array of float32 (stored as vec4)
  13857. * @param uniform defines the webGL uniform location where to store the value
  13858. * @param array defines the array of float32 to store
  13859. */
  13860. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13861. if (!uniform || array.length % 4 !== 0)
  13862. return;
  13863. this._gl.uniform4fv(uniform, array);
  13864. };
  13865. /**
  13866. * Set the value of an uniform to an array of number
  13867. * @param uniform defines the webGL uniform location where to store the value
  13868. * @param array defines the array of number to store
  13869. */
  13870. Engine.prototype.setArray = function (uniform, array) {
  13871. if (!uniform)
  13872. return;
  13873. this._gl.uniform1fv(uniform, array);
  13874. };
  13875. /**
  13876. * Set the value of an uniform to an array of number (stored as vec2)
  13877. * @param uniform defines the webGL uniform location where to store the value
  13878. * @param array defines the array of number to store
  13879. */
  13880. Engine.prototype.setArray2 = function (uniform, array) {
  13881. if (!uniform || array.length % 2 !== 0)
  13882. return;
  13883. this._gl.uniform2fv(uniform, array);
  13884. };
  13885. /**
  13886. * Set the value of an uniform to an array of number (stored as vec3)
  13887. * @param uniform defines the webGL uniform location where to store the value
  13888. * @param array defines the array of number to store
  13889. */
  13890. Engine.prototype.setArray3 = function (uniform, array) {
  13891. if (!uniform || array.length % 3 !== 0)
  13892. return;
  13893. this._gl.uniform3fv(uniform, array);
  13894. };
  13895. /**
  13896. * Set the value of an uniform to an array of number (stored as vec4)
  13897. * @param uniform defines the webGL uniform location where to store the value
  13898. * @param array defines the array of number to store
  13899. */
  13900. Engine.prototype.setArray4 = function (uniform, array) {
  13901. if (!uniform || array.length % 4 !== 0)
  13902. return;
  13903. this._gl.uniform4fv(uniform, array);
  13904. };
  13905. /**
  13906. * Set the value of an uniform to an array of float32 (stored as matrices)
  13907. * @param uniform defines the webGL uniform location where to store the value
  13908. * @param matrices defines the array of float32 to store
  13909. */
  13910. Engine.prototype.setMatrices = function (uniform, matrices) {
  13911. if (!uniform)
  13912. return;
  13913. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13914. };
  13915. /**
  13916. * Set the value of an uniform to a matrix
  13917. * @param uniform defines the webGL uniform location where to store the value
  13918. * @param matrix defines the matrix to store
  13919. */
  13920. Engine.prototype.setMatrix = function (uniform, matrix) {
  13921. if (!uniform)
  13922. return;
  13923. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13924. };
  13925. /**
  13926. * Set the value of an uniform to a matrix (3x3)
  13927. * @param uniform defines the webGL uniform location where to store the value
  13928. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13929. */
  13930. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13931. if (!uniform)
  13932. return;
  13933. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13934. };
  13935. /**
  13936. * Set the value of an uniform to a matrix (2x2)
  13937. * @param uniform defines the webGL uniform location where to store the value
  13938. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13939. */
  13940. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13941. if (!uniform)
  13942. return;
  13943. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13944. };
  13945. /**
  13946. * Set the value of an uniform to a number (int)
  13947. * @param uniform defines the webGL uniform location where to store the value
  13948. * @param value defines the int number to store
  13949. */
  13950. Engine.prototype.setInt = function (uniform, value) {
  13951. if (!uniform)
  13952. return;
  13953. this._gl.uniform1i(uniform, value);
  13954. };
  13955. /**
  13956. * Set the value of an uniform to a number (float)
  13957. * @param uniform defines the webGL uniform location where to store the value
  13958. * @param value defines the float number to store
  13959. */
  13960. Engine.prototype.setFloat = function (uniform, value) {
  13961. if (!uniform)
  13962. return;
  13963. this._gl.uniform1f(uniform, value);
  13964. };
  13965. /**
  13966. * Set the value of an uniform to a vec2
  13967. * @param uniform defines the webGL uniform location where to store the value
  13968. * @param x defines the 1st component of the value
  13969. * @param y defines the 2nd component of the value
  13970. */
  13971. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13972. if (!uniform)
  13973. return;
  13974. this._gl.uniform2f(uniform, x, y);
  13975. };
  13976. /**
  13977. * Set the value of an uniform to a vec3
  13978. * @param uniform defines the webGL uniform location where to store the value
  13979. * @param x defines the 1st component of the value
  13980. * @param y defines the 2nd component of the value
  13981. * @param z defines the 3rd component of the value
  13982. */
  13983. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13984. if (!uniform)
  13985. return;
  13986. this._gl.uniform3f(uniform, x, y, z);
  13987. };
  13988. /**
  13989. * Set the value of an uniform to a boolean
  13990. * @param uniform defines the webGL uniform location where to store the value
  13991. * @param bool defines the boolean to store
  13992. */
  13993. Engine.prototype.setBool = function (uniform, bool) {
  13994. if (!uniform)
  13995. return;
  13996. this._gl.uniform1i(uniform, bool);
  13997. };
  13998. /**
  13999. * Set the value of an uniform to a vec4
  14000. * @param uniform defines the webGL uniform location where to store the value
  14001. * @param x defines the 1st component of the value
  14002. * @param y defines the 2nd component of the value
  14003. * @param z defines the 3rd component of the value
  14004. * @param w defines the 4th component of the value
  14005. */
  14006. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14007. if (!uniform)
  14008. return;
  14009. this._gl.uniform4f(uniform, x, y, z, w);
  14010. };
  14011. /**
  14012. * Set the value of an uniform to a Color3
  14013. * @param uniform defines the webGL uniform location where to store the value
  14014. * @param color3 defines the color to store
  14015. */
  14016. Engine.prototype.setColor3 = function (uniform, color3) {
  14017. if (!uniform)
  14018. return;
  14019. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14020. };
  14021. /**
  14022. * Set the value of an uniform to a Color3 and an alpha value
  14023. * @param uniform defines the webGL uniform location where to store the value
  14024. * @param color3 defines the color to store
  14025. * @param alpha defines the alpha component to store
  14026. */
  14027. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14028. if (!uniform)
  14029. return;
  14030. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14031. };
  14032. /**
  14033. * Sets a Color4 on a uniform variable
  14034. * @param uniform defines the uniform location
  14035. * @param color4 defines the value to be set
  14036. */
  14037. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14038. if (!uniform)
  14039. return;
  14040. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14041. };
  14042. // States
  14043. /**
  14044. * Set various states to the webGL context
  14045. * @param culling defines backface culling state
  14046. * @param zOffset defines the value to apply to zOffset (0 by default)
  14047. * @param force defines if states must be applied even if cache is up to date
  14048. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14049. */
  14050. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14051. if (zOffset === void 0) { zOffset = 0; }
  14052. if (reverseSide === void 0) { reverseSide = false; }
  14053. // Culling
  14054. if (this._depthCullingState.cull !== culling || force) {
  14055. this._depthCullingState.cull = culling;
  14056. }
  14057. // Cull face
  14058. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14059. if (this._depthCullingState.cullFace !== cullFace || force) {
  14060. this._depthCullingState.cullFace = cullFace;
  14061. }
  14062. // Z offset
  14063. this.setZOffset(zOffset);
  14064. // Front face
  14065. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14066. if (this._depthCullingState.frontFace !== frontFace || force) {
  14067. this._depthCullingState.frontFace = frontFace;
  14068. }
  14069. };
  14070. /**
  14071. * Set the z offset to apply to current rendering
  14072. * @param value defines the offset to apply
  14073. */
  14074. Engine.prototype.setZOffset = function (value) {
  14075. this._depthCullingState.zOffset = value;
  14076. };
  14077. /**
  14078. * Gets the current value of the zOffset
  14079. * @returns the current zOffset state
  14080. */
  14081. Engine.prototype.getZOffset = function () {
  14082. return this._depthCullingState.zOffset;
  14083. };
  14084. /**
  14085. * Enable or disable depth buffering
  14086. * @param enable defines the state to set
  14087. */
  14088. Engine.prototype.setDepthBuffer = function (enable) {
  14089. this._depthCullingState.depthTest = enable;
  14090. };
  14091. /**
  14092. * Gets a boolean indicating if depth writing is enabled
  14093. * @returns the current depth writing state
  14094. */
  14095. Engine.prototype.getDepthWrite = function () {
  14096. return this._depthCullingState.depthMask;
  14097. };
  14098. /**
  14099. * Enable or disable depth writing
  14100. * @param enable defines the state to set
  14101. */
  14102. Engine.prototype.setDepthWrite = function (enable) {
  14103. this._depthCullingState.depthMask = enable;
  14104. };
  14105. /**
  14106. * Enable or disable color writing
  14107. * @param enable defines the state to set
  14108. */
  14109. Engine.prototype.setColorWrite = function (enable) {
  14110. this._gl.colorMask(enable, enable, enable, enable);
  14111. this._colorWrite = enable;
  14112. };
  14113. /**
  14114. * Gets a boolean indicating if color writing is enabled
  14115. * @returns the current color writing state
  14116. */
  14117. Engine.prototype.getColorWrite = function () {
  14118. return this._colorWrite;
  14119. };
  14120. /**
  14121. * Sets alpha constants used by some alpha blending modes
  14122. * @param r defines the red component
  14123. * @param g defines the green component
  14124. * @param b defines the blue component
  14125. * @param a defines the alpha component
  14126. */
  14127. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14128. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14129. };
  14130. /**
  14131. * Sets the current alpha mode
  14132. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14133. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14134. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14135. */
  14136. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14137. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14138. if (this._alphaMode === mode) {
  14139. return;
  14140. }
  14141. switch (mode) {
  14142. case Engine.ALPHA_DISABLE:
  14143. this._alphaState.alphaBlend = false;
  14144. break;
  14145. case Engine.ALPHA_PREMULTIPLIED:
  14146. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14147. this._alphaState.alphaBlend = true;
  14148. break;
  14149. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14150. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14151. this._alphaState.alphaBlend = true;
  14152. break;
  14153. case Engine.ALPHA_COMBINE:
  14154. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14155. this._alphaState.alphaBlend = true;
  14156. break;
  14157. case Engine.ALPHA_ONEONE:
  14158. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14159. this._alphaState.alphaBlend = true;
  14160. break;
  14161. case Engine.ALPHA_ADD:
  14162. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14163. this._alphaState.alphaBlend = true;
  14164. break;
  14165. case Engine.ALPHA_SUBTRACT:
  14166. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14167. this._alphaState.alphaBlend = true;
  14168. break;
  14169. case Engine.ALPHA_MULTIPLY:
  14170. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14171. this._alphaState.alphaBlend = true;
  14172. break;
  14173. case Engine.ALPHA_MAXIMIZED:
  14174. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14175. this._alphaState.alphaBlend = true;
  14176. break;
  14177. case Engine.ALPHA_INTERPOLATE:
  14178. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14179. this._alphaState.alphaBlend = true;
  14180. break;
  14181. case Engine.ALPHA_SCREENMODE:
  14182. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14183. this._alphaState.alphaBlend = true;
  14184. break;
  14185. }
  14186. if (!noDepthWriteChange) {
  14187. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14188. }
  14189. this._alphaMode = mode;
  14190. };
  14191. /**
  14192. * Gets the current alpha mode
  14193. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14194. * @returns the current alpha mode
  14195. */
  14196. Engine.prototype.getAlphaMode = function () {
  14197. return this._alphaMode;
  14198. };
  14199. // Textures
  14200. /**
  14201. * Clears the list of texture accessible through engine.
  14202. * This can help preventing texture load conflict due to name collision.
  14203. */
  14204. Engine.prototype.clearInternalTexturesCache = function () {
  14205. this._internalTexturesCache = [];
  14206. };
  14207. /**
  14208. * Force the entire cache to be cleared
  14209. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14210. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14211. */
  14212. Engine.prototype.wipeCaches = function (bruteForce) {
  14213. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14214. return;
  14215. }
  14216. this._currentEffect = null;
  14217. this._viewportCached.x = 0;
  14218. this._viewportCached.y = 0;
  14219. this._viewportCached.z = 0;
  14220. this._viewportCached.w = 0;
  14221. if (bruteForce) {
  14222. this.resetTextureCache();
  14223. this._currentProgram = null;
  14224. this._stencilState.reset();
  14225. this._depthCullingState.reset();
  14226. this.setDepthFunctionToLessOrEqual();
  14227. this._alphaState.reset();
  14228. this._unpackFlipYCached = null;
  14229. }
  14230. this._resetVertexBufferBinding();
  14231. this._cachedIndexBuffer = null;
  14232. this._cachedEffectForVertexBuffers = null;
  14233. this._unbindVertexArrayObject();
  14234. this.bindIndexBuffer(null);
  14235. };
  14236. /**
  14237. * Set the compressed texture format to use, based on the formats you have, and the formats
  14238. * supported by the hardware / browser.
  14239. *
  14240. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14241. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14242. * to API arguments needed to compressed textures. This puts the burden on the container
  14243. * generator to house the arcane code for determining these for current & future formats.
  14244. *
  14245. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14246. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14247. *
  14248. * Note: The result of this call is not taken into account when a texture is base64.
  14249. *
  14250. * @param formatsAvailable defines the list of those format families you have created
  14251. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14252. *
  14253. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14254. * @returns The extension selected.
  14255. */
  14256. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14257. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14258. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14259. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14260. return this._textureFormatInUse = this._texturesSupported[i];
  14261. }
  14262. }
  14263. }
  14264. // actively set format to nothing, to allow this to be called more than once
  14265. // and possibly fail the 2nd time
  14266. this._textureFormatInUse = null;
  14267. return null;
  14268. };
  14269. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14270. var gl = this._gl;
  14271. var magFilter = gl.NEAREST;
  14272. var minFilter = gl.NEAREST;
  14273. switch (samplingMode) {
  14274. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14275. magFilter = gl.LINEAR;
  14276. if (generateMipMaps) {
  14277. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14278. }
  14279. else {
  14280. minFilter = gl.LINEAR;
  14281. }
  14282. break;
  14283. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14284. magFilter = gl.LINEAR;
  14285. if (generateMipMaps) {
  14286. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14287. }
  14288. else {
  14289. minFilter = gl.LINEAR;
  14290. }
  14291. break;
  14292. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14293. magFilter = gl.NEAREST;
  14294. if (generateMipMaps) {
  14295. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14296. }
  14297. else {
  14298. minFilter = gl.NEAREST;
  14299. }
  14300. break;
  14301. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14302. magFilter = gl.NEAREST;
  14303. if (generateMipMaps) {
  14304. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14305. }
  14306. else {
  14307. minFilter = gl.NEAREST;
  14308. }
  14309. break;
  14310. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14311. magFilter = gl.NEAREST;
  14312. if (generateMipMaps) {
  14313. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14314. }
  14315. else {
  14316. minFilter = gl.LINEAR;
  14317. }
  14318. break;
  14319. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14320. magFilter = gl.NEAREST;
  14321. if (generateMipMaps) {
  14322. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14323. }
  14324. else {
  14325. minFilter = gl.LINEAR;
  14326. }
  14327. break;
  14328. case Engine.TEXTURE_NEAREST_LINEAR:
  14329. magFilter = gl.NEAREST;
  14330. minFilter = gl.LINEAR;
  14331. break;
  14332. case Engine.TEXTURE_NEAREST_NEAREST:
  14333. magFilter = gl.NEAREST;
  14334. minFilter = gl.NEAREST;
  14335. break;
  14336. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14337. magFilter = gl.LINEAR;
  14338. if (generateMipMaps) {
  14339. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14340. }
  14341. else {
  14342. minFilter = gl.NEAREST;
  14343. }
  14344. break;
  14345. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14346. magFilter = gl.LINEAR;
  14347. if (generateMipMaps) {
  14348. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14349. }
  14350. else {
  14351. minFilter = gl.NEAREST;
  14352. }
  14353. break;
  14354. case Engine.TEXTURE_LINEAR_LINEAR:
  14355. magFilter = gl.LINEAR;
  14356. minFilter = gl.LINEAR;
  14357. break;
  14358. case Engine.TEXTURE_LINEAR_NEAREST:
  14359. magFilter = gl.LINEAR;
  14360. minFilter = gl.NEAREST;
  14361. break;
  14362. }
  14363. return {
  14364. min: minFilter,
  14365. mag: magFilter
  14366. };
  14367. };
  14368. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14369. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14370. var img;
  14371. var onload = function () {
  14372. loadedImages[index] = img;
  14373. loadedImages._internalCount++;
  14374. if (scene) {
  14375. scene._removePendingData(img);
  14376. }
  14377. if (loadedImages._internalCount === 6) {
  14378. onfinish(loadedImages);
  14379. }
  14380. };
  14381. var onerror = function (message, exception) {
  14382. if (scene) {
  14383. scene._removePendingData(img);
  14384. }
  14385. if (onErrorCallBack) {
  14386. onErrorCallBack(message, exception);
  14387. }
  14388. };
  14389. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14390. if (scene) {
  14391. scene._addPendingData(img);
  14392. }
  14393. };
  14394. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14395. if (onError === void 0) { onError = null; }
  14396. var loadedImages = [];
  14397. loadedImages._internalCount = 0;
  14398. for (var index = 0; index < 6; index++) {
  14399. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14400. }
  14401. };
  14402. ;
  14403. /** @hidden */
  14404. Engine.prototype._createTexture = function () {
  14405. var texture = this._gl.createTexture();
  14406. if (!texture) {
  14407. throw new Error("Unable to create texture");
  14408. }
  14409. return texture;
  14410. };
  14411. /**
  14412. * Usually called from BABYLON.Texture.ts.
  14413. * Passed information to create a WebGLTexture
  14414. * @param urlArg defines a value which contains one of the following:
  14415. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14416. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14417. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14418. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14419. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14420. * @param scene needed for loading to the correct scene
  14421. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14422. * @param onLoad optional callback to be called upon successful completion
  14423. * @param onError optional callback to be called upon failure
  14424. * @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
  14425. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14426. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14427. * @param forcedExtension defines the extension to use to pick the right loader
  14428. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14429. */
  14430. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14431. var _this = this;
  14432. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14433. if (onLoad === void 0) { onLoad = null; }
  14434. if (onError === void 0) { onError = null; }
  14435. if (buffer === void 0) { buffer = null; }
  14436. if (fallback === void 0) { fallback = null; }
  14437. if (format === void 0) { format = null; }
  14438. if (forcedExtension === void 0) { forcedExtension = null; }
  14439. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14440. var fromData = url.substr(0, 5) === "data:";
  14441. var fromBlob = url.substr(0, 5) === "blob:";
  14442. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14443. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14444. // establish the file extension, if possible
  14445. var lastDot = url.lastIndexOf('.');
  14446. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14447. var loader = null;
  14448. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14449. var availableLoader = _a[_i];
  14450. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14451. loader = availableLoader;
  14452. break;
  14453. }
  14454. }
  14455. if (loader) {
  14456. url = loader.transformUrl(url, this._textureFormatInUse);
  14457. }
  14458. if (scene) {
  14459. scene._addPendingData(texture);
  14460. }
  14461. texture.url = url;
  14462. texture.generateMipMaps = !noMipmap;
  14463. texture.samplingMode = samplingMode;
  14464. texture.invertY = invertY;
  14465. if (!this._doNotHandleContextLost) {
  14466. // Keep a link to the buffer only if we plan to handle context lost
  14467. texture._buffer = buffer;
  14468. }
  14469. var onLoadObserver = null;
  14470. if (onLoad && !fallback) {
  14471. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14472. }
  14473. if (!fallback)
  14474. this._internalTexturesCache.push(texture);
  14475. var onInternalError = function (message, exception) {
  14476. if (scene) {
  14477. scene._removePendingData(texture);
  14478. }
  14479. var customFallback = false;
  14480. if (loader) {
  14481. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14482. if (fallbackUrl) {
  14483. // Add Back
  14484. customFallback = true;
  14485. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14486. }
  14487. }
  14488. if (!customFallback) {
  14489. if (onLoadObserver) {
  14490. texture.onLoadedObservable.remove(onLoadObserver);
  14491. }
  14492. if (BABYLON.Tools.UseFallbackTexture) {
  14493. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14494. }
  14495. }
  14496. if (onError) {
  14497. onError(message || "Unknown error", exception);
  14498. }
  14499. };
  14500. // processing for non-image formats
  14501. if (loader) {
  14502. var callback = function (data) {
  14503. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14504. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14505. done();
  14506. return false;
  14507. }, samplingMode);
  14508. });
  14509. };
  14510. if (!buffer) {
  14511. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14512. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14513. });
  14514. }
  14515. else {
  14516. callback(buffer);
  14517. }
  14518. }
  14519. else {
  14520. var onload = function (img) {
  14521. if (fromBlob && !_this._doNotHandleContextLost) {
  14522. // We need to store the image if we need to rebuild the texture
  14523. // in case of a webgl context lost
  14524. texture._buffer = img;
  14525. }
  14526. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14527. var gl = _this._gl;
  14528. var isPot = (img.width === potWidth && img.height === potHeight);
  14529. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14530. if (isPot) {
  14531. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14532. return false;
  14533. }
  14534. var maxTextureSize = _this._caps.maxTextureSize;
  14535. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14536. _this._prepareWorkingCanvas();
  14537. if (!_this._workingCanvas || !_this._workingContext) {
  14538. return false;
  14539. }
  14540. _this._workingCanvas.width = potWidth;
  14541. _this._workingCanvas.height = potHeight;
  14542. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14543. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14544. texture.width = potWidth;
  14545. texture.height = potHeight;
  14546. return false;
  14547. }
  14548. else {
  14549. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14550. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14551. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14552. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14553. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14554. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14555. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14556. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14557. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14558. _this._releaseTexture(source_1);
  14559. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14560. continuationCallback();
  14561. });
  14562. }
  14563. return true;
  14564. }, samplingMode);
  14565. };
  14566. if (!fromData || isBase64) {
  14567. if (buffer instanceof HTMLImageElement) {
  14568. onload(buffer);
  14569. }
  14570. else {
  14571. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14572. }
  14573. }
  14574. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14575. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14576. }
  14577. else {
  14578. onload(buffer);
  14579. }
  14580. }
  14581. return texture;
  14582. };
  14583. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14584. var _this = this;
  14585. var rtt = this.createRenderTargetTexture({
  14586. width: destination.width,
  14587. height: destination.height,
  14588. }, {
  14589. generateMipMaps: false,
  14590. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14591. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14592. generateDepthBuffer: false,
  14593. generateStencilBuffer: false
  14594. });
  14595. if (!this._rescalePostProcess) {
  14596. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14597. }
  14598. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14599. _this._rescalePostProcess.onApply = function (effect) {
  14600. effect._bindTexture("textureSampler", source);
  14601. };
  14602. var hostingScene = scene;
  14603. if (!hostingScene) {
  14604. hostingScene = _this.scenes[_this.scenes.length - 1];
  14605. }
  14606. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14607. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14608. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14609. _this.unBindFramebuffer(rtt);
  14610. _this._releaseTexture(rtt);
  14611. if (onComplete) {
  14612. onComplete();
  14613. }
  14614. });
  14615. };
  14616. /**
  14617. * Update a raw texture
  14618. * @param texture defines the texture to update
  14619. * @param data defines the data to store in the texture
  14620. * @param format defines the format of the data
  14621. * @param invertY defines if data must be stored with Y axis inverted
  14622. * @param compression defines the compression used (null by default)
  14623. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14624. */
  14625. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14626. if (compression === void 0) { compression = null; }
  14627. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14628. if (!texture) {
  14629. return;
  14630. }
  14631. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14632. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14633. // babylon's internalFormat but gl's texImage2D format
  14634. var internalFormat = this._getInternalFormat(format);
  14635. var textureType = this._getWebGLTextureType(type);
  14636. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14637. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14638. if (!this._doNotHandleContextLost) {
  14639. texture._bufferView = data;
  14640. texture.format = format;
  14641. texture.type = type;
  14642. texture.invertY = invertY;
  14643. texture._compression = compression;
  14644. }
  14645. if (texture.width % 4 !== 0) {
  14646. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14647. }
  14648. if (compression && data) {
  14649. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14650. }
  14651. else {
  14652. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14653. }
  14654. if (texture.generateMipMaps) {
  14655. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14656. }
  14657. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14658. // this.resetTextureCache();
  14659. texture.isReady = true;
  14660. };
  14661. /**
  14662. * Creates a raw texture
  14663. * @param data defines the data to store in the texture
  14664. * @param width defines the width of the texture
  14665. * @param height defines the height of the texture
  14666. * @param format defines the format of the data
  14667. * @param generateMipMaps defines if the engine should generate the mip levels
  14668. * @param invertY defines if data must be stored with Y axis inverted
  14669. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14670. * @param compression defines the compression used (null by default)
  14671. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14672. * @returns the raw texture inside an InternalTexture
  14673. */
  14674. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14675. if (compression === void 0) { compression = null; }
  14676. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14677. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14678. texture.baseWidth = width;
  14679. texture.baseHeight = height;
  14680. texture.width = width;
  14681. texture.height = height;
  14682. texture.format = format;
  14683. texture.generateMipMaps = generateMipMaps;
  14684. texture.samplingMode = samplingMode;
  14685. texture.invertY = invertY;
  14686. texture._compression = compression;
  14687. texture.type = type;
  14688. if (!this._doNotHandleContextLost) {
  14689. texture._bufferView = data;
  14690. }
  14691. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14692. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14693. // Filters
  14694. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14695. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14696. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14697. if (generateMipMaps) {
  14698. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14699. }
  14700. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14701. this._internalTexturesCache.push(texture);
  14702. return texture;
  14703. };
  14704. /** @hidden */
  14705. Engine.prototype._unpackFlipY = function (value) {
  14706. if (this._unpackFlipYCached !== value) {
  14707. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14708. if (this.enableUnpackFlipYCached) {
  14709. this._unpackFlipYCached = value;
  14710. }
  14711. }
  14712. };
  14713. /** @hidden */
  14714. Engine.prototype._getUnpackAlignement = function () {
  14715. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14716. };
  14717. /**
  14718. * Creates a dynamic texture
  14719. * @param width defines the width of the texture
  14720. * @param height defines the height of the texture
  14721. * @param generateMipMaps defines if the engine should generate the mip levels
  14722. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14723. * @returns the dynamic texture inside an InternalTexture
  14724. */
  14725. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14726. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14727. texture.baseWidth = width;
  14728. texture.baseHeight = height;
  14729. if (generateMipMaps) {
  14730. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14731. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14732. }
  14733. // this.resetTextureCache();
  14734. texture.width = width;
  14735. texture.height = height;
  14736. texture.isReady = false;
  14737. texture.generateMipMaps = generateMipMaps;
  14738. texture.samplingMode = samplingMode;
  14739. this.updateTextureSamplingMode(samplingMode, texture);
  14740. this._internalTexturesCache.push(texture);
  14741. return texture;
  14742. };
  14743. /**
  14744. * Update the sampling mode of a given texture
  14745. * @param samplingMode defines the required sampling mode
  14746. * @param texture defines the texture to update
  14747. */
  14748. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14749. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14750. if (texture.isCube) {
  14751. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14752. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14753. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14754. }
  14755. else if (texture.is3D) {
  14756. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14757. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14758. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14759. }
  14760. else {
  14761. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14762. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14763. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14764. }
  14765. texture.samplingMode = samplingMode;
  14766. };
  14767. /**
  14768. * Update the content of a dynamic texture
  14769. * @param texture defines the texture to update
  14770. * @param canvas defines the canvas containing the source
  14771. * @param invertY defines if data must be stored with Y axis inverted
  14772. * @param premulAlpha defines if alpha is stored as premultiplied
  14773. * @param format defines the format of the data
  14774. */
  14775. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14776. if (premulAlpha === void 0) { premulAlpha = false; }
  14777. if (!texture) {
  14778. return;
  14779. }
  14780. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14781. this._unpackFlipY(invertY);
  14782. if (premulAlpha) {
  14783. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14784. }
  14785. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14786. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14787. if (texture.generateMipMaps) {
  14788. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14789. }
  14790. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14791. if (premulAlpha) {
  14792. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14793. }
  14794. texture.isReady = true;
  14795. };
  14796. /**
  14797. * Update a video texture
  14798. * @param texture defines the texture to update
  14799. * @param video defines the video element to use
  14800. * @param invertY defines if data must be stored with Y axis inverted
  14801. */
  14802. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14803. if (!texture || texture._isDisabled) {
  14804. return;
  14805. }
  14806. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14807. this._unpackFlipY(!invertY); // Video are upside down by default
  14808. try {
  14809. // Testing video texture support
  14810. if (this._videoTextureSupported === undefined) {
  14811. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14812. if (this._gl.getError() !== 0) {
  14813. this._videoTextureSupported = false;
  14814. }
  14815. else {
  14816. this._videoTextureSupported = true;
  14817. }
  14818. }
  14819. // Copy video through the current working canvas if video texture is not supported
  14820. if (!this._videoTextureSupported) {
  14821. if (!texture._workingCanvas) {
  14822. texture._workingCanvas = document.createElement("canvas");
  14823. var context = texture._workingCanvas.getContext("2d");
  14824. if (!context) {
  14825. throw new Error("Unable to get 2d context");
  14826. }
  14827. texture._workingContext = context;
  14828. texture._workingCanvas.width = texture.width;
  14829. texture._workingCanvas.height = texture.height;
  14830. }
  14831. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14832. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14833. }
  14834. else {
  14835. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14836. }
  14837. if (texture.generateMipMaps) {
  14838. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14839. }
  14840. if (!wasPreviouslyBound) {
  14841. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14842. }
  14843. // this.resetTextureCache();
  14844. texture.isReady = true;
  14845. }
  14846. catch (ex) {
  14847. // Something unexpected
  14848. // Let's disable the texture
  14849. texture._isDisabled = true;
  14850. }
  14851. };
  14852. /**
  14853. * Updates a depth texture Comparison Mode and Function.
  14854. * If the comparison Function is equal to 0, the mode will be set to none.
  14855. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14856. * @param texture The texture to set the comparison function for
  14857. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14858. */
  14859. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14860. if (this.webGLVersion === 1) {
  14861. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14862. return;
  14863. }
  14864. var gl = this._gl;
  14865. if (texture.isCube) {
  14866. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14867. if (comparisonFunction === 0) {
  14868. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14869. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14870. }
  14871. else {
  14872. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14873. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14874. }
  14875. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14876. }
  14877. else {
  14878. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14879. if (comparisonFunction === 0) {
  14880. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14881. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14882. }
  14883. else {
  14884. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14885. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14886. }
  14887. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14888. }
  14889. texture._comparisonFunction = comparisonFunction;
  14890. };
  14891. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14892. var width = size.width || size;
  14893. var height = size.height || size;
  14894. internalTexture.baseWidth = width;
  14895. internalTexture.baseHeight = height;
  14896. internalTexture.width = width;
  14897. internalTexture.height = height;
  14898. internalTexture.isReady = true;
  14899. internalTexture.samples = 1;
  14900. internalTexture.generateMipMaps = false;
  14901. internalTexture._generateDepthBuffer = true;
  14902. internalTexture._generateStencilBuffer = generateStencil;
  14903. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14904. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14905. internalTexture._comparisonFunction = comparisonFunction;
  14906. var gl = this._gl;
  14907. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14908. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14909. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14910. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14911. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14912. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14913. if (comparisonFunction === 0) {
  14914. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14915. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14916. }
  14917. else {
  14918. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14919. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14920. }
  14921. };
  14922. /**
  14923. * Creates a depth stencil texture.
  14924. * This is only available in WebGL 2 or with the depth texture extension available.
  14925. * @param size The size of face edge in the texture.
  14926. * @param options The options defining the texture.
  14927. * @returns The texture
  14928. */
  14929. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14930. if (options.isCube) {
  14931. var width = size.width || size;
  14932. return this._createDepthStencilCubeTexture(width, options);
  14933. }
  14934. else {
  14935. return this._createDepthStencilTexture(size, options);
  14936. }
  14937. };
  14938. /**
  14939. * Creates a depth stencil texture.
  14940. * This is only available in WebGL 2 or with the depth texture extension available.
  14941. * @param size The size of face edge in the texture.
  14942. * @param options The options defining the texture.
  14943. * @returns The texture
  14944. */
  14945. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14946. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14947. if (!this._caps.depthTextureExtension) {
  14948. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14949. return internalTexture;
  14950. }
  14951. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14952. var gl = this._gl;
  14953. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14954. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14955. if (this.webGLVersion > 1) {
  14956. if (internalOptions.generateStencil) {
  14957. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14958. }
  14959. else {
  14960. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14961. }
  14962. }
  14963. else {
  14964. if (internalOptions.generateStencil) {
  14965. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14966. }
  14967. else {
  14968. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14969. }
  14970. }
  14971. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14972. return internalTexture;
  14973. };
  14974. /**
  14975. * Creates a depth stencil cube texture.
  14976. * This is only available in WebGL 2.
  14977. * @param size The size of face edge in the cube texture.
  14978. * @param options The options defining the cube texture.
  14979. * @returns The cube texture
  14980. */
  14981. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14982. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14983. internalTexture.isCube = true;
  14984. if (this.webGLVersion === 1) {
  14985. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14986. return internalTexture;
  14987. }
  14988. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14989. var gl = this._gl;
  14990. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14991. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14992. // Create the depth/stencil buffer
  14993. for (var face = 0; face < 6; face++) {
  14994. if (internalOptions.generateStencil) {
  14995. 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);
  14996. }
  14997. else {
  14998. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14999. }
  15000. }
  15001. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15002. return internalTexture;
  15003. };
  15004. /**
  15005. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15006. * @param renderTarget The render target to set the frame buffer for
  15007. */
  15008. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15009. // Create the framebuffer
  15010. var internalTexture = renderTarget.getInternalTexture();
  15011. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15012. return;
  15013. }
  15014. var gl = this._gl;
  15015. var depthStencilTexture = renderTarget.depthStencilTexture;
  15016. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15017. if (depthStencilTexture.isCube) {
  15018. if (depthStencilTexture._generateStencilBuffer) {
  15019. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15020. }
  15021. else {
  15022. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15023. }
  15024. }
  15025. else {
  15026. if (depthStencilTexture._generateStencilBuffer) {
  15027. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15028. }
  15029. else {
  15030. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15031. }
  15032. }
  15033. this.bindUnboundFramebuffer(null);
  15034. };
  15035. /**
  15036. * Creates a new render target texture
  15037. * @param size defines the size of the texture
  15038. * @param options defines the options used to create the texture
  15039. * @returns a new render target texture stored in an InternalTexture
  15040. */
  15041. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15042. var fullOptions = new RenderTargetCreationOptions();
  15043. if (options !== undefined && typeof options === "object") {
  15044. fullOptions.generateMipMaps = options.generateMipMaps;
  15045. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15046. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15047. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15048. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15049. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15050. }
  15051. else {
  15052. fullOptions.generateMipMaps = options;
  15053. fullOptions.generateDepthBuffer = true;
  15054. fullOptions.generateStencilBuffer = false;
  15055. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15056. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15057. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15058. }
  15059. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15060. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15061. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15062. }
  15063. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15064. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15065. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15066. }
  15067. var gl = this._gl;
  15068. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15069. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15070. var width = size.width || size;
  15071. var height = size.height || size;
  15072. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15073. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15074. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15075. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15076. }
  15077. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15078. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15079. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15080. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15081. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15082. // Create the framebuffer
  15083. var currentFrameBuffer = this._currentFramebuffer;
  15084. var framebuffer = gl.createFramebuffer();
  15085. this.bindUnboundFramebuffer(framebuffer);
  15086. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15087. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15088. if (fullOptions.generateMipMaps) {
  15089. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15090. }
  15091. // Unbind
  15092. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15093. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15094. this.bindUnboundFramebuffer(currentFrameBuffer);
  15095. texture._framebuffer = framebuffer;
  15096. texture.baseWidth = width;
  15097. texture.baseHeight = height;
  15098. texture.width = width;
  15099. texture.height = height;
  15100. texture.isReady = true;
  15101. texture.samples = 1;
  15102. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15103. texture.samplingMode = fullOptions.samplingMode;
  15104. texture.type = fullOptions.type;
  15105. texture.format = fullOptions.format;
  15106. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15107. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15108. // this.resetTextureCache();
  15109. this._internalTexturesCache.push(texture);
  15110. return texture;
  15111. };
  15112. /**
  15113. * Create a multi render target texture
  15114. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15115. * @param size defines the size of the texture
  15116. * @param options defines the creation options
  15117. * @returns the cube texture as an InternalTexture
  15118. */
  15119. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15120. var generateMipMaps = false;
  15121. var generateDepthBuffer = true;
  15122. var generateStencilBuffer = false;
  15123. var generateDepthTexture = false;
  15124. var textureCount = 1;
  15125. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15126. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15127. var types = new Array();
  15128. var samplingModes = new Array();
  15129. if (options !== undefined) {
  15130. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15131. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15132. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15133. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15134. textureCount = options.textureCount || 1;
  15135. if (options.types) {
  15136. types = options.types;
  15137. }
  15138. if (options.samplingModes) {
  15139. samplingModes = options.samplingModes;
  15140. }
  15141. }
  15142. var gl = this._gl;
  15143. // Create the framebuffer
  15144. var framebuffer = gl.createFramebuffer();
  15145. this.bindUnboundFramebuffer(framebuffer);
  15146. var width = size.width || size;
  15147. var height = size.height || size;
  15148. var textures = [];
  15149. var attachments = [];
  15150. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15151. for (var i = 0; i < textureCount; i++) {
  15152. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15153. var type = types[i] || defaultType;
  15154. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15155. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15156. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15157. }
  15158. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15159. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15160. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15161. }
  15162. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15163. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15164. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15165. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15166. }
  15167. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15168. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15169. textures.push(texture);
  15170. attachments.push(attachment);
  15171. gl.activeTexture(gl["TEXTURE" + i]);
  15172. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15176. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15177. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15178. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15179. if (generateMipMaps) {
  15180. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15181. }
  15182. // Unbind
  15183. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15184. texture._framebuffer = framebuffer;
  15185. texture._depthStencilBuffer = depthStencilBuffer;
  15186. texture.baseWidth = width;
  15187. texture.baseHeight = height;
  15188. texture.width = width;
  15189. texture.height = height;
  15190. texture.isReady = true;
  15191. texture.samples = 1;
  15192. texture.generateMipMaps = generateMipMaps;
  15193. texture.samplingMode = samplingMode;
  15194. texture.type = type;
  15195. texture._generateDepthBuffer = generateDepthBuffer;
  15196. texture._generateStencilBuffer = generateStencilBuffer;
  15197. texture._attachments = attachments;
  15198. this._internalTexturesCache.push(texture);
  15199. }
  15200. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15201. // Depth texture
  15202. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15203. gl.activeTexture(gl.TEXTURE0);
  15204. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15205. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15206. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15207. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15208. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15209. 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);
  15210. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15211. depthTexture._framebuffer = framebuffer;
  15212. depthTexture.baseWidth = width;
  15213. depthTexture.baseHeight = height;
  15214. depthTexture.width = width;
  15215. depthTexture.height = height;
  15216. depthTexture.isReady = true;
  15217. depthTexture.samples = 1;
  15218. depthTexture.generateMipMaps = generateMipMaps;
  15219. depthTexture.samplingMode = gl.NEAREST;
  15220. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15221. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15222. textures.push(depthTexture);
  15223. this._internalTexturesCache.push(depthTexture);
  15224. }
  15225. gl.drawBuffers(attachments);
  15226. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15227. this.bindUnboundFramebuffer(null);
  15228. this.resetTextureCache();
  15229. return textures;
  15230. };
  15231. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15232. if (samples === void 0) { samples = 1; }
  15233. var depthStencilBuffer = null;
  15234. var gl = this._gl;
  15235. // Create the depth/stencil buffer
  15236. if (generateStencilBuffer) {
  15237. depthStencilBuffer = gl.createRenderbuffer();
  15238. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15239. if (samples > 1) {
  15240. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15241. }
  15242. else {
  15243. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15244. }
  15245. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15246. }
  15247. else if (generateDepthBuffer) {
  15248. depthStencilBuffer = gl.createRenderbuffer();
  15249. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15250. if (samples > 1) {
  15251. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15252. }
  15253. else {
  15254. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15255. }
  15256. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15257. }
  15258. return depthStencilBuffer;
  15259. };
  15260. /**
  15261. * Updates the sample count of a render target texture
  15262. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15263. * @param texture defines the texture to update
  15264. * @param samples defines the sample count to set
  15265. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15266. */
  15267. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15268. if (this.webGLVersion < 2 || !texture) {
  15269. return 1;
  15270. }
  15271. if (texture.samples === samples) {
  15272. return samples;
  15273. }
  15274. var gl = this._gl;
  15275. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15276. // Dispose previous render buffers
  15277. if (texture._depthStencilBuffer) {
  15278. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15279. texture._depthStencilBuffer = null;
  15280. }
  15281. if (texture._MSAAFramebuffer) {
  15282. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15283. texture._MSAAFramebuffer = null;
  15284. }
  15285. if (texture._MSAARenderBuffer) {
  15286. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15287. texture._MSAARenderBuffer = null;
  15288. }
  15289. if (samples > 1) {
  15290. var framebuffer = gl.createFramebuffer();
  15291. if (!framebuffer) {
  15292. throw new Error("Unable to create multi sampled framebuffer");
  15293. }
  15294. texture._MSAAFramebuffer = framebuffer;
  15295. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15296. var colorRenderbuffer = gl.createRenderbuffer();
  15297. if (!colorRenderbuffer) {
  15298. throw new Error("Unable to create multi sampled framebuffer");
  15299. }
  15300. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15301. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15302. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15303. texture._MSAARenderBuffer = colorRenderbuffer;
  15304. }
  15305. else {
  15306. this.bindUnboundFramebuffer(texture._framebuffer);
  15307. }
  15308. texture.samples = samples;
  15309. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15310. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15311. this.bindUnboundFramebuffer(null);
  15312. return samples;
  15313. };
  15314. /**
  15315. * Update the sample count for a given multiple render target texture
  15316. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15317. * @param textures defines the textures to update
  15318. * @param samples defines the sample count to set
  15319. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15320. */
  15321. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15322. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15323. return 1;
  15324. }
  15325. if (textures[0].samples === samples) {
  15326. return samples;
  15327. }
  15328. var gl = this._gl;
  15329. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15330. // Dispose previous render buffers
  15331. if (textures[0]._depthStencilBuffer) {
  15332. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15333. textures[0]._depthStencilBuffer = null;
  15334. }
  15335. if (textures[0]._MSAAFramebuffer) {
  15336. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15337. textures[0]._MSAAFramebuffer = null;
  15338. }
  15339. for (var i = 0; i < textures.length; i++) {
  15340. if (textures[i]._MSAARenderBuffer) {
  15341. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15342. textures[i]._MSAARenderBuffer = null;
  15343. }
  15344. }
  15345. if (samples > 1) {
  15346. var framebuffer = gl.createFramebuffer();
  15347. if (!framebuffer) {
  15348. throw new Error("Unable to create multi sampled framebuffer");
  15349. }
  15350. this.bindUnboundFramebuffer(framebuffer);
  15351. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15352. var attachments = [];
  15353. for (var i = 0; i < textures.length; i++) {
  15354. var texture = textures[i];
  15355. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15356. var colorRenderbuffer = gl.createRenderbuffer();
  15357. if (!colorRenderbuffer) {
  15358. throw new Error("Unable to create multi sampled framebuffer");
  15359. }
  15360. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15361. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15362. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15363. texture._MSAAFramebuffer = framebuffer;
  15364. texture._MSAARenderBuffer = colorRenderbuffer;
  15365. texture.samples = samples;
  15366. texture._depthStencilBuffer = depthStencilBuffer;
  15367. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15368. attachments.push(attachment);
  15369. }
  15370. gl.drawBuffers(attachments);
  15371. }
  15372. else {
  15373. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15374. }
  15375. this.bindUnboundFramebuffer(null);
  15376. return samples;
  15377. };
  15378. /** @hidden */
  15379. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15380. if (faceIndex === void 0) { faceIndex = 0; }
  15381. if (lod === void 0) { lod = 0; }
  15382. var gl = this._gl;
  15383. var target = gl.TEXTURE_2D;
  15384. if (texture.isCube) {
  15385. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15386. }
  15387. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15388. };
  15389. /** @hidden */
  15390. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15391. if (faceIndex === void 0) { faceIndex = 0; }
  15392. if (lod === void 0) { lod = 0; }
  15393. var gl = this._gl;
  15394. var textureType = this._getWebGLTextureType(texture.type);
  15395. var format = this._getInternalFormat(texture.format);
  15396. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15397. this._unpackFlipY(texture.invertY);
  15398. var target = gl.TEXTURE_2D;
  15399. if (texture.isCube) {
  15400. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15401. }
  15402. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15403. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15404. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15405. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15406. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15407. };
  15408. /** @hidden */
  15409. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15410. if (faceIndex === void 0) { faceIndex = 0; }
  15411. if (lod === void 0) { lod = 0; }
  15412. var gl = this._gl;
  15413. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15414. this._bindTextureDirectly(bindTarget, texture, true);
  15415. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15416. this._bindTextureDirectly(bindTarget, null, true);
  15417. };
  15418. /** @hidden */
  15419. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15420. if (faceIndex === void 0) { faceIndex = 0; }
  15421. if (lod === void 0) { lod = 0; }
  15422. var gl = this._gl;
  15423. var textureType = this._getWebGLTextureType(texture.type);
  15424. var format = this._getInternalFormat(texture.format);
  15425. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15426. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15427. this._bindTextureDirectly(bindTarget, texture, true);
  15428. this._unpackFlipY(texture.invertY);
  15429. var target = gl.TEXTURE_2D;
  15430. if (texture.isCube) {
  15431. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15432. }
  15433. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15434. this._bindTextureDirectly(bindTarget, null, true);
  15435. };
  15436. /**
  15437. * Creates a new render target cube texture
  15438. * @param size defines the size of the texture
  15439. * @param options defines the options used to create the texture
  15440. * @returns a new render target cube texture stored in an InternalTexture
  15441. */
  15442. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15443. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15444. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15445. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15446. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15447. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15448. }
  15449. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15450. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15451. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15452. }
  15453. var gl = this._gl;
  15454. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15455. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15456. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15457. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15458. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15459. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15460. }
  15461. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15462. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15463. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15464. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15465. for (var face = 0; face < 6; face++) {
  15466. 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);
  15467. }
  15468. // Create the framebuffer
  15469. var framebuffer = gl.createFramebuffer();
  15470. this.bindUnboundFramebuffer(framebuffer);
  15471. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15472. // MipMaps
  15473. if (fullOptions.generateMipMaps) {
  15474. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15475. }
  15476. // Unbind
  15477. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15478. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15479. this.bindUnboundFramebuffer(null);
  15480. texture._framebuffer = framebuffer;
  15481. texture.width = size;
  15482. texture.height = size;
  15483. texture.isReady = true;
  15484. texture.isCube = true;
  15485. texture.samples = 1;
  15486. texture.generateMipMaps = fullOptions.generateMipMaps;
  15487. texture.samplingMode = fullOptions.samplingMode;
  15488. texture.type = fullOptions.type;
  15489. texture.format = fullOptions.format;
  15490. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15491. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15492. this._internalTexturesCache.push(texture);
  15493. return texture;
  15494. };
  15495. /**
  15496. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15497. * @param rootUrl defines the url where the file to load is located
  15498. * @param scene defines the current scene
  15499. * @param lodScale defines scale to apply to the mip map selection
  15500. * @param lodOffset defines offset to apply to the mip map selection
  15501. * @param onLoad defines an optional callback raised when the texture is loaded
  15502. * @param onError defines an optional callback raised if there is an issue to load the texture
  15503. * @param format defines the format of the data
  15504. * @param forcedExtension defines the extension to use to pick the right loader
  15505. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15506. * @returns the cube texture as an InternalTexture
  15507. */
  15508. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15509. var _this = this;
  15510. if (onLoad === void 0) { onLoad = null; }
  15511. if (onError === void 0) { onError = null; }
  15512. if (forcedExtension === void 0) { forcedExtension = null; }
  15513. if (createPolynomials === void 0) { createPolynomials = true; }
  15514. var callback = function (loadData) {
  15515. if (!loadData) {
  15516. if (onLoad) {
  15517. onLoad(null);
  15518. }
  15519. return;
  15520. }
  15521. var texture = loadData.texture;
  15522. if (!createPolynomials) {
  15523. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15524. }
  15525. else if (loadData.info.sphericalPolynomial) {
  15526. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15527. }
  15528. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15529. if (_this._caps.textureLOD) {
  15530. // Do not add extra process if texture lod is supported.
  15531. if (onLoad) {
  15532. onLoad(texture);
  15533. }
  15534. return;
  15535. }
  15536. var mipSlices = 3;
  15537. var gl = _this._gl;
  15538. var width = loadData.width;
  15539. if (!width) {
  15540. return;
  15541. }
  15542. var textures = [];
  15543. for (var i = 0; i < mipSlices; i++) {
  15544. //compute LOD from even spacing in smoothness (matching shader calculation)
  15545. var smoothness = i / (mipSlices - 1);
  15546. var roughness = 1 - smoothness;
  15547. var minLODIndex = lodOffset; // roughness = 0
  15548. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15549. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15550. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15551. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15552. glTextureFromLod.type = texture.type;
  15553. glTextureFromLod.format = texture.format;
  15554. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15555. glTextureFromLod.height = glTextureFromLod.width;
  15556. glTextureFromLod.isCube = true;
  15557. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15558. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15559. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15560. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15561. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15562. if (loadData.isDDS) {
  15563. var info = loadData.info;
  15564. var data = loadData.data;
  15565. _this._unpackFlipY(info.isCompressed);
  15566. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15567. }
  15568. else {
  15569. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15570. }
  15571. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15572. // Wrap in a base texture for easy binding.
  15573. var lodTexture = new BABYLON.BaseTexture(scene);
  15574. lodTexture.isCube = true;
  15575. lodTexture._texture = glTextureFromLod;
  15576. glTextureFromLod.isReady = true;
  15577. textures.push(lodTexture);
  15578. }
  15579. texture._lodTextureHigh = textures[2];
  15580. texture._lodTextureMid = textures[1];
  15581. texture._lodTextureLow = textures[0];
  15582. if (onLoad) {
  15583. onLoad(texture);
  15584. }
  15585. };
  15586. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15587. };
  15588. /**
  15589. * Creates a cube texture
  15590. * @param rootUrl defines the url where the files to load is located
  15591. * @param scene defines the current scene
  15592. * @param files defines the list of files to load (1 per face)
  15593. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15594. * @param onLoad defines an optional callback raised when the texture is loaded
  15595. * @param onError defines an optional callback raised if there is an issue to load the texture
  15596. * @param format defines the format of the data
  15597. * @param forcedExtension defines the extension to use to pick the right loader
  15598. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15599. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15600. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15601. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15602. * @returns the cube texture as an InternalTexture
  15603. */
  15604. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15605. var _this = this;
  15606. if (onLoad === void 0) { onLoad = null; }
  15607. if (onError === void 0) { onError = null; }
  15608. if (forcedExtension === void 0) { forcedExtension = null; }
  15609. if (createPolynomials === void 0) { createPolynomials = false; }
  15610. if (lodScale === void 0) { lodScale = 0; }
  15611. if (lodOffset === void 0) { lodOffset = 0; }
  15612. if (fallback === void 0) { fallback = null; }
  15613. var gl = this._gl;
  15614. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15615. texture.isCube = true;
  15616. texture.url = rootUrl;
  15617. texture.generateMipMaps = !noMipmap;
  15618. texture._lodGenerationScale = lodScale;
  15619. texture._lodGenerationOffset = lodOffset;
  15620. if (!this._doNotHandleContextLost) {
  15621. texture._extension = forcedExtension;
  15622. texture._files = files;
  15623. }
  15624. var lastDot = rootUrl.lastIndexOf('.');
  15625. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15626. var loader = null;
  15627. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15628. var availableLoader = _a[_i];
  15629. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15630. loader = availableLoader;
  15631. break;
  15632. }
  15633. }
  15634. var onInternalError = function (request, exception) {
  15635. if (loader) {
  15636. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15637. if (fallbackUrl) {
  15638. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15639. }
  15640. }
  15641. if (onError && request) {
  15642. onError(request.status + " " + request.statusText, exception);
  15643. }
  15644. };
  15645. if (loader) {
  15646. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15647. var onloaddata = function (data) {
  15648. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15649. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15650. };
  15651. if (files && files.length === 6) {
  15652. if (loader.supportCascades) {
  15653. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15654. }
  15655. else if (onError) {
  15656. onError("Textures type does not support cascades.");
  15657. }
  15658. }
  15659. else {
  15660. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15661. }
  15662. }
  15663. else {
  15664. if (!files) {
  15665. throw new Error("Cannot load cubemap because files were not defined");
  15666. }
  15667. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15668. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15669. var height = width;
  15670. _this._prepareWorkingCanvas();
  15671. if (!_this._workingCanvas || !_this._workingContext) {
  15672. return;
  15673. }
  15674. _this._workingCanvas.width = width;
  15675. _this._workingCanvas.height = height;
  15676. var faces = [
  15677. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15678. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15679. ];
  15680. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15681. _this._unpackFlipY(false);
  15682. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15683. for (var index = 0; index < faces.length; index++) {
  15684. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15685. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15686. }
  15687. if (!noMipmap) {
  15688. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15689. }
  15690. _this._setCubeMapTextureParams(!noMipmap);
  15691. texture.width = width;
  15692. texture.height = height;
  15693. texture.isReady = true;
  15694. if (format) {
  15695. texture.format = format;
  15696. }
  15697. texture.onLoadedObservable.notifyObservers(texture);
  15698. texture.onLoadedObservable.clear();
  15699. if (onLoad) {
  15700. onLoad();
  15701. }
  15702. }, files, onError);
  15703. }
  15704. this._internalTexturesCache.push(texture);
  15705. return texture;
  15706. };
  15707. /**
  15708. * @hidden
  15709. */
  15710. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15711. var gl = this._gl;
  15712. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15713. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15714. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15715. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15716. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15717. // this.resetTextureCache();
  15718. };
  15719. /**
  15720. * Update a raw cube texture
  15721. * @param texture defines the texture to udpdate
  15722. * @param data defines the data to store
  15723. * @param format defines the data format
  15724. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15725. * @param invertY defines if data must be stored with Y axis inverted
  15726. * @param compression defines the compression used (null by default)
  15727. * @param level defines which level of the texture to update
  15728. */
  15729. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15730. if (compression === void 0) { compression = null; }
  15731. if (level === void 0) { level = 0; }
  15732. texture._bufferViewArray = data;
  15733. texture.format = format;
  15734. texture.type = type;
  15735. texture.invertY = invertY;
  15736. texture._compression = compression;
  15737. var gl = this._gl;
  15738. var textureType = this._getWebGLTextureType(type);
  15739. var internalFormat = this._getInternalFormat(format);
  15740. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15741. var needConversion = false;
  15742. if (internalFormat === gl.RGB) {
  15743. internalFormat = gl.RGBA;
  15744. needConversion = true;
  15745. }
  15746. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15747. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15748. if (texture.width % 4 !== 0) {
  15749. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15750. }
  15751. // Data are known to be in +X +Y +Z -X -Y -Z
  15752. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15753. var faceData = data[faceIndex];
  15754. if (compression) {
  15755. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15756. }
  15757. else {
  15758. if (needConversion) {
  15759. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15760. }
  15761. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15762. }
  15763. }
  15764. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15765. if (isPot && texture.generateMipMaps && level === 0) {
  15766. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15767. }
  15768. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15769. // this.resetTextureCache();
  15770. texture.isReady = true;
  15771. };
  15772. /**
  15773. * Creates a new raw cube texture
  15774. * @param data defines the array of data to use to create each face
  15775. * @param size defines the size of the textures
  15776. * @param format defines the format of the data
  15777. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15778. * @param generateMipMaps defines if the engine should generate the mip levels
  15779. * @param invertY defines if data must be stored with Y axis inverted
  15780. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15781. * @param compression defines the compression used (null by default)
  15782. * @returns the cube texture as an InternalTexture
  15783. */
  15784. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15785. if (compression === void 0) { compression = null; }
  15786. var gl = this._gl;
  15787. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15788. texture.isCube = true;
  15789. texture.format = format;
  15790. texture.type = type;
  15791. if (!this._doNotHandleContextLost) {
  15792. texture._bufferViewArray = data;
  15793. }
  15794. var textureType = this._getWebGLTextureType(type);
  15795. var internalFormat = this._getInternalFormat(format);
  15796. if (internalFormat === gl.RGB) {
  15797. internalFormat = gl.RGBA;
  15798. }
  15799. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15800. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15801. generateMipMaps = false;
  15802. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15803. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15804. }
  15805. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15806. generateMipMaps = false;
  15807. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15808. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15809. }
  15810. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15811. generateMipMaps = false;
  15812. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15813. }
  15814. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15815. generateMipMaps = false;
  15816. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15817. }
  15818. var width = size;
  15819. var height = width;
  15820. texture.width = width;
  15821. texture.height = height;
  15822. // Double check on POT to generate Mips.
  15823. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15824. if (!isPot) {
  15825. generateMipMaps = false;
  15826. }
  15827. // Upload data if needed. The texture won't be ready until then.
  15828. if (data) {
  15829. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15830. }
  15831. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15832. // Filters
  15833. if (data && generateMipMaps) {
  15834. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15835. }
  15836. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15837. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15838. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15839. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15840. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15841. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15842. texture.generateMipMaps = generateMipMaps;
  15843. return texture;
  15844. };
  15845. /**
  15846. * Creates a new raw cube texture from a specified url
  15847. * @param url defines the url where the data is located
  15848. * @param scene defines the current scene
  15849. * @param size defines the size of the textures
  15850. * @param format defines the format of the data
  15851. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15852. * @param noMipmap defines if the engine should avoid generating the mip levels
  15853. * @param callback defines a callback used to extract texture data from loaded data
  15854. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15855. * @param onLoad defines a callback called when texture is loaded
  15856. * @param onError defines a callback called if there is an error
  15857. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15858. * @param invertY defines if data must be stored with Y axis inverted
  15859. * @returns the cube texture as an InternalTexture
  15860. */
  15861. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15862. var _this = this;
  15863. if (onLoad === void 0) { onLoad = null; }
  15864. if (onError === void 0) { onError = null; }
  15865. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15866. if (invertY === void 0) { invertY = false; }
  15867. var gl = this._gl;
  15868. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15869. scene._addPendingData(texture);
  15870. texture.url = url;
  15871. this._internalTexturesCache.push(texture);
  15872. var onerror = function (request, exception) {
  15873. scene._removePendingData(texture);
  15874. if (onError && request) {
  15875. onError(request.status + " " + request.statusText, exception);
  15876. }
  15877. };
  15878. var internalCallback = function (data) {
  15879. var width = texture.width;
  15880. var faceDataArrays = callback(data);
  15881. if (!faceDataArrays) {
  15882. return;
  15883. }
  15884. if (mipmapGenerator) {
  15885. var textureType = _this._getWebGLTextureType(type);
  15886. var internalFormat = _this._getInternalFormat(format);
  15887. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15888. var needConversion = false;
  15889. if (internalFormat === gl.RGB) {
  15890. internalFormat = gl.RGBA;
  15891. needConversion = true;
  15892. }
  15893. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15894. _this._unpackFlipY(false);
  15895. var mipData = mipmapGenerator(faceDataArrays);
  15896. for (var level = 0; level < mipData.length; level++) {
  15897. var mipSize = width >> level;
  15898. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15899. var mipFaceData = mipData[level][faceIndex];
  15900. if (needConversion) {
  15901. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15902. }
  15903. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15904. }
  15905. }
  15906. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15907. }
  15908. else {
  15909. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15910. }
  15911. texture.isReady = true;
  15912. // this.resetTextureCache();
  15913. scene._removePendingData(texture);
  15914. if (onLoad) {
  15915. onLoad();
  15916. }
  15917. };
  15918. this._loadFile(url, function (data) {
  15919. internalCallback(data);
  15920. }, undefined, scene.database, true, onerror);
  15921. return texture;
  15922. };
  15923. ;
  15924. /**
  15925. * Update a raw 3D texture
  15926. * @param texture defines the texture to update
  15927. * @param data defines the data to store
  15928. * @param format defines the data format
  15929. * @param invertY defines if data must be stored with Y axis inverted
  15930. * @param compression defines the used compression (can be null)
  15931. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15932. */
  15933. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15934. if (compression === void 0) { compression = null; }
  15935. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15936. var internalType = this._getWebGLTextureType(textureType);
  15937. var internalFormat = this._getInternalFormat(format);
  15938. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15939. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15940. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15941. if (!this._doNotHandleContextLost) {
  15942. texture._bufferView = data;
  15943. texture.format = format;
  15944. texture.invertY = invertY;
  15945. texture._compression = compression;
  15946. }
  15947. if (texture.width % 4 !== 0) {
  15948. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15949. }
  15950. if (compression && data) {
  15951. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15952. }
  15953. else {
  15954. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15955. }
  15956. if (texture.generateMipMaps) {
  15957. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15958. }
  15959. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15960. // this.resetTextureCache();
  15961. texture.isReady = true;
  15962. };
  15963. /**
  15964. * Creates a new raw 3D texture
  15965. * @param data defines the data used to create the texture
  15966. * @param width defines the width of the texture
  15967. * @param height defines the height of the texture
  15968. * @param depth defines the depth of the texture
  15969. * @param format defines the format of the texture
  15970. * @param generateMipMaps defines if the engine must generate mip levels
  15971. * @param invertY defines if data must be stored with Y axis inverted
  15972. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15973. * @param compression defines the compressed used (can be null)
  15974. * @param textureType defines the compressed used (can be null)
  15975. * @returns a new raw 3D texture (stored in an InternalTexture)
  15976. */
  15977. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15978. if (compression === void 0) { compression = null; }
  15979. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15980. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15981. texture.baseWidth = width;
  15982. texture.baseHeight = height;
  15983. texture.baseDepth = depth;
  15984. texture.width = width;
  15985. texture.height = height;
  15986. texture.depth = depth;
  15987. texture.format = format;
  15988. texture.type = textureType;
  15989. texture.generateMipMaps = generateMipMaps;
  15990. texture.samplingMode = samplingMode;
  15991. texture.is3D = true;
  15992. if (!this._doNotHandleContextLost) {
  15993. texture._bufferView = data;
  15994. }
  15995. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15996. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15997. // Filters
  15998. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15999. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16000. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16001. if (generateMipMaps) {
  16002. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16003. }
  16004. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16005. this._internalTexturesCache.push(texture);
  16006. return texture;
  16007. };
  16008. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16009. var gl = this._gl;
  16010. if (!gl) {
  16011. return;
  16012. }
  16013. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16014. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16016. if (!noMipmap && !isCompressed) {
  16017. gl.generateMipmap(gl.TEXTURE_2D);
  16018. }
  16019. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16020. // this.resetTextureCache();
  16021. if (scene) {
  16022. scene._removePendingData(texture);
  16023. }
  16024. texture.onLoadedObservable.notifyObservers(texture);
  16025. texture.onLoadedObservable.clear();
  16026. };
  16027. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16028. var _this = this;
  16029. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16030. var maxTextureSize = this.getCaps().maxTextureSize;
  16031. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16032. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16033. var gl = this._gl;
  16034. if (!gl) {
  16035. return;
  16036. }
  16037. if (!texture._webGLTexture) {
  16038. // this.resetTextureCache();
  16039. if (scene) {
  16040. scene._removePendingData(texture);
  16041. }
  16042. return;
  16043. }
  16044. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16045. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16046. texture.baseWidth = width;
  16047. texture.baseHeight = height;
  16048. texture.width = potWidth;
  16049. texture.height = potHeight;
  16050. texture.isReady = true;
  16051. if (processFunction(potWidth, potHeight, function () {
  16052. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16053. })) {
  16054. // Returning as texture needs extra async steps
  16055. return;
  16056. }
  16057. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16058. };
  16059. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16060. // Create new RGBA data container.
  16061. var rgbaData;
  16062. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16063. rgbaData = new Float32Array(width * height * 4);
  16064. }
  16065. else {
  16066. rgbaData = new Uint32Array(width * height * 4);
  16067. }
  16068. // Convert each pixel.
  16069. for (var x = 0; x < width; x++) {
  16070. for (var y = 0; y < height; y++) {
  16071. var index = (y * width + x) * 3;
  16072. var newIndex = (y * width + x) * 4;
  16073. // Map Old Value to new value.
  16074. rgbaData[newIndex + 0] = rgbData[index + 0];
  16075. rgbaData[newIndex + 1] = rgbData[index + 1];
  16076. rgbaData[newIndex + 2] = rgbData[index + 2];
  16077. // Add fully opaque alpha channel.
  16078. rgbaData[newIndex + 3] = 1;
  16079. }
  16080. }
  16081. return rgbaData;
  16082. };
  16083. /** @hidden */
  16084. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16085. var gl = this._gl;
  16086. if (texture._framebuffer) {
  16087. gl.deleteFramebuffer(texture._framebuffer);
  16088. texture._framebuffer = null;
  16089. }
  16090. if (texture._depthStencilBuffer) {
  16091. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16092. texture._depthStencilBuffer = null;
  16093. }
  16094. if (texture._MSAAFramebuffer) {
  16095. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16096. texture._MSAAFramebuffer = null;
  16097. }
  16098. if (texture._MSAARenderBuffer) {
  16099. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16100. texture._MSAARenderBuffer = null;
  16101. }
  16102. };
  16103. /** @hidden */
  16104. Engine.prototype._releaseTexture = function (texture) {
  16105. var gl = this._gl;
  16106. this._releaseFramebufferObjects(texture);
  16107. gl.deleteTexture(texture._webGLTexture);
  16108. // Unbind channels
  16109. this.unbindAllTextures();
  16110. var index = this._internalTexturesCache.indexOf(texture);
  16111. if (index !== -1) {
  16112. this._internalTexturesCache.splice(index, 1);
  16113. }
  16114. // Integrated fixed lod samplers.
  16115. if (texture._lodTextureHigh) {
  16116. texture._lodTextureHigh.dispose();
  16117. }
  16118. if (texture._lodTextureMid) {
  16119. texture._lodTextureMid.dispose();
  16120. }
  16121. if (texture._lodTextureLow) {
  16122. texture._lodTextureLow.dispose();
  16123. }
  16124. // Set output texture of post process to null if the texture has been released/disposed
  16125. this.scenes.forEach(function (scene) {
  16126. scene.postProcesses.forEach(function (postProcess) {
  16127. if (postProcess._outputTexture == texture) {
  16128. postProcess._outputTexture = null;
  16129. }
  16130. });
  16131. scene.cameras.forEach(function (camera) {
  16132. camera._postProcesses.forEach(function (postProcess) {
  16133. if (postProcess) {
  16134. if (postProcess._outputTexture == texture) {
  16135. postProcess._outputTexture = null;
  16136. }
  16137. }
  16138. });
  16139. });
  16140. });
  16141. };
  16142. Engine.prototype.setProgram = function (program) {
  16143. if (this._currentProgram !== program) {
  16144. this._gl.useProgram(program);
  16145. this._currentProgram = program;
  16146. }
  16147. };
  16148. /**
  16149. * Binds an effect to the webGL context
  16150. * @param effect defines the effect to bind
  16151. */
  16152. Engine.prototype.bindSamplers = function (effect) {
  16153. this.setProgram(effect.getProgram());
  16154. var samplers = effect.getSamplers();
  16155. for (var index = 0; index < samplers.length; index++) {
  16156. var uniform = effect.getUniform(samplers[index]);
  16157. if (uniform) {
  16158. this._boundUniforms[index] = uniform;
  16159. }
  16160. }
  16161. this._currentEffect = null;
  16162. };
  16163. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16164. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16165. return;
  16166. }
  16167. // Remove
  16168. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16169. // Bind last to it
  16170. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16171. // Bind to dummy
  16172. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16173. };
  16174. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16175. if (!internalTexture) {
  16176. return -1;
  16177. }
  16178. internalTexture._initialSlot = channel;
  16179. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16180. if (channel !== internalTexture._designatedSlot) {
  16181. this._textureCollisions.addCount(1, false);
  16182. }
  16183. }
  16184. else {
  16185. if (channel !== internalTexture._designatedSlot) {
  16186. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16187. return internalTexture._designatedSlot;
  16188. }
  16189. else {
  16190. // No slot for this texture, let's pick a new one (if we find a free slot)
  16191. if (this._nextFreeTextureSlots.length) {
  16192. return this._nextFreeTextureSlots[0];
  16193. }
  16194. // We need to recycle the oldest bound texture, sorry.
  16195. this._textureCollisions.addCount(1, false);
  16196. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16197. }
  16198. }
  16199. }
  16200. return channel;
  16201. };
  16202. Engine.prototype._linkTrackers = function (previous, next) {
  16203. previous.next = next;
  16204. next.previous = previous;
  16205. };
  16206. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16207. var currentSlot = internalTexture._designatedSlot;
  16208. if (currentSlot === -1) {
  16209. return -1;
  16210. }
  16211. internalTexture._designatedSlot = -1;
  16212. if (this.disableTextureBindingOptimization) {
  16213. return -1;
  16214. }
  16215. // Remove from bound list
  16216. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16217. // Free the slot
  16218. this._boundTexturesCache[currentSlot] = null;
  16219. this._nextFreeTextureSlots.push(currentSlot);
  16220. return currentSlot;
  16221. };
  16222. Engine.prototype._activateCurrentTexture = function () {
  16223. if (this._currentTextureChannel !== this._activeChannel) {
  16224. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16225. this._currentTextureChannel = this._activeChannel;
  16226. }
  16227. };
  16228. /** @hidden */
  16229. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16230. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16231. if (force === void 0) { force = false; }
  16232. var wasPreviouslyBound = false;
  16233. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16234. this._activeChannel = texture._designatedSlot;
  16235. }
  16236. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16237. var isTextureForRendering = texture && texture._initialSlot > -1;
  16238. if (currentTextureBound !== texture || force) {
  16239. if (currentTextureBound) {
  16240. this._removeDesignatedSlot(currentTextureBound);
  16241. }
  16242. this._activateCurrentTexture();
  16243. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16244. this._boundTexturesCache[this._activeChannel] = texture;
  16245. if (texture) {
  16246. if (!this.disableTextureBindingOptimization) {
  16247. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16248. if (slotIndex > -1) {
  16249. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16250. }
  16251. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16252. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16253. }
  16254. texture._designatedSlot = this._activeChannel;
  16255. }
  16256. }
  16257. else if (forTextureDataUpdate) {
  16258. wasPreviouslyBound = true;
  16259. this._activateCurrentTexture();
  16260. }
  16261. if (isTextureForRendering && !forTextureDataUpdate) {
  16262. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16263. }
  16264. return wasPreviouslyBound;
  16265. };
  16266. /** @hidden */
  16267. Engine.prototype._bindTexture = function (channel, texture) {
  16268. if (channel < 0) {
  16269. return;
  16270. }
  16271. if (texture) {
  16272. channel = this._getCorrectTextureChannel(channel, texture);
  16273. }
  16274. this._activeChannel = channel;
  16275. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16276. };
  16277. /**
  16278. * Sets a texture to the webGL context from a postprocess
  16279. * @param channel defines the channel to use
  16280. * @param postProcess defines the source postprocess
  16281. */
  16282. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16283. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16284. };
  16285. /**
  16286. * Binds the output of the passed in post process to the texture channel specified
  16287. * @param channel The channel the texture should be bound to
  16288. * @param postProcess The post process which's output should be bound
  16289. */
  16290. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16291. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16292. };
  16293. /**
  16294. * Unbind all textures from the webGL context
  16295. */
  16296. Engine.prototype.unbindAllTextures = function () {
  16297. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16298. this._activeChannel = channel;
  16299. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16300. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16301. if (this.webGLVersion > 1) {
  16302. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16303. }
  16304. }
  16305. };
  16306. /**
  16307. * Sets a texture to the according uniform.
  16308. * @param channel The texture channel
  16309. * @param uniform The uniform to set
  16310. * @param texture The texture to apply
  16311. */
  16312. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16313. if (channel < 0) {
  16314. return;
  16315. }
  16316. if (uniform) {
  16317. this._boundUniforms[channel] = uniform;
  16318. }
  16319. this._setTexture(channel, texture);
  16320. };
  16321. /**
  16322. * Sets a depth stencil texture from a render target to the according uniform.
  16323. * @param channel The texture channel
  16324. * @param uniform The uniform to set
  16325. * @param texture The render target texture containing the depth stencil texture to apply
  16326. */
  16327. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16328. if (channel < 0) {
  16329. return;
  16330. }
  16331. if (uniform) {
  16332. this._boundUniforms[channel] = uniform;
  16333. }
  16334. if (!texture || !texture.depthStencilTexture) {
  16335. this._setTexture(channel, null);
  16336. }
  16337. else {
  16338. this._setTexture(channel, texture, false, true);
  16339. }
  16340. };
  16341. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16342. var uniform = this._boundUniforms[sourceSlot];
  16343. if (uniform._currentState === destination) {
  16344. return;
  16345. }
  16346. this._gl.uniform1i(uniform, destination);
  16347. uniform._currentState = destination;
  16348. };
  16349. Engine.prototype._getTextureWrapMode = function (mode) {
  16350. switch (mode) {
  16351. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16352. return this._gl.REPEAT;
  16353. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16354. return this._gl.CLAMP_TO_EDGE;
  16355. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16356. return this._gl.MIRRORED_REPEAT;
  16357. }
  16358. return this._gl.REPEAT;
  16359. };
  16360. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16361. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16362. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16363. // Not ready?
  16364. if (!texture) {
  16365. if (this._boundTexturesCache[channel] != null) {
  16366. this._activeChannel = channel;
  16367. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16368. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16369. if (this.webGLVersion > 1) {
  16370. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16371. }
  16372. }
  16373. return false;
  16374. }
  16375. // Video
  16376. if (texture.video) {
  16377. this._activeChannel = channel;
  16378. texture.update();
  16379. }
  16380. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16381. texture.delayLoad();
  16382. return false;
  16383. }
  16384. var internalTexture;
  16385. if (depthStencilTexture) {
  16386. internalTexture = texture.depthStencilTexture;
  16387. }
  16388. else if (texture.isReady()) {
  16389. internalTexture = texture.getInternalTexture();
  16390. }
  16391. else if (texture.isCube) {
  16392. internalTexture = this.emptyCubeTexture;
  16393. }
  16394. else if (texture.is3D) {
  16395. internalTexture = this.emptyTexture3D;
  16396. }
  16397. else {
  16398. internalTexture = this.emptyTexture;
  16399. }
  16400. if (!isPartOfTextureArray) {
  16401. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16402. }
  16403. var needToBind = true;
  16404. if (this._boundTexturesCache[channel] === internalTexture) {
  16405. this._moveBoundTextureOnTop(internalTexture);
  16406. if (!isPartOfTextureArray) {
  16407. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16408. }
  16409. needToBind = false;
  16410. }
  16411. this._activeChannel = channel;
  16412. if (internalTexture && internalTexture.is3D) {
  16413. if (needToBind) {
  16414. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16415. }
  16416. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16417. internalTexture._cachedWrapU = texture.wrapU;
  16418. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16419. }
  16420. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16421. internalTexture._cachedWrapV = texture.wrapV;
  16422. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16423. }
  16424. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16425. internalTexture._cachedWrapR = texture.wrapR;
  16426. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16427. }
  16428. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16429. }
  16430. else if (internalTexture && internalTexture.isCube) {
  16431. if (needToBind) {
  16432. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16433. }
  16434. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16435. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16436. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16437. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16438. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16439. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16440. }
  16441. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16442. }
  16443. else {
  16444. if (needToBind) {
  16445. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16446. }
  16447. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16448. internalTexture._cachedWrapU = texture.wrapU;
  16449. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16450. }
  16451. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16452. internalTexture._cachedWrapV = texture.wrapV;
  16453. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16454. }
  16455. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16456. }
  16457. return true;
  16458. };
  16459. /**
  16460. * Sets an array of texture to the webGL context
  16461. * @param channel defines the channel where the texture array must be set
  16462. * @param uniform defines the associated uniform location
  16463. * @param textures defines the array of textures to bind
  16464. */
  16465. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16466. if (channel < 0 || !uniform) {
  16467. return;
  16468. }
  16469. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16470. this._textureUnits = new Int32Array(textures.length);
  16471. }
  16472. for (var i = 0; i < textures.length; i++) {
  16473. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16474. }
  16475. this._gl.uniform1iv(uniform, this._textureUnits);
  16476. for (var index = 0; index < textures.length; index++) {
  16477. this._setTexture(this._textureUnits[index], textures[index], true);
  16478. }
  16479. };
  16480. /** @hidden */
  16481. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16482. var internalTexture = texture.getInternalTexture();
  16483. if (!internalTexture) {
  16484. return;
  16485. }
  16486. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16487. var value = texture.anisotropicFilteringLevel;
  16488. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16489. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16490. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16491. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16492. }
  16493. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16494. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16495. internalTexture._cachedAnisotropicFilteringLevel = value;
  16496. }
  16497. };
  16498. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16499. this._bindTextureDirectly(target, texture, true, true);
  16500. this._gl.texParameterf(target, parameter, value);
  16501. };
  16502. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16503. if (texture) {
  16504. this._bindTextureDirectly(target, texture, true, true);
  16505. }
  16506. this._gl.texParameteri(target, parameter, value);
  16507. };
  16508. /**
  16509. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16510. * @param x defines the x coordinate of the rectangle where pixels must be read
  16511. * @param y defines the y coordinate of the rectangle where pixels must be read
  16512. * @param width defines the width of the rectangle where pixels must be read
  16513. * @param height defines the height of the rectangle where pixels must be read
  16514. * @returns a Uint8Array containing RGBA colors
  16515. */
  16516. Engine.prototype.readPixels = function (x, y, width, height) {
  16517. var data = new Uint8Array(height * width * 4);
  16518. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16519. return data;
  16520. };
  16521. /**
  16522. * Add an externaly attached data from its key.
  16523. * This method call will fail and return false, if such key already exists.
  16524. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16525. * @param key the unique key that identifies the data
  16526. * @param data the data object to associate to the key for this Engine instance
  16527. * @return true if no such key were already present and the data was added successfully, false otherwise
  16528. */
  16529. Engine.prototype.addExternalData = function (key, data) {
  16530. if (!this._externalData) {
  16531. this._externalData = new BABYLON.StringDictionary();
  16532. }
  16533. return this._externalData.add(key, data);
  16534. };
  16535. /**
  16536. * Get an externaly attached data from its key
  16537. * @param key the unique key that identifies the data
  16538. * @return the associated data, if present (can be null), or undefined if not present
  16539. */
  16540. Engine.prototype.getExternalData = function (key) {
  16541. if (!this._externalData) {
  16542. this._externalData = new BABYLON.StringDictionary();
  16543. }
  16544. return this._externalData.get(key);
  16545. };
  16546. /**
  16547. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16548. * @param key the unique key that identifies the data
  16549. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16550. * @return the associated data, can be null if the factory returned null.
  16551. */
  16552. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16553. if (!this._externalData) {
  16554. this._externalData = new BABYLON.StringDictionary();
  16555. }
  16556. return this._externalData.getOrAddWithFactory(key, factory);
  16557. };
  16558. /**
  16559. * Remove an externaly attached data from the Engine instance
  16560. * @param key the unique key that identifies the data
  16561. * @return true if the data was successfully removed, false if it doesn't exist
  16562. */
  16563. Engine.prototype.removeExternalData = function (key) {
  16564. if (!this._externalData) {
  16565. this._externalData = new BABYLON.StringDictionary();
  16566. }
  16567. return this._externalData.remove(key);
  16568. };
  16569. /**
  16570. * Unbind all vertex attributes from the webGL context
  16571. */
  16572. Engine.prototype.unbindAllAttributes = function () {
  16573. if (this._mustWipeVertexAttributes) {
  16574. this._mustWipeVertexAttributes = false;
  16575. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16576. this._gl.disableVertexAttribArray(i);
  16577. this._vertexAttribArraysEnabled[i] = false;
  16578. this._currentBufferPointers[i].active = false;
  16579. }
  16580. return;
  16581. }
  16582. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16583. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16584. continue;
  16585. }
  16586. this._gl.disableVertexAttribArray(i);
  16587. this._vertexAttribArraysEnabled[i] = false;
  16588. this._currentBufferPointers[i].active = false;
  16589. }
  16590. };
  16591. /**
  16592. * 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
  16593. */
  16594. Engine.prototype.releaseEffects = function () {
  16595. for (var name in this._compiledEffects) {
  16596. this._deleteProgram(this._compiledEffects[name]._program);
  16597. }
  16598. this._compiledEffects = {};
  16599. };
  16600. /**
  16601. * Dispose and release all associated resources
  16602. */
  16603. Engine.prototype.dispose = function () {
  16604. this.hideLoadingUI();
  16605. this.stopRenderLoop();
  16606. // Release postProcesses
  16607. while (this.postProcesses.length) {
  16608. this.postProcesses[0].dispose();
  16609. }
  16610. // Empty texture
  16611. if (this._emptyTexture) {
  16612. this._releaseTexture(this._emptyTexture);
  16613. this._emptyTexture = null;
  16614. }
  16615. if (this._emptyCubeTexture) {
  16616. this._releaseTexture(this._emptyCubeTexture);
  16617. this._emptyCubeTexture = null;
  16618. }
  16619. // Rescale PP
  16620. if (this._rescalePostProcess) {
  16621. this._rescalePostProcess.dispose();
  16622. }
  16623. // Release scenes
  16624. while (this.scenes.length) {
  16625. this.scenes[0].dispose();
  16626. }
  16627. // Release audio engine
  16628. if (Engine.audioEngine) {
  16629. Engine.audioEngine.dispose();
  16630. }
  16631. // Release effects
  16632. this.releaseEffects();
  16633. // Unbind
  16634. this.unbindAllAttributes();
  16635. this._boundUniforms = [];
  16636. if (this._dummyFramebuffer) {
  16637. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16638. }
  16639. //WebVR
  16640. this.disableVR();
  16641. // Events
  16642. if (BABYLON.Tools.IsWindowObjectExist()) {
  16643. window.removeEventListener("blur", this._onBlur);
  16644. window.removeEventListener("focus", this._onFocus);
  16645. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16646. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16647. if (this._renderingCanvas) {
  16648. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16649. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16650. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16651. if (!this._doNotHandleContextLost) {
  16652. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16653. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16654. }
  16655. }
  16656. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16657. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16658. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16659. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16660. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16661. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16662. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16663. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16664. if (this._onVrDisplayConnect) {
  16665. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16666. if (this._onVrDisplayDisconnect) {
  16667. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16668. }
  16669. if (this._onVrDisplayPresentChange) {
  16670. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16671. }
  16672. this._onVrDisplayConnect = null;
  16673. this._onVrDisplayDisconnect = null;
  16674. }
  16675. }
  16676. // Remove from Instances
  16677. var index = Engine.Instances.indexOf(this);
  16678. if (index >= 0) {
  16679. Engine.Instances.splice(index, 1);
  16680. }
  16681. this._workingCanvas = null;
  16682. this._workingContext = null;
  16683. this._currentBufferPointers = [];
  16684. this._renderingCanvas = null;
  16685. this._currentProgram = null;
  16686. this._bindedRenderFunction = null;
  16687. this.onResizeObservable.clear();
  16688. this.onCanvasBlurObservable.clear();
  16689. this.onCanvasFocusObservable.clear();
  16690. this.onCanvasPointerOutObservable.clear();
  16691. this.onBeginFrameObservable.clear();
  16692. this.onEndFrameObservable.clear();
  16693. BABYLON.Effect.ResetCache();
  16694. // Abort active requests
  16695. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16696. var request = _a[_i];
  16697. request.abort();
  16698. }
  16699. };
  16700. // Loading screen
  16701. /**
  16702. * Display the loading screen
  16703. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16704. */
  16705. Engine.prototype.displayLoadingUI = function () {
  16706. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16707. return;
  16708. }
  16709. var loadingScreen = this.loadingScreen;
  16710. if (loadingScreen) {
  16711. loadingScreen.displayLoadingUI();
  16712. }
  16713. };
  16714. /**
  16715. * Hide the loading screen
  16716. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16717. */
  16718. Engine.prototype.hideLoadingUI = function () {
  16719. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16720. return;
  16721. }
  16722. var loadingScreen = this.loadingScreen;
  16723. if (loadingScreen) {
  16724. loadingScreen.hideLoadingUI();
  16725. }
  16726. };
  16727. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16728. /**
  16729. * Gets the current loading screen object
  16730. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16731. */
  16732. get: function () {
  16733. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16734. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16735. return this._loadingScreen;
  16736. },
  16737. /**
  16738. * Sets the current loading screen object
  16739. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16740. */
  16741. set: function (loadingScreen) {
  16742. this._loadingScreen = loadingScreen;
  16743. },
  16744. enumerable: true,
  16745. configurable: true
  16746. });
  16747. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16748. /**
  16749. * Sets the current loading screen text
  16750. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16751. */
  16752. set: function (text) {
  16753. this.loadingScreen.loadingUIText = text;
  16754. },
  16755. enumerable: true,
  16756. configurable: true
  16757. });
  16758. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16759. /**
  16760. * Sets the current loading screen background color
  16761. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16762. */
  16763. set: function (color) {
  16764. this.loadingScreen.loadingUIBackgroundColor = color;
  16765. },
  16766. enumerable: true,
  16767. configurable: true
  16768. });
  16769. /**
  16770. * Attach a new callback raised when context lost event is fired
  16771. * @param callback defines the callback to call
  16772. */
  16773. Engine.prototype.attachContextLostEvent = function (callback) {
  16774. if (this._renderingCanvas) {
  16775. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16776. }
  16777. };
  16778. /**
  16779. * Attach a new callback raised when context restored event is fired
  16780. * @param callback defines the callback to call
  16781. */
  16782. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16783. if (this._renderingCanvas) {
  16784. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16785. }
  16786. };
  16787. /**
  16788. * Gets the source code of the vertex shader associated with a specific webGL program
  16789. * @param program defines the program to use
  16790. * @returns a string containing the source code of the vertex shader associated with the program
  16791. */
  16792. Engine.prototype.getVertexShaderSource = function (program) {
  16793. var shaders = this._gl.getAttachedShaders(program);
  16794. if (!shaders) {
  16795. return null;
  16796. }
  16797. return this._gl.getShaderSource(shaders[0]);
  16798. };
  16799. /**
  16800. * Gets the source code of the fragment shader associated with a specific webGL program
  16801. * @param program defines the program to use
  16802. * @returns a string containing the source code of the fragment shader associated with the program
  16803. */
  16804. Engine.prototype.getFragmentShaderSource = function (program) {
  16805. var shaders = this._gl.getAttachedShaders(program);
  16806. if (!shaders) {
  16807. return null;
  16808. }
  16809. return this._gl.getShaderSource(shaders[1]);
  16810. };
  16811. /**
  16812. * Get the current error code of the webGL context
  16813. * @returns the error code
  16814. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16815. */
  16816. Engine.prototype.getError = function () {
  16817. return this._gl.getError();
  16818. };
  16819. // FPS
  16820. /**
  16821. * Gets the current framerate
  16822. * @returns a number representing the framerate
  16823. */
  16824. Engine.prototype.getFps = function () {
  16825. return this._fps;
  16826. };
  16827. /**
  16828. * Gets the time spent between current and previous frame
  16829. * @returns a number representing the delta time in ms
  16830. */
  16831. Engine.prototype.getDeltaTime = function () {
  16832. return this._deltaTime;
  16833. };
  16834. Engine.prototype._measureFps = function () {
  16835. this._performanceMonitor.sampleFrame();
  16836. this._fps = this._performanceMonitor.averageFPS;
  16837. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16838. };
  16839. /** @hidden */
  16840. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16841. if (faceIndex === void 0) { faceIndex = -1; }
  16842. if (level === void 0) { level = 0; }
  16843. var gl = this._gl;
  16844. if (!this._dummyFramebuffer) {
  16845. var dummy = gl.createFramebuffer();
  16846. if (!dummy) {
  16847. throw new Error("Unable to create dummy framebuffer");
  16848. }
  16849. this._dummyFramebuffer = dummy;
  16850. }
  16851. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16852. if (faceIndex > -1) {
  16853. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16854. }
  16855. else {
  16856. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16857. }
  16858. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16859. var buffer;
  16860. switch (readType) {
  16861. case gl.UNSIGNED_BYTE:
  16862. buffer = new Uint8Array(4 * width * height);
  16863. readType = gl.UNSIGNED_BYTE;
  16864. break;
  16865. default:
  16866. buffer = new Float32Array(4 * width * height);
  16867. readType = gl.FLOAT;
  16868. break;
  16869. }
  16870. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16871. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16872. return buffer;
  16873. };
  16874. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16875. if (this._webGLVersion > 1) {
  16876. return this._caps.colorBufferFloat;
  16877. }
  16878. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16879. };
  16880. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16881. if (this._webGLVersion > 1) {
  16882. return this._caps.colorBufferFloat;
  16883. }
  16884. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16885. };
  16886. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16887. Engine.prototype._canRenderToFramebuffer = function (type) {
  16888. var gl = this._gl;
  16889. //clear existing errors
  16890. while (gl.getError() !== gl.NO_ERROR) { }
  16891. var successful = true;
  16892. var texture = gl.createTexture();
  16893. gl.bindTexture(gl.TEXTURE_2D, texture);
  16894. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16896. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16897. var fb = gl.createFramebuffer();
  16898. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16899. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16900. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16901. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16902. successful = successful && (gl.getError() === gl.NO_ERROR);
  16903. //try render by clearing frame buffer's color buffer
  16904. if (successful) {
  16905. gl.clear(gl.COLOR_BUFFER_BIT);
  16906. successful = successful && (gl.getError() === gl.NO_ERROR);
  16907. }
  16908. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16909. if (successful) {
  16910. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16911. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16912. var readFormat = gl.RGBA;
  16913. var readType = gl.UNSIGNED_BYTE;
  16914. var buffer = new Uint8Array(4);
  16915. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16916. successful = successful && (gl.getError() === gl.NO_ERROR);
  16917. }
  16918. //clean up
  16919. gl.deleteTexture(texture);
  16920. gl.deleteFramebuffer(fb);
  16921. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16922. //clear accumulated errors
  16923. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16924. return successful;
  16925. };
  16926. /** @hidden */
  16927. Engine.prototype._getWebGLTextureType = function (type) {
  16928. if (this._webGLVersion === 1) {
  16929. switch (type) {
  16930. case Engine.TEXTURETYPE_FLOAT:
  16931. return this._gl.FLOAT;
  16932. case Engine.TEXTURETYPE_HALF_FLOAT:
  16933. return this._gl.HALF_FLOAT_OES;
  16934. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16935. return this._gl.UNSIGNED_BYTE;
  16936. }
  16937. return this._gl.UNSIGNED_BYTE;
  16938. }
  16939. switch (type) {
  16940. case Engine.TEXTURETYPE_BYTE:
  16941. return this._gl.BYTE;
  16942. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16943. return this._gl.UNSIGNED_BYTE;
  16944. case Engine.TEXTURETYPE_SHORT:
  16945. return this._gl.SHORT;
  16946. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  16947. return this._gl.UNSIGNED_SHORT;
  16948. case Engine.TEXTURETYPE_INT:
  16949. return this._gl.INT;
  16950. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  16951. return this._gl.UNSIGNED_INT;
  16952. case Engine.TEXTURETYPE_FLOAT:
  16953. return this._gl.FLOAT;
  16954. case Engine.TEXTURETYPE_HALF_FLOAT:
  16955. return this._gl.HALF_FLOAT;
  16956. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  16957. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  16958. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  16959. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  16960. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  16961. return this._gl.UNSIGNED_SHORT_5_6_5;
  16962. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  16963. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  16964. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  16965. return this._gl.UNSIGNED_INT_24_8;
  16966. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  16967. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  16968. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  16969. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  16970. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  16971. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  16972. }
  16973. return this._gl.UNSIGNED_BYTE;
  16974. };
  16975. ;
  16976. Engine.prototype._getInternalFormat = function (format) {
  16977. var internalFormat = this._gl.RGBA;
  16978. switch (format) {
  16979. case Engine.TEXTUREFORMAT_ALPHA:
  16980. internalFormat = this._gl.ALPHA;
  16981. break;
  16982. case Engine.TEXTUREFORMAT_LUMINANCE:
  16983. internalFormat = this._gl.LUMINANCE;
  16984. break;
  16985. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16986. internalFormat = this._gl.LUMINANCE_ALPHA;
  16987. break;
  16988. case Engine.TEXTUREFORMAT_RED:
  16989. internalFormat = this._gl.RED;
  16990. break;
  16991. case Engine.TEXTUREFORMAT_RG:
  16992. internalFormat = this._gl.RG;
  16993. break;
  16994. case Engine.TEXTUREFORMAT_RGB:
  16995. internalFormat = this._gl.RGB;
  16996. break;
  16997. case Engine.TEXTUREFORMAT_RGBA:
  16998. internalFormat = this._gl.RGBA;
  16999. break;
  17000. }
  17001. if (this._webGLVersion > 1) {
  17002. switch (format) {
  17003. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17004. internalFormat = this._gl.RED_INTEGER;
  17005. break;
  17006. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17007. internalFormat = this._gl.RG_INTEGER;
  17008. break;
  17009. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17010. internalFormat = this._gl.RGB_INTEGER;
  17011. break;
  17012. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17013. internalFormat = this._gl.RGBA_INTEGER;
  17014. break;
  17015. }
  17016. }
  17017. return internalFormat;
  17018. };
  17019. /** @hidden */
  17020. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17021. if (this._webGLVersion === 1) {
  17022. if (format !== undefined) {
  17023. switch (format) {
  17024. case Engine.TEXTUREFORMAT_ALPHA:
  17025. return this._gl.ALPHA;
  17026. case Engine.TEXTUREFORMAT_LUMINANCE:
  17027. return this._gl.LUMINANCE;
  17028. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17029. return this._gl.LUMINANCE_ALPHA;
  17030. }
  17031. }
  17032. return this._gl.RGBA;
  17033. }
  17034. switch (type) {
  17035. case Engine.TEXTURETYPE_BYTE:
  17036. switch (format) {
  17037. case Engine.TEXTUREFORMAT_RED:
  17038. return this._gl.R8_SNORM;
  17039. case Engine.TEXTUREFORMAT_RG:
  17040. return this._gl.RG8_SNORM;
  17041. case Engine.TEXTUREFORMAT_RGB:
  17042. return this._gl.RGB8_SNORM;
  17043. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17044. return this._gl.R8I;
  17045. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17046. return this._gl.RG8I;
  17047. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17048. return this._gl.RGB8I;
  17049. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17050. return this._gl.RGBA8I;
  17051. default:
  17052. return this._gl.RGBA8_SNORM;
  17053. }
  17054. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17055. switch (format) {
  17056. case Engine.TEXTUREFORMAT_RED:
  17057. return this._gl.R8;
  17058. case Engine.TEXTUREFORMAT_RG:
  17059. return this._gl.RG8;
  17060. case Engine.TEXTUREFORMAT_RGB:
  17061. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17062. case Engine.TEXTUREFORMAT_RGBA:
  17063. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17064. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17065. return this._gl.R8UI;
  17066. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17067. return this._gl.RG8UI;
  17068. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17069. return this._gl.RGB8UI;
  17070. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17071. return this._gl.RGBA8UI;
  17072. default:
  17073. return this._gl.RGBA8;
  17074. }
  17075. case Engine.TEXTURETYPE_SHORT:
  17076. switch (format) {
  17077. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17078. return this._gl.R16I;
  17079. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17080. return this._gl.RG16I;
  17081. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17082. return this._gl.RGB16I;
  17083. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17084. return this._gl.RGBA16I;
  17085. default:
  17086. return this._gl.RGBA16I;
  17087. }
  17088. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17089. switch (format) {
  17090. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17091. return this._gl.R16UI;
  17092. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17093. return this._gl.RG16UI;
  17094. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17095. return this._gl.RGB16UI;
  17096. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17097. return this._gl.RGBA16UI;
  17098. default:
  17099. return this._gl.RGBA16UI;
  17100. }
  17101. case Engine.TEXTURETYPE_INT:
  17102. switch (format) {
  17103. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17104. return this._gl.R32I;
  17105. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17106. return this._gl.RG32I;
  17107. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17108. return this._gl.RGB32I;
  17109. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17110. return this._gl.RGBA32I;
  17111. default:
  17112. return this._gl.RGBA32I;
  17113. }
  17114. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17115. switch (format) {
  17116. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17117. return this._gl.R32UI;
  17118. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17119. return this._gl.RG32UI;
  17120. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17121. return this._gl.RGB32UI;
  17122. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17123. return this._gl.RGBA32UI;
  17124. default:
  17125. return this._gl.RGBA32UI;
  17126. }
  17127. case Engine.TEXTURETYPE_FLOAT:
  17128. switch (format) {
  17129. case Engine.TEXTUREFORMAT_RED:
  17130. return this._gl.R32F; // By default. Other possibility is R16F.
  17131. case Engine.TEXTUREFORMAT_RG:
  17132. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17133. case Engine.TEXTUREFORMAT_RGB:
  17134. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17135. case Engine.TEXTUREFORMAT_RGBA:
  17136. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17137. default:
  17138. return this._gl.RGBA32F;
  17139. }
  17140. case Engine.TEXTURETYPE_HALF_FLOAT:
  17141. switch (format) {
  17142. case Engine.TEXTUREFORMAT_RED:
  17143. return this._gl.R16F;
  17144. case Engine.TEXTUREFORMAT_RG:
  17145. return this._gl.RG16F;
  17146. case Engine.TEXTUREFORMAT_RGB:
  17147. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17148. case Engine.TEXTUREFORMAT_RGBA:
  17149. return this._gl.RGBA16F;
  17150. default:
  17151. return this._gl.RGBA16F;
  17152. }
  17153. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17154. return this._gl.RGB565;
  17155. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17156. return this._gl.R11F_G11F_B10F;
  17157. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17158. return this._gl.RGB9_E5;
  17159. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17160. return this._gl.RGBA4;
  17161. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17162. return this._gl.RGB5_A1;
  17163. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17164. switch (format) {
  17165. case Engine.TEXTUREFORMAT_RGBA:
  17166. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17167. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17168. return this._gl.RGB10_A2UI;
  17169. default:
  17170. return this._gl.RGB10_A2;
  17171. }
  17172. }
  17173. return this._gl.RGBA8;
  17174. };
  17175. ;
  17176. /** @hidden */
  17177. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17178. if (type === Engine.TEXTURETYPE_FLOAT) {
  17179. return this._gl.RGBA32F;
  17180. }
  17181. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17182. return this._gl.RGBA16F;
  17183. }
  17184. return this._gl.RGBA8;
  17185. };
  17186. ;
  17187. /** @hidden */
  17188. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17189. var _this = this;
  17190. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17191. this._activeRequests.push(request);
  17192. request.onCompleteObservable.add(function (request) {
  17193. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17194. });
  17195. return request;
  17196. };
  17197. /** @hidden */
  17198. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17199. var _this = this;
  17200. return new Promise(function (resolve, reject) {
  17201. _this._loadFile(url, function (data) {
  17202. resolve(data);
  17203. }, undefined, database, useArrayBuffer, function (request, exception) {
  17204. reject(exception);
  17205. });
  17206. });
  17207. };
  17208. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17209. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17210. var onload = function (data) {
  17211. loadedFiles[index] = data;
  17212. loadedFiles._internalCount++;
  17213. if (loadedFiles._internalCount === 6) {
  17214. onfinish(loadedFiles);
  17215. }
  17216. };
  17217. var onerror = function (request, exception) {
  17218. if (onErrorCallBack && request) {
  17219. onErrorCallBack(request.status + " " + request.statusText, exception);
  17220. }
  17221. };
  17222. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17223. };
  17224. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17225. if (onError === void 0) { onError = null; }
  17226. var loadedFiles = [];
  17227. loadedFiles._internalCount = 0;
  17228. for (var index = 0; index < 6; index++) {
  17229. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17230. }
  17231. };
  17232. // Statics
  17233. /**
  17234. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17235. * @returns true if the engine can be created
  17236. * @ignorenaming
  17237. */
  17238. Engine.isSupported = function () {
  17239. try {
  17240. var tempcanvas = document.createElement("canvas");
  17241. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17242. return gl != null && !!window.WebGLRenderingContext;
  17243. }
  17244. catch (e) {
  17245. return false;
  17246. }
  17247. };
  17248. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17249. Engine.ExceptionList = [
  17250. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17251. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17252. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17253. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17254. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17255. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17256. ];
  17257. /** Gets the list of created engines */
  17258. Engine.Instances = new Array();
  17259. /**
  17260. * Hidden
  17261. */
  17262. Engine._TextureLoaders = [];
  17263. // Const statics
  17264. /** Defines that alpha blending is disabled */
  17265. Engine.ALPHA_DISABLE = 0;
  17266. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17267. Engine.ALPHA_ADD = 1;
  17268. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17269. Engine.ALPHA_COMBINE = 2;
  17270. /** Defines that alpha blending to DEST - SRC * DEST */
  17271. Engine.ALPHA_SUBTRACT = 3;
  17272. /** Defines that alpha blending to SRC * DEST */
  17273. Engine.ALPHA_MULTIPLY = 4;
  17274. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17275. Engine.ALPHA_MAXIMIZED = 5;
  17276. /** Defines that alpha blending to SRC + DEST */
  17277. Engine.ALPHA_ONEONE = 6;
  17278. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17279. Engine.ALPHA_PREMULTIPLIED = 7;
  17280. /**
  17281. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17282. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17283. */
  17284. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17285. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17286. Engine.ALPHA_INTERPOLATE = 9;
  17287. /**
  17288. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17289. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17290. */
  17291. Engine.ALPHA_SCREENMODE = 10;
  17292. /** Defines that the ressource is not delayed*/
  17293. Engine.DELAYLOADSTATE_NONE = 0;
  17294. /** Defines that the ressource was successfully delay loaded */
  17295. Engine.DELAYLOADSTATE_LOADED = 1;
  17296. /** Defines that the ressource is currently delay loading */
  17297. Engine.DELAYLOADSTATE_LOADING = 2;
  17298. /** Defines that the ressource is delayed and has not started loading */
  17299. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17300. // Depht or Stencil test Constants.
  17301. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17302. Engine.NEVER = 0x0200;
  17303. /** 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 */
  17304. Engine.ALWAYS = 0x0207;
  17305. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17306. Engine.LESS = 0x0201;
  17307. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17308. Engine.EQUAL = 0x0202;
  17309. /** 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 */
  17310. Engine.LEQUAL = 0x0203;
  17311. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17312. Engine.GREATER = 0x0204;
  17313. /** 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 */
  17314. Engine.GEQUAL = 0x0206;
  17315. /** 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 */
  17316. Engine.NOTEQUAL = 0x0205;
  17317. // Stencil Actions Constants.
  17318. /** Passed to stencilOperation to specify that stencil value must be kept */
  17319. Engine.KEEP = 0x1E00;
  17320. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17321. Engine.REPLACE = 0x1E01;
  17322. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17323. Engine.INCR = 0x1E02;
  17324. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17325. Engine.DECR = 0x1E03;
  17326. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17327. Engine.INVERT = 0x150A;
  17328. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17329. Engine.INCR_WRAP = 0x8507;
  17330. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17331. Engine.DECR_WRAP = 0x8508;
  17332. /** Texture is not repeating outside of 0..1 UVs */
  17333. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17334. /** Texture is repeating outside of 0..1 UVs */
  17335. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17336. /** Texture is repeating and mirrored */
  17337. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17338. /** ALPHA */
  17339. Engine.TEXTUREFORMAT_ALPHA = 0;
  17340. /** LUMINANCE */
  17341. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17342. /** LUMINANCE_ALPHA */
  17343. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17344. /** RGB */
  17345. Engine.TEXTUREFORMAT_RGB = 4;
  17346. /** RGBA */
  17347. Engine.TEXTUREFORMAT_RGBA = 5;
  17348. /** RED */
  17349. Engine.TEXTUREFORMAT_RED = 6;
  17350. /** RED (2nd reference) */
  17351. Engine.TEXTUREFORMAT_R = 6;
  17352. /** RG */
  17353. Engine.TEXTUREFORMAT_RG = 7;
  17354. /** RED_INTEGER */
  17355. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17356. /** RED_INTEGER (2nd reference) */
  17357. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17358. /** RG_INTEGER */
  17359. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17360. /** RGB_INTEGER */
  17361. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17362. /** RGBA_INTEGER */
  17363. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17364. /** UNSIGNED_BYTE */
  17365. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17366. /** UNSIGNED_BYTE (2nd reference) */
  17367. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17368. /** FLOAT */
  17369. Engine.TEXTURETYPE_FLOAT = 1;
  17370. /** HALF_FLOAT */
  17371. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17372. /** BYTE */
  17373. Engine.TEXTURETYPE_BYTE = 3;
  17374. /** SHORT */
  17375. Engine.TEXTURETYPE_SHORT = 4;
  17376. /** UNSIGNED_SHORT */
  17377. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17378. /** INT */
  17379. Engine.TEXTURETYPE_INT = 6;
  17380. /** UNSIGNED_INT */
  17381. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17382. /** UNSIGNED_SHORT_4_4_4_4 */
  17383. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17384. /** UNSIGNED_SHORT_5_5_5_1 */
  17385. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17386. /** UNSIGNED_SHORT_5_6_5 */
  17387. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17388. /** UNSIGNED_INT_2_10_10_10_REV */
  17389. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17390. /** UNSIGNED_INT_24_8 */
  17391. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17392. /** UNSIGNED_INT_10F_11F_11F_REV */
  17393. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17394. /** UNSIGNED_INT_5_9_9_9_REV */
  17395. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17396. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17397. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17398. /** nearest is mag = nearest and min = nearest and mip = linear */
  17399. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17400. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17401. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17402. /** Trilinear is mag = linear and min = linear and mip = linear */
  17403. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17404. /** nearest is mag = nearest and min = nearest and mip = linear */
  17405. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17406. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17407. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17408. /** Trilinear is mag = linear and min = linear and mip = linear */
  17409. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17410. /** mag = nearest and min = nearest and mip = nearest */
  17411. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17412. /** mag = nearest and min = linear and mip = nearest */
  17413. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17414. /** mag = nearest and min = linear and mip = linear */
  17415. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17416. /** mag = nearest and min = linear and mip = none */
  17417. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17418. /** mag = nearest and min = nearest and mip = none */
  17419. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17420. /** mag = linear and min = nearest and mip = nearest */
  17421. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17422. /** mag = linear and min = nearest and mip = linear */
  17423. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17424. /** mag = linear and min = linear and mip = none */
  17425. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17426. /** mag = linear and min = nearest and mip = none */
  17427. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17428. /** Explicit coordinates mode */
  17429. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17430. /** Spherical coordinates mode */
  17431. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17432. /** Planar coordinates mode */
  17433. Engine.TEXTURE_PLANAR_MODE = 2;
  17434. /** Cubic coordinates mode */
  17435. Engine.TEXTURE_CUBIC_MODE = 3;
  17436. /** Projection coordinates mode */
  17437. Engine.TEXTURE_PROJECTION_MODE = 4;
  17438. /** Skybox coordinates mode */
  17439. Engine.TEXTURE_SKYBOX_MODE = 5;
  17440. /** Inverse Cubic coordinates mode */
  17441. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17442. /** Equirectangular coordinates mode */
  17443. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17444. /** Equirectangular Fixed coordinates mode */
  17445. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17446. /** Equirectangular Fixed Mirrored coordinates mode */
  17447. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17448. // Texture rescaling mode
  17449. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17450. Engine.SCALEMODE_FLOOR = 1;
  17451. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17452. Engine.SCALEMODE_NEAREST = 2;
  17453. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17454. Engine.SCALEMODE_CEILING = 3;
  17455. // Updatable statics so stick with vars here
  17456. /**
  17457. * Gets or sets the epsilon value used by collision engine
  17458. */
  17459. Engine.CollisionsEpsilon = 0.001;
  17460. /**
  17461. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17462. */
  17463. Engine.CodeRepository = "src/";
  17464. /**
  17465. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17466. */
  17467. Engine.ShadersRepository = "src/Shaders/";
  17468. return Engine;
  17469. }());
  17470. BABYLON.Engine = Engine;
  17471. })(BABYLON || (BABYLON = {}));
  17472. //# sourceMappingURL=babylon.engine.js.map
  17473. var BABYLON;
  17474. (function (BABYLON) {
  17475. /**
  17476. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17477. */
  17478. var Node = /** @class */ (function () {
  17479. /**
  17480. * Creates a new Node
  17481. * @param {string} name - the name and id to be given to this node
  17482. * @param {BABYLON.Scene} the scene this node will be added to
  17483. */
  17484. function Node(name, scene) {
  17485. if (scene === void 0) { scene = null; }
  17486. /**
  17487. * Gets or sets a string used to store user defined state for the node
  17488. */
  17489. this.state = "";
  17490. /**
  17491. * Gets or sets an object used to store user defined information for the node
  17492. */
  17493. this.metadata = null;
  17494. /**
  17495. * Gets or sets a boolean used to define if the node must be serialized
  17496. */
  17497. this.doNotSerialize = false;
  17498. /** @hidden */
  17499. this._isDisposed = false;
  17500. /**
  17501. * Gets a list of Animations associated with the node
  17502. */
  17503. this.animations = new Array();
  17504. this._ranges = {};
  17505. this._isEnabled = true;
  17506. this._isReady = true;
  17507. /** @hidden */
  17508. this._currentRenderId = -1;
  17509. this._parentRenderId = -1;
  17510. this._childRenderId = -1;
  17511. this._animationPropertiesOverride = null;
  17512. /**
  17513. * An event triggered when the mesh is disposed
  17514. */
  17515. this.onDisposeObservable = new BABYLON.Observable();
  17516. // Behaviors
  17517. this._behaviors = new Array();
  17518. this.name = name;
  17519. this.id = name;
  17520. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17521. this.uniqueId = this._scene.getUniqueId();
  17522. this._initCache();
  17523. this._scene.rootNodes.push(this);
  17524. }
  17525. /**
  17526. * Add a new node constructor
  17527. * @param type defines the type name of the node to construct
  17528. * @param constructorFunc defines the constructor function
  17529. */
  17530. Node.AddNodeConstructor = function (type, constructorFunc) {
  17531. this._NodeConstructors[type] = constructorFunc;
  17532. };
  17533. /**
  17534. * Returns a node constructor based on type name
  17535. * @param type defines the type name
  17536. * @param name defines the new node name
  17537. * @param scene defines the hosting scene
  17538. * @param options defines optional options to transmit to constructors
  17539. * @returns the new constructor or null
  17540. */
  17541. Node.Construct = function (type, name, scene, options) {
  17542. var constructorFunc = this._NodeConstructors[type];
  17543. if (!constructorFunc) {
  17544. return null;
  17545. }
  17546. return constructorFunc(name, scene, options);
  17547. };
  17548. /**
  17549. * Gets a boolean indicating if the node has been disposed
  17550. * @returns true if the node was disposed
  17551. */
  17552. Node.prototype.isDisposed = function () {
  17553. return this._isDisposed;
  17554. };
  17555. Object.defineProperty(Node.prototype, "parent", {
  17556. get: function () {
  17557. return this._parentNode;
  17558. },
  17559. /**
  17560. * Gets or sets the parent of the node
  17561. */
  17562. set: function (parent) {
  17563. if (this._parentNode === parent) {
  17564. return;
  17565. }
  17566. var previousParentNode = this._parentNode;
  17567. // Remove self from list of children of parent
  17568. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17569. var index = this._parentNode._children.indexOf(this);
  17570. if (index !== -1) {
  17571. this._parentNode._children.splice(index, 1);
  17572. }
  17573. if (!parent) {
  17574. // Need to add this node to the rootNodes
  17575. this._scene.rootNodes.push(this);
  17576. }
  17577. }
  17578. // Store new parent
  17579. this._parentNode = parent;
  17580. // Add as child to new parent
  17581. if (this._parentNode) {
  17582. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17583. this._parentNode._children = new Array();
  17584. }
  17585. this._parentNode._children.push(this);
  17586. if (!previousParentNode) {
  17587. // Need to remove from rootNodes
  17588. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17589. if (rootNodeIndex > -1) {
  17590. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17591. }
  17592. }
  17593. }
  17594. },
  17595. enumerable: true,
  17596. configurable: true
  17597. });
  17598. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17599. /**
  17600. * Gets or sets the animation properties override
  17601. */
  17602. get: function () {
  17603. if (!this._animationPropertiesOverride) {
  17604. return this._scene.animationPropertiesOverride;
  17605. }
  17606. return this._animationPropertiesOverride;
  17607. },
  17608. set: function (value) {
  17609. this._animationPropertiesOverride = value;
  17610. },
  17611. enumerable: true,
  17612. configurable: true
  17613. });
  17614. /**
  17615. * Gets a string idenfifying the name of the class
  17616. * @returns "Node" string
  17617. */
  17618. Node.prototype.getClassName = function () {
  17619. return "Node";
  17620. };
  17621. Object.defineProperty(Node.prototype, "onDispose", {
  17622. /**
  17623. * Sets a callback that will be raised when the node will be disposed
  17624. */
  17625. set: function (callback) {
  17626. if (this._onDisposeObserver) {
  17627. this.onDisposeObservable.remove(this._onDisposeObserver);
  17628. }
  17629. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17630. },
  17631. enumerable: true,
  17632. configurable: true
  17633. });
  17634. /**
  17635. * Gets the scene of the node
  17636. * @returns a {BABYLON.Scene}
  17637. */
  17638. Node.prototype.getScene = function () {
  17639. return this._scene;
  17640. };
  17641. /**
  17642. * Gets the engine of the node
  17643. * @returns a {BABYLON.Engine}
  17644. */
  17645. Node.prototype.getEngine = function () {
  17646. return this._scene.getEngine();
  17647. };
  17648. /**
  17649. * Attach a behavior to the node
  17650. * @see http://doc.babylonjs.com/features/behaviour
  17651. * @param behavior defines the behavior to attach
  17652. * @returns the current Node
  17653. */
  17654. Node.prototype.addBehavior = function (behavior) {
  17655. var _this = this;
  17656. var index = this._behaviors.indexOf(behavior);
  17657. if (index !== -1) {
  17658. return this;
  17659. }
  17660. behavior.init();
  17661. if (this._scene.isLoading) {
  17662. // We defer the attach when the scene will be loaded
  17663. this._scene.onDataLoadedObservable.addOnce(function () {
  17664. behavior.attach(_this);
  17665. });
  17666. }
  17667. else {
  17668. behavior.attach(this);
  17669. }
  17670. this._behaviors.push(behavior);
  17671. return this;
  17672. };
  17673. /**
  17674. * Remove an attached behavior
  17675. * @see http://doc.babylonjs.com/features/behaviour
  17676. * @param behavior defines the behavior to attach
  17677. * @returns the current Node
  17678. */
  17679. Node.prototype.removeBehavior = function (behavior) {
  17680. var index = this._behaviors.indexOf(behavior);
  17681. if (index === -1) {
  17682. return this;
  17683. }
  17684. this._behaviors[index].detach();
  17685. this._behaviors.splice(index, 1);
  17686. return this;
  17687. };
  17688. Object.defineProperty(Node.prototype, "behaviors", {
  17689. /**
  17690. * Gets the list of attached behaviors
  17691. * @see http://doc.babylonjs.com/features/behaviour
  17692. */
  17693. get: function () {
  17694. return this._behaviors;
  17695. },
  17696. enumerable: true,
  17697. configurable: true
  17698. });
  17699. /**
  17700. * Gets an attached behavior by name
  17701. * @param name defines the name of the behavior to look for
  17702. * @see http://doc.babylonjs.com/features/behaviour
  17703. * @returns null if behavior was not found else the requested behavior
  17704. */
  17705. Node.prototype.getBehaviorByName = function (name) {
  17706. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17707. var behavior = _a[_i];
  17708. if (behavior.name === name) {
  17709. return behavior;
  17710. }
  17711. }
  17712. return null;
  17713. };
  17714. /**
  17715. * Returns the world matrix of the node
  17716. * @returns a matrix containing the node's world matrix
  17717. */
  17718. Node.prototype.getWorldMatrix = function () {
  17719. return BABYLON.Matrix.Identity();
  17720. };
  17721. /** @hidden */
  17722. Node.prototype._getWorldMatrixDeterminant = function () {
  17723. return 1;
  17724. };
  17725. // override it in derived class if you add new variables to the cache
  17726. // and call the parent class method
  17727. /** @hidden */
  17728. Node.prototype._initCache = function () {
  17729. this._cache = {};
  17730. this._cache.parent = undefined;
  17731. };
  17732. /** @hidden */
  17733. Node.prototype.updateCache = function (force) {
  17734. if (!force && this.isSynchronized())
  17735. return;
  17736. this._cache.parent = this.parent;
  17737. this._updateCache();
  17738. };
  17739. // override it in derived class if you add new variables to the cache
  17740. // and call the parent class method if !ignoreParentClass
  17741. /** @hidden */
  17742. Node.prototype._updateCache = function (ignoreParentClass) {
  17743. };
  17744. // override it in derived class if you add new variables to the cache
  17745. /** @hidden */
  17746. Node.prototype._isSynchronized = function () {
  17747. return true;
  17748. };
  17749. /** @hidden */
  17750. Node.prototype._markSyncedWithParent = function () {
  17751. if (this.parent) {
  17752. this._parentRenderId = this.parent._childRenderId;
  17753. }
  17754. };
  17755. /** @hidden */
  17756. Node.prototype.isSynchronizedWithParent = function () {
  17757. if (!this.parent) {
  17758. return true;
  17759. }
  17760. if (this._parentRenderId !== this.parent._childRenderId) {
  17761. return false;
  17762. }
  17763. return this.parent.isSynchronized();
  17764. };
  17765. /** @hidden */
  17766. Node.prototype.isSynchronized = function (updateCache) {
  17767. var check = this.hasNewParent();
  17768. check = check || !this.isSynchronizedWithParent();
  17769. check = check || !this._isSynchronized();
  17770. if (updateCache)
  17771. this.updateCache(true);
  17772. return !check;
  17773. };
  17774. /** @hidden */
  17775. Node.prototype.hasNewParent = function () {
  17776. if (this._cache.parent === this.parent)
  17777. return false;
  17778. this._cache.parent = this.parent;
  17779. return true;
  17780. };
  17781. /**
  17782. * Is this node ready to be used/rendered
  17783. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17784. * @return true if the node is ready
  17785. */
  17786. Node.prototype.isReady = function (completeCheck) {
  17787. if (completeCheck === void 0) { completeCheck = false; }
  17788. return this._isReady;
  17789. };
  17790. /**
  17791. * Is this node enabled?
  17792. * 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
  17793. * @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
  17794. * @return whether this node (and its parent) is enabled
  17795. */
  17796. Node.prototype.isEnabled = function (checkAncestors) {
  17797. if (checkAncestors === void 0) { checkAncestors = true; }
  17798. if (checkAncestors === false) {
  17799. return this._isEnabled;
  17800. }
  17801. if (this._isEnabled === false) {
  17802. return false;
  17803. }
  17804. if (this.parent !== undefined && this.parent !== null) {
  17805. return this.parent.isEnabled(checkAncestors);
  17806. }
  17807. return true;
  17808. };
  17809. /**
  17810. * Set the enabled state of this node
  17811. * @param value defines the new enabled state
  17812. */
  17813. Node.prototype.setEnabled = function (value) {
  17814. this._isEnabled = value;
  17815. };
  17816. /**
  17817. * Is this node a descendant of the given node?
  17818. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17819. * @param ancestor defines the parent node to inspect
  17820. * @returns a boolean indicating if this node is a descendant of the given node
  17821. */
  17822. Node.prototype.isDescendantOf = function (ancestor) {
  17823. if (this.parent) {
  17824. if (this.parent === ancestor) {
  17825. return true;
  17826. }
  17827. return this.parent.isDescendantOf(ancestor);
  17828. }
  17829. return false;
  17830. };
  17831. /** @hidden */
  17832. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17833. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17834. if (!this._children) {
  17835. return;
  17836. }
  17837. for (var index = 0; index < this._children.length; index++) {
  17838. var item = this._children[index];
  17839. if (!predicate || predicate(item)) {
  17840. results.push(item);
  17841. }
  17842. if (!directDescendantsOnly) {
  17843. item._getDescendants(results, false, predicate);
  17844. }
  17845. }
  17846. };
  17847. /**
  17848. * Will return all nodes that have this node as ascendant
  17849. * @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
  17850. * @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
  17851. * @return all children nodes of all types
  17852. */
  17853. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17854. var results = new Array();
  17855. this._getDescendants(results, directDescendantsOnly, predicate);
  17856. return results;
  17857. };
  17858. /**
  17859. * Get all child-meshes of this node
  17860. * @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
  17861. * @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
  17862. * @returns an array of {BABYLON.AbstractMesh}
  17863. */
  17864. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17865. var results = [];
  17866. this._getDescendants(results, directDescendantsOnly, function (node) {
  17867. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17868. });
  17869. return results;
  17870. };
  17871. /**
  17872. * Get all child-transformNodes of this node
  17873. * @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
  17874. * @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
  17875. * @returns an array of {BABYLON.TransformNode}
  17876. */
  17877. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17878. var results = [];
  17879. this._getDescendants(results, directDescendantsOnly, function (node) {
  17880. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17881. });
  17882. return results;
  17883. };
  17884. /**
  17885. * Get all direct children of this node
  17886. * @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
  17887. * @returns an array of {BABYLON.Node}
  17888. */
  17889. Node.prototype.getChildren = function (predicate) {
  17890. if (!predicate) {
  17891. return this._children;
  17892. }
  17893. return this.getDescendants(true, predicate);
  17894. };
  17895. /** @hidden */
  17896. Node.prototype._setReady = function (state) {
  17897. if (state === this._isReady) {
  17898. return;
  17899. }
  17900. if (!state) {
  17901. this._isReady = false;
  17902. return;
  17903. }
  17904. if (this.onReady) {
  17905. this.onReady(this);
  17906. }
  17907. this._isReady = true;
  17908. };
  17909. /**
  17910. * Get an animation by name
  17911. * @param name defines the name of the animation to look for
  17912. * @returns null if not found else the requested animation
  17913. */
  17914. Node.prototype.getAnimationByName = function (name) {
  17915. for (var i = 0; i < this.animations.length; i++) {
  17916. var animation = this.animations[i];
  17917. if (animation.name === name) {
  17918. return animation;
  17919. }
  17920. }
  17921. return null;
  17922. };
  17923. /**
  17924. * Creates an animation range for this node
  17925. * @param name defines the name of the range
  17926. * @param from defines the starting key
  17927. * @param to defines the end key
  17928. */
  17929. Node.prototype.createAnimationRange = function (name, from, to) {
  17930. // check name not already in use
  17931. if (!this._ranges[name]) {
  17932. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17933. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17934. if (this.animations[i]) {
  17935. this.animations[i].createRange(name, from, to);
  17936. }
  17937. }
  17938. }
  17939. };
  17940. /**
  17941. * Delete a specific animation range
  17942. * @param name defines the name of the range to delete
  17943. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17944. */
  17945. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17946. if (deleteFrames === void 0) { deleteFrames = true; }
  17947. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17948. if (this.animations[i]) {
  17949. this.animations[i].deleteRange(name, deleteFrames);
  17950. }
  17951. }
  17952. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17953. };
  17954. /**
  17955. * Get an animation range by name
  17956. * @param name defines the name of the animation range to look for
  17957. * @returns null if not found else the requested animation range
  17958. */
  17959. Node.prototype.getAnimationRange = function (name) {
  17960. return this._ranges[name];
  17961. };
  17962. /**
  17963. * Will start the animation sequence
  17964. * @param name defines the range frames for animation sequence
  17965. * @param loop defines if the animation should loop (false by default)
  17966. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17967. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17968. * @returns the object created for this animation. If range does not exist, it will return null
  17969. */
  17970. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17971. var range = this.getAnimationRange(name);
  17972. if (!range) {
  17973. return null;
  17974. }
  17975. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17976. };
  17977. /**
  17978. * Serialize animation ranges into a JSON compatible object
  17979. * @returns serialization object
  17980. */
  17981. Node.prototype.serializeAnimationRanges = function () {
  17982. var serializationRanges = [];
  17983. for (var name in this._ranges) {
  17984. var localRange = this._ranges[name];
  17985. if (!localRange) {
  17986. continue;
  17987. }
  17988. var range = {};
  17989. range.name = name;
  17990. range.from = localRange.from;
  17991. range.to = localRange.to;
  17992. serializationRanges.push(range);
  17993. }
  17994. return serializationRanges;
  17995. };
  17996. /**
  17997. * Computes the world matrix of the node
  17998. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17999. * @returns the world matrix
  18000. */
  18001. Node.prototype.computeWorldMatrix = function (force) {
  18002. return BABYLON.Matrix.Identity();
  18003. };
  18004. /**
  18005. * Releases resources associated with this node.
  18006. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18007. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18008. */
  18009. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18010. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18011. if (!doNotRecurse) {
  18012. var nodes = this.getDescendants(true);
  18013. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18014. var node = nodes_1[_i];
  18015. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18016. }
  18017. }
  18018. else {
  18019. var transformNodes = this.getChildTransformNodes(true);
  18020. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18021. var transformNode = transformNodes_1[_a];
  18022. transformNode.parent = null;
  18023. transformNode.computeWorldMatrix(true);
  18024. }
  18025. }
  18026. if (!this.parent) {
  18027. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18028. if (rootNodeIndex > -1) {
  18029. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18030. }
  18031. }
  18032. else {
  18033. this.parent = null;
  18034. }
  18035. // Callback
  18036. this.onDisposeObservable.notifyObservers(this);
  18037. this.onDisposeObservable.clear();
  18038. // Behaviors
  18039. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18040. var behavior = _c[_b];
  18041. behavior.detach();
  18042. }
  18043. this._behaviors = [];
  18044. this._isDisposed = true;
  18045. };
  18046. /**
  18047. * Parse animation range data from a serialization object and store them into a given node
  18048. * @param node defines where to store the animation ranges
  18049. * @param parsedNode defines the serialization object to read data from
  18050. * @param scene defines the hosting scene
  18051. */
  18052. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18053. if (parsedNode.ranges) {
  18054. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18055. var data = parsedNode.ranges[index];
  18056. node.createAnimationRange(data.name, data.from, data.to);
  18057. }
  18058. }
  18059. };
  18060. Node._NodeConstructors = {};
  18061. __decorate([
  18062. BABYLON.serialize()
  18063. ], Node.prototype, "name", void 0);
  18064. __decorate([
  18065. BABYLON.serialize()
  18066. ], Node.prototype, "id", void 0);
  18067. __decorate([
  18068. BABYLON.serialize()
  18069. ], Node.prototype, "uniqueId", void 0);
  18070. __decorate([
  18071. BABYLON.serialize()
  18072. ], Node.prototype, "state", void 0);
  18073. __decorate([
  18074. BABYLON.serialize()
  18075. ], Node.prototype, "metadata", void 0);
  18076. return Node;
  18077. }());
  18078. BABYLON.Node = Node;
  18079. })(BABYLON || (BABYLON = {}));
  18080. //# sourceMappingURL=babylon.node.js.map
  18081. var BABYLON;
  18082. (function (BABYLON) {
  18083. // This matrix is used as a value to reset the bounding box.
  18084. var _identityMatrix = BABYLON.Matrix.Identity();
  18085. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18086. var BoundingSphere = /** @class */ (function () {
  18087. /**
  18088. * Creates a new bounding sphere
  18089. * @param min defines the minimum vector (in local space)
  18090. * @param max defines the maximum vector (in local space)
  18091. */
  18092. function BoundingSphere(min, max) {
  18093. this.center = BABYLON.Vector3.Zero();
  18094. this.centerWorld = BABYLON.Vector3.Zero();
  18095. this.reConstruct(min, max);
  18096. }
  18097. /**
  18098. * Recreates the entire bounding sphere from scratch
  18099. * @param min defines the new minimum vector (in local space)
  18100. * @param max defines the new maximum vector (in local space)
  18101. */
  18102. BoundingSphere.prototype.reConstruct = function (min, max) {
  18103. this.minimum = min.clone();
  18104. this.maximum = max.clone();
  18105. var distance = BABYLON.Vector3.Distance(min, max);
  18106. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18107. this.radius = distance * 0.5;
  18108. this.centerWorld.set(0, 0, 0);
  18109. this._update(_identityMatrix);
  18110. };
  18111. /**
  18112. * Scale the current bounding sphere by applying a scale factor
  18113. * @param factor defines the scale factor to apply
  18114. * @returns the current bounding box
  18115. */
  18116. BoundingSphere.prototype.scale = function (factor) {
  18117. var newRadius = this.radius * factor;
  18118. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18119. var min = this.center.subtract(_tempRadiusVector);
  18120. var max = this.center.add(_tempRadiusVector);
  18121. this.reConstruct(min, max);
  18122. return this;
  18123. };
  18124. // Methods
  18125. /** @hidden */
  18126. BoundingSphere.prototype._update = function (world) {
  18127. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18128. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18129. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18130. };
  18131. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18132. for (var i = 0; i < 6; i++) {
  18133. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18134. return false;
  18135. }
  18136. return true;
  18137. };
  18138. BoundingSphere.prototype.intersectsPoint = function (point) {
  18139. var x = this.centerWorld.x - point.x;
  18140. var y = this.centerWorld.y - point.y;
  18141. var z = this.centerWorld.z - point.z;
  18142. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18143. if (this.radiusWorld < distance)
  18144. return false;
  18145. return true;
  18146. };
  18147. // Statics
  18148. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18149. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18150. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18151. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18152. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18153. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18154. return false;
  18155. return true;
  18156. };
  18157. return BoundingSphere;
  18158. }());
  18159. BABYLON.BoundingSphere = BoundingSphere;
  18160. })(BABYLON || (BABYLON = {}));
  18161. //# sourceMappingURL=babylon.boundingSphere.js.map
  18162. var BABYLON;
  18163. (function (BABYLON) {
  18164. var BoundingBox = /** @class */ (function () {
  18165. /**
  18166. * Creates a new bounding box
  18167. * @param min defines the minimum vector (in local space)
  18168. * @param max defines the maximum vector (in local space)
  18169. */
  18170. function BoundingBox(min, max) {
  18171. this.vectorsWorld = new Array();
  18172. this.reConstruct(min, max);
  18173. }
  18174. // Methods
  18175. /**
  18176. * Recreates the entire bounding box from scratch
  18177. * @param min defines the new minimum vector (in local space)
  18178. * @param max defines the new maximum vector (in local space)
  18179. */
  18180. BoundingBox.prototype.reConstruct = function (min, max) {
  18181. this.minimum = min.clone();
  18182. this.maximum = max.clone();
  18183. // Bounding vectors
  18184. this.vectors = [
  18185. this.minimum.clone(),
  18186. this.maximum.clone(),
  18187. this.minimum.clone(),
  18188. this.minimum.clone(),
  18189. this.minimum.clone(),
  18190. this.maximum.clone(),
  18191. this.maximum.clone(),
  18192. this.maximum.clone()
  18193. ];
  18194. this.vectors[2].x = this.maximum.x;
  18195. this.vectors[3].y = this.maximum.y;
  18196. this.vectors[4].z = this.maximum.z;
  18197. this.vectors[5].z = this.minimum.z;
  18198. this.vectors[6].x = this.minimum.x;
  18199. this.vectors[7].y = this.minimum.y;
  18200. // OBB
  18201. this.center = this.maximum.add(this.minimum).scale(0.5);
  18202. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18203. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18204. // World
  18205. for (var index = 0; index < this.vectors.length; index++) {
  18206. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18207. }
  18208. this.minimumWorld = BABYLON.Vector3.Zero();
  18209. this.maximumWorld = BABYLON.Vector3.Zero();
  18210. this.centerWorld = BABYLON.Vector3.Zero();
  18211. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18212. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18213. };
  18214. /**
  18215. * Scale the current bounding box by applying a scale factor
  18216. * @param factor defines the scale factor to apply
  18217. * @returns the current bounding box
  18218. */
  18219. BoundingBox.prototype.scale = function (factor) {
  18220. var diff = this.maximum.subtract(this.minimum);
  18221. var distance = diff.length() * factor;
  18222. diff.normalize();
  18223. var newRadius = diff.scale(distance / 2);
  18224. var min = this.center.subtract(newRadius);
  18225. var max = this.center.add(newRadius);
  18226. this.reConstruct(min, max);
  18227. return this;
  18228. };
  18229. BoundingBox.prototype.getWorldMatrix = function () {
  18230. return this._worldMatrix;
  18231. };
  18232. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18233. this._worldMatrix.copyFrom(matrix);
  18234. return this;
  18235. };
  18236. /** @hidden */
  18237. BoundingBox.prototype._update = function (world) {
  18238. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18239. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18240. for (var index = 0; index < this.vectors.length; index++) {
  18241. var v = this.vectorsWorld[index];
  18242. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18243. if (v.x < this.minimumWorld.x)
  18244. this.minimumWorld.x = v.x;
  18245. if (v.y < this.minimumWorld.y)
  18246. this.minimumWorld.y = v.y;
  18247. if (v.z < this.minimumWorld.z)
  18248. this.minimumWorld.z = v.z;
  18249. if (v.x > this.maximumWorld.x)
  18250. this.maximumWorld.x = v.x;
  18251. if (v.y > this.maximumWorld.y)
  18252. this.maximumWorld.y = v.y;
  18253. if (v.z > this.maximumWorld.z)
  18254. this.maximumWorld.z = v.z;
  18255. }
  18256. // Extend
  18257. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18258. this.extendSizeWorld.scaleInPlace(0.5);
  18259. // OBB
  18260. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18261. this.centerWorld.scaleInPlace(0.5);
  18262. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18263. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18264. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18265. this._worldMatrix = world;
  18266. };
  18267. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18268. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18269. };
  18270. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18271. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18272. };
  18273. BoundingBox.prototype.intersectsPoint = function (point) {
  18274. var delta = -BABYLON.Epsilon;
  18275. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18276. return false;
  18277. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18278. return false;
  18279. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18280. return false;
  18281. return true;
  18282. };
  18283. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18284. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18285. };
  18286. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18287. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18288. return false;
  18289. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18290. return false;
  18291. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18292. return false;
  18293. return true;
  18294. };
  18295. // Statics
  18296. BoundingBox.Intersects = function (box0, box1) {
  18297. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18298. return false;
  18299. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18300. return false;
  18301. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18302. return false;
  18303. return true;
  18304. };
  18305. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18306. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18307. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18308. return (num <= (sphereRadius * sphereRadius));
  18309. };
  18310. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18311. for (var p = 0; p < 6; p++) {
  18312. for (var i = 0; i < 8; i++) {
  18313. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18314. return false;
  18315. }
  18316. }
  18317. }
  18318. return true;
  18319. };
  18320. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18321. for (var p = 0; p < 6; p++) {
  18322. var inCount = 8;
  18323. for (var i = 0; i < 8; i++) {
  18324. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18325. --inCount;
  18326. }
  18327. else {
  18328. break;
  18329. }
  18330. }
  18331. if (inCount === 0)
  18332. return false;
  18333. }
  18334. return true;
  18335. };
  18336. return BoundingBox;
  18337. }());
  18338. BABYLON.BoundingBox = BoundingBox;
  18339. })(BABYLON || (BABYLON = {}));
  18340. //# sourceMappingURL=babylon.boundingBox.js.map
  18341. var BABYLON;
  18342. (function (BABYLON) {
  18343. var computeBoxExtents = function (axis, box) {
  18344. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18345. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18346. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18347. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18348. var r = r0 + r1 + r2;
  18349. return {
  18350. min: p - r,
  18351. max: p + r
  18352. };
  18353. };
  18354. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18355. var axisOverlap = function (axis, box0, box1) {
  18356. var result0 = computeBoxExtents(axis, box0);
  18357. var result1 = computeBoxExtents(axis, box1);
  18358. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18359. };
  18360. var BoundingInfo = /** @class */ (function () {
  18361. function BoundingInfo(minimum, maximum) {
  18362. this.minimum = minimum;
  18363. this.maximum = maximum;
  18364. this._isLocked = false;
  18365. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18366. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18367. }
  18368. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18369. get: function () {
  18370. return this._isLocked;
  18371. },
  18372. set: function (value) {
  18373. this._isLocked = value;
  18374. },
  18375. enumerable: true,
  18376. configurable: true
  18377. });
  18378. // Methods
  18379. BoundingInfo.prototype.update = function (world) {
  18380. if (this._isLocked) {
  18381. return;
  18382. }
  18383. this.boundingBox._update(world);
  18384. this.boundingSphere._update(world);
  18385. };
  18386. /**
  18387. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18388. * @param center New center of the bounding info
  18389. * @param extend New extend of the bounding info
  18390. */
  18391. BoundingInfo.prototype.centerOn = function (center, extend) {
  18392. this.minimum = center.subtract(extend);
  18393. this.maximum = center.add(extend);
  18394. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18395. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18396. return this;
  18397. };
  18398. /**
  18399. * Scale the current bounding info by applying a scale factor
  18400. * @param factor defines the scale factor to apply
  18401. * @returns the current bounding info
  18402. */
  18403. BoundingInfo.prototype.scale = function (factor) {
  18404. this.boundingBox.scale(factor);
  18405. this.boundingSphere.scale(factor);
  18406. return this;
  18407. };
  18408. /**
  18409. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18410. * @param frustumPlanes defines the frustum to test
  18411. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18412. * @returns true if the bounding info is in the frustum planes
  18413. */
  18414. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18415. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18416. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18417. return false;
  18418. }
  18419. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18420. return true;
  18421. }
  18422. return this.boundingBox.isInFrustum(frustumPlanes);
  18423. };
  18424. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18425. /**
  18426. * Gets the world distance between the min and max points of the bounding box
  18427. */
  18428. get: function () {
  18429. var boundingBox = this.boundingBox;
  18430. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18431. return size.length();
  18432. },
  18433. enumerable: true,
  18434. configurable: true
  18435. });
  18436. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18437. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18438. };
  18439. /** @hidden */
  18440. BoundingInfo.prototype._checkCollision = function (collider) {
  18441. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18442. };
  18443. BoundingInfo.prototype.intersectsPoint = function (point) {
  18444. if (!this.boundingSphere.centerWorld) {
  18445. return false;
  18446. }
  18447. if (!this.boundingSphere.intersectsPoint(point)) {
  18448. return false;
  18449. }
  18450. if (!this.boundingBox.intersectsPoint(point)) {
  18451. return false;
  18452. }
  18453. return true;
  18454. };
  18455. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18456. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18457. return false;
  18458. }
  18459. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18460. return false;
  18461. }
  18462. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18463. return false;
  18464. }
  18465. if (!precise) {
  18466. return true;
  18467. }
  18468. var box0 = this.boundingBox;
  18469. var box1 = boundingInfo.boundingBox;
  18470. if (!axisOverlap(box0.directions[0], box0, box1))
  18471. return false;
  18472. if (!axisOverlap(box0.directions[1], box0, box1))
  18473. return false;
  18474. if (!axisOverlap(box0.directions[2], box0, box1))
  18475. return false;
  18476. if (!axisOverlap(box1.directions[0], box0, box1))
  18477. return false;
  18478. if (!axisOverlap(box1.directions[1], box0, box1))
  18479. return false;
  18480. if (!axisOverlap(box1.directions[2], box0, box1))
  18481. return false;
  18482. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18483. return false;
  18484. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18485. return false;
  18486. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18487. return false;
  18488. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18489. return false;
  18490. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18491. return false;
  18492. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18493. return false;
  18494. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18495. return false;
  18496. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18497. return false;
  18498. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18499. return false;
  18500. return true;
  18501. };
  18502. return BoundingInfo;
  18503. }());
  18504. BABYLON.BoundingInfo = BoundingInfo;
  18505. })(BABYLON || (BABYLON = {}));
  18506. //# sourceMappingURL=babylon.boundingInfo.js.map
  18507. var BABYLON;
  18508. (function (BABYLON) {
  18509. var TransformNode = /** @class */ (function (_super) {
  18510. __extends(TransformNode, _super);
  18511. function TransformNode(name, scene, isPure) {
  18512. if (scene === void 0) { scene = null; }
  18513. if (isPure === void 0) { isPure = true; }
  18514. var _this = _super.call(this, name, scene) || this;
  18515. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18516. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18517. _this._up = new BABYLON.Vector3(0, 1, 0);
  18518. _this._right = new BABYLON.Vector3(1, 0, 0);
  18519. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18520. // Properties
  18521. _this._rotation = BABYLON.Vector3.Zero();
  18522. _this._scaling = BABYLON.Vector3.One();
  18523. _this._isDirty = false;
  18524. /**
  18525. * Set the billboard mode. Default is 0.
  18526. *
  18527. * | Value | Type | Description |
  18528. * | --- | --- | --- |
  18529. * | 0 | BILLBOARDMODE_NONE | |
  18530. * | 1 | BILLBOARDMODE_X | |
  18531. * | 2 | BILLBOARDMODE_Y | |
  18532. * | 4 | BILLBOARDMODE_Z | |
  18533. * | 7 | BILLBOARDMODE_ALL | |
  18534. *
  18535. */
  18536. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18537. _this.scalingDeterminant = 1;
  18538. _this.infiniteDistance = false;
  18539. /**
  18540. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18541. * By default the system will update normals to compensate
  18542. */
  18543. _this.ignoreNonUniformScaling = false;
  18544. _this.position = BABYLON.Vector3.Zero();
  18545. _this._localWorld = BABYLON.Matrix.Zero();
  18546. /** @hidden */
  18547. _this._worldMatrix = BABYLON.Matrix.Zero();
  18548. /** @hidden */
  18549. _this._worldMatrixDeterminant = 0;
  18550. _this._absolutePosition = BABYLON.Vector3.Zero();
  18551. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18552. _this._postMultiplyPivotMatrix = false;
  18553. _this._isWorldMatrixFrozen = false;
  18554. /**
  18555. * An event triggered after the world matrix is updated
  18556. */
  18557. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18558. _this._nonUniformScaling = false;
  18559. if (isPure) {
  18560. _this.getScene().addTransformNode(_this);
  18561. }
  18562. return _this;
  18563. }
  18564. /**
  18565. * Gets a string identifying the name of the class
  18566. * @returns "TransformNode" string
  18567. */
  18568. TransformNode.prototype.getClassName = function () {
  18569. return "TransformNode";
  18570. };
  18571. Object.defineProperty(TransformNode.prototype, "rotation", {
  18572. /**
  18573. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18574. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18575. * Default : (0.0, 0.0, 0.0)
  18576. */
  18577. get: function () {
  18578. return this._rotation;
  18579. },
  18580. set: function (newRotation) {
  18581. this._rotation = newRotation;
  18582. },
  18583. enumerable: true,
  18584. configurable: true
  18585. });
  18586. Object.defineProperty(TransformNode.prototype, "scaling", {
  18587. /**
  18588. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18589. * Default : (1.0, 1.0, 1.0)
  18590. */
  18591. get: function () {
  18592. return this._scaling;
  18593. },
  18594. /**
  18595. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18596. * Default : (1.0, 1.0, 1.0)
  18597. */
  18598. set: function (newScaling) {
  18599. this._scaling = newScaling;
  18600. },
  18601. enumerable: true,
  18602. configurable: true
  18603. });
  18604. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18605. /**
  18606. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18607. * It's null by default.
  18608. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18609. */
  18610. get: function () {
  18611. return this._rotationQuaternion;
  18612. },
  18613. set: function (quaternion) {
  18614. this._rotationQuaternion = quaternion;
  18615. //reset the rotation vector.
  18616. if (quaternion && this.rotation.length()) {
  18617. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18618. }
  18619. },
  18620. enumerable: true,
  18621. configurable: true
  18622. });
  18623. Object.defineProperty(TransformNode.prototype, "forward", {
  18624. /**
  18625. * The forward direction of that transform in world space.
  18626. */
  18627. get: function () {
  18628. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18629. },
  18630. enumerable: true,
  18631. configurable: true
  18632. });
  18633. Object.defineProperty(TransformNode.prototype, "up", {
  18634. /**
  18635. * The up direction of that transform in world space.
  18636. */
  18637. get: function () {
  18638. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18639. },
  18640. enumerable: true,
  18641. configurable: true
  18642. });
  18643. Object.defineProperty(TransformNode.prototype, "right", {
  18644. /**
  18645. * The right direction of that transform in world space.
  18646. */
  18647. get: function () {
  18648. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18649. },
  18650. enumerable: true,
  18651. configurable: true
  18652. });
  18653. /**
  18654. * Returns the latest update of the World matrix
  18655. * Returns a Matrix.
  18656. */
  18657. TransformNode.prototype.getWorldMatrix = function () {
  18658. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18659. this.computeWorldMatrix();
  18660. }
  18661. return this._worldMatrix;
  18662. };
  18663. /** @hidden */
  18664. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18665. return this._worldMatrixDeterminant;
  18666. };
  18667. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18668. /**
  18669. * Returns directly the latest state of the mesh World matrix.
  18670. * A Matrix is returned.
  18671. */
  18672. get: function () {
  18673. return this._worldMatrix;
  18674. },
  18675. enumerable: true,
  18676. configurable: true
  18677. });
  18678. /**
  18679. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18680. * Returns the TransformNode.
  18681. */
  18682. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18683. this._poseMatrix.copyFrom(matrix);
  18684. return this;
  18685. };
  18686. /**
  18687. * Returns the mesh Pose matrix.
  18688. * Returned object : Matrix
  18689. */
  18690. TransformNode.prototype.getPoseMatrix = function () {
  18691. return this._poseMatrix;
  18692. };
  18693. /** @hidden */
  18694. TransformNode.prototype._isSynchronized = function () {
  18695. if (this._isDirty) {
  18696. return false;
  18697. }
  18698. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18699. return false;
  18700. if (this._cache.pivotMatrixUpdated) {
  18701. return false;
  18702. }
  18703. if (this.infiniteDistance) {
  18704. return false;
  18705. }
  18706. if (!this._cache.position.equals(this.position))
  18707. return false;
  18708. if (this._rotationQuaternion) {
  18709. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18710. return false;
  18711. }
  18712. if (!this._cache.rotation.equals(this.rotation))
  18713. return false;
  18714. if (!this._cache.scaling.equals(this.scaling))
  18715. return false;
  18716. return true;
  18717. };
  18718. /** @hidden */
  18719. TransformNode.prototype._initCache = function () {
  18720. _super.prototype._initCache.call(this);
  18721. this._cache.localMatrixUpdated = false;
  18722. this._cache.position = BABYLON.Vector3.Zero();
  18723. this._cache.scaling = BABYLON.Vector3.Zero();
  18724. this._cache.rotation = BABYLON.Vector3.Zero();
  18725. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18726. this._cache.billboardMode = -1;
  18727. };
  18728. TransformNode.prototype.markAsDirty = function (property) {
  18729. if (property === "rotation") {
  18730. this.rotationQuaternion = null;
  18731. }
  18732. this._currentRenderId = Number.MAX_VALUE;
  18733. this._isDirty = true;
  18734. return this;
  18735. };
  18736. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18737. /**
  18738. * Returns the current mesh absolute position.
  18739. * Returns a Vector3.
  18740. */
  18741. get: function () {
  18742. return this._absolutePosition;
  18743. },
  18744. enumerable: true,
  18745. configurable: true
  18746. });
  18747. /**
  18748. * Sets a new matrix to apply before all other transformation
  18749. * @param matrix defines the transform matrix
  18750. * @returns the current TransformNode
  18751. */
  18752. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18753. return this.setPivotMatrix(matrix, false);
  18754. };
  18755. /**
  18756. * Sets a new pivot matrix to the current node
  18757. * @param matrix defines the new pivot matrix to use
  18758. * @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
  18759. * @returns the current TransformNode
  18760. */
  18761. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18762. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18763. this._pivotMatrix = matrix.clone();
  18764. this._cache.pivotMatrixUpdated = true;
  18765. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18766. if (this._postMultiplyPivotMatrix) {
  18767. if (!this._pivotMatrixInverse) {
  18768. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18769. }
  18770. else {
  18771. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18772. }
  18773. }
  18774. return this;
  18775. };
  18776. /**
  18777. * Returns the mesh pivot matrix.
  18778. * Default : Identity.
  18779. * A Matrix is returned.
  18780. */
  18781. TransformNode.prototype.getPivotMatrix = function () {
  18782. return this._pivotMatrix;
  18783. };
  18784. /**
  18785. * Prevents the World matrix to be computed any longer.
  18786. * Returns the TransformNode.
  18787. */
  18788. TransformNode.prototype.freezeWorldMatrix = function () {
  18789. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18790. this.computeWorldMatrix(true);
  18791. this._isWorldMatrixFrozen = true;
  18792. return this;
  18793. };
  18794. /**
  18795. * Allows back the World matrix computation.
  18796. * Returns the TransformNode.
  18797. */
  18798. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18799. this._isWorldMatrixFrozen = false;
  18800. this.computeWorldMatrix(true);
  18801. return this;
  18802. };
  18803. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18804. /**
  18805. * True if the World matrix has been frozen.
  18806. * Returns a boolean.
  18807. */
  18808. get: function () {
  18809. return this._isWorldMatrixFrozen;
  18810. },
  18811. enumerable: true,
  18812. configurable: true
  18813. });
  18814. /**
  18815. * Retuns the mesh absolute position in the World.
  18816. * Returns a Vector3.
  18817. */
  18818. TransformNode.prototype.getAbsolutePosition = function () {
  18819. this.computeWorldMatrix();
  18820. return this._absolutePosition;
  18821. };
  18822. /**
  18823. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18824. * Returns the TransformNode.
  18825. */
  18826. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18827. if (!absolutePosition) {
  18828. return this;
  18829. }
  18830. var absolutePositionX;
  18831. var absolutePositionY;
  18832. var absolutePositionZ;
  18833. if (absolutePosition.x === undefined) {
  18834. if (arguments.length < 3) {
  18835. return this;
  18836. }
  18837. absolutePositionX = arguments[0];
  18838. absolutePositionY = arguments[1];
  18839. absolutePositionZ = arguments[2];
  18840. }
  18841. else {
  18842. absolutePositionX = absolutePosition.x;
  18843. absolutePositionY = absolutePosition.y;
  18844. absolutePositionZ = absolutePosition.z;
  18845. }
  18846. if (this.parent) {
  18847. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18848. invertParentWorldMatrix.invert();
  18849. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18850. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18851. }
  18852. else {
  18853. this.position.x = absolutePositionX;
  18854. this.position.y = absolutePositionY;
  18855. this.position.z = absolutePositionZ;
  18856. }
  18857. return this;
  18858. };
  18859. /**
  18860. * Sets the mesh position in its local space.
  18861. * Returns the TransformNode.
  18862. */
  18863. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18864. this.computeWorldMatrix();
  18865. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18866. return this;
  18867. };
  18868. /**
  18869. * Returns the mesh position in the local space from the current World matrix values.
  18870. * Returns a new Vector3.
  18871. */
  18872. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18873. this.computeWorldMatrix();
  18874. var invLocalWorldMatrix = this._localWorld.clone();
  18875. invLocalWorldMatrix.invert();
  18876. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18877. };
  18878. /**
  18879. * Translates the mesh along the passed Vector3 in its local space.
  18880. * Returns the TransformNode.
  18881. */
  18882. TransformNode.prototype.locallyTranslate = function (vector3) {
  18883. this.computeWorldMatrix(true);
  18884. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18885. return this;
  18886. };
  18887. /**
  18888. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18889. * @param targetPoint the position (must be in same space as current mesh) to look at
  18890. * @param yawCor optional yaw (y-axis) correction in radians
  18891. * @param pitchCor optional pitch (x-axis) correction in radians
  18892. * @param rollCor optional roll (z-axis) correction in radians
  18893. * @param space the choosen space of the target
  18894. * @returns the TransformNode.
  18895. */
  18896. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18897. if (yawCor === void 0) { yawCor = 0; }
  18898. if (pitchCor === void 0) { pitchCor = 0; }
  18899. if (rollCor === void 0) { rollCor = 0; }
  18900. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18901. var dv = TransformNode._lookAtVectorCache;
  18902. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18903. targetPoint.subtractToRef(pos, dv);
  18904. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18905. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18906. var pitch = Math.atan2(dv.y, len);
  18907. if (this.rotationQuaternion) {
  18908. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18909. }
  18910. else {
  18911. this.rotation.x = pitch + pitchCor;
  18912. this.rotation.y = yaw + yawCor;
  18913. this.rotation.z = rollCor;
  18914. }
  18915. return this;
  18916. };
  18917. /**
  18918. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18919. * This Vector3 is expressed in the World space.
  18920. */
  18921. TransformNode.prototype.getDirection = function (localAxis) {
  18922. var result = BABYLON.Vector3.Zero();
  18923. this.getDirectionToRef(localAxis, result);
  18924. return result;
  18925. };
  18926. /**
  18927. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18928. * localAxis is expressed in the mesh local space.
  18929. * result is computed in the Wordl space from the mesh World matrix.
  18930. * Returns the TransformNode.
  18931. */
  18932. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18933. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18934. return this;
  18935. };
  18936. /**
  18937. * Sets a new pivot point to the current node
  18938. * @param point defines the new pivot point to use
  18939. * @param space defines if the point is in world or local space (local by default)
  18940. * @returns the current TransformNode
  18941. */
  18942. TransformNode.prototype.setPivotPoint = function (point, space) {
  18943. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18944. if (this.getScene().getRenderId() == 0) {
  18945. this.computeWorldMatrix(true);
  18946. }
  18947. var wm = this.getWorldMatrix();
  18948. if (space == BABYLON.Space.WORLD) {
  18949. var tmat = BABYLON.Tmp.Matrix[0];
  18950. wm.invertToRef(tmat);
  18951. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18952. }
  18953. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18954. };
  18955. /**
  18956. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18957. */
  18958. TransformNode.prototype.getPivotPoint = function () {
  18959. var point = BABYLON.Vector3.Zero();
  18960. this.getPivotPointToRef(point);
  18961. return point;
  18962. };
  18963. /**
  18964. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18965. * Returns the TransformNode.
  18966. */
  18967. TransformNode.prototype.getPivotPointToRef = function (result) {
  18968. result.x = -this._pivotMatrix.m[12];
  18969. result.y = -this._pivotMatrix.m[13];
  18970. result.z = -this._pivotMatrix.m[14];
  18971. return this;
  18972. };
  18973. /**
  18974. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18975. */
  18976. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18977. var point = BABYLON.Vector3.Zero();
  18978. this.getAbsolutePivotPointToRef(point);
  18979. return point;
  18980. };
  18981. /**
  18982. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18983. * Returns the TransformNode.
  18984. */
  18985. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18986. result.x = this._pivotMatrix.m[12];
  18987. result.y = this._pivotMatrix.m[13];
  18988. result.z = this._pivotMatrix.m[14];
  18989. this.getPivotPointToRef(result);
  18990. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18991. return this;
  18992. };
  18993. /**
  18994. * Defines the passed node as the parent of the current node.
  18995. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18996. * Returns the TransformNode.
  18997. */
  18998. TransformNode.prototype.setParent = function (node) {
  18999. if (!node && !this.parent) {
  19000. return this;
  19001. }
  19002. if (!node) {
  19003. var rotation = BABYLON.Tmp.Quaternion[0];
  19004. var position = BABYLON.Tmp.Vector3[0];
  19005. var scale = BABYLON.Tmp.Vector3[1];
  19006. if (this.parent && this.parent.computeWorldMatrix) {
  19007. this.parent.computeWorldMatrix(true);
  19008. }
  19009. this.computeWorldMatrix(true);
  19010. this.getWorldMatrix().decompose(scale, rotation, position);
  19011. if (this.rotationQuaternion) {
  19012. this.rotationQuaternion.copyFrom(rotation);
  19013. }
  19014. else {
  19015. rotation.toEulerAnglesToRef(this.rotation);
  19016. }
  19017. this.scaling.x = scale.x;
  19018. this.scaling.y = scale.y;
  19019. this.scaling.z = scale.z;
  19020. this.position.x = position.x;
  19021. this.position.y = position.y;
  19022. this.position.z = position.z;
  19023. }
  19024. else {
  19025. var rotation = BABYLON.Tmp.Quaternion[0];
  19026. var position = BABYLON.Tmp.Vector3[0];
  19027. var scale = BABYLON.Tmp.Vector3[1];
  19028. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19029. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19030. this.computeWorldMatrix(true);
  19031. node.computeWorldMatrix(true);
  19032. node.getWorldMatrix().invertToRef(invParentMatrix);
  19033. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19034. diffMatrix.decompose(scale, rotation, position);
  19035. if (this.rotationQuaternion) {
  19036. this.rotationQuaternion.copyFrom(rotation);
  19037. }
  19038. else {
  19039. rotation.toEulerAnglesToRef(this.rotation);
  19040. }
  19041. this.position.x = position.x;
  19042. this.position.y = position.y;
  19043. this.position.z = position.z;
  19044. this.scaling.x = scale.x;
  19045. this.scaling.y = scale.y;
  19046. this.scaling.z = scale.z;
  19047. }
  19048. this.parent = node;
  19049. return this;
  19050. };
  19051. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19052. get: function () {
  19053. return this._nonUniformScaling;
  19054. },
  19055. enumerable: true,
  19056. configurable: true
  19057. });
  19058. /** @hidden */
  19059. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19060. if (this._nonUniformScaling === value) {
  19061. return false;
  19062. }
  19063. this._nonUniformScaling = value;
  19064. return true;
  19065. };
  19066. /**
  19067. * Attach the current TransformNode to another TransformNode associated with a bone
  19068. * @param bone Bone affecting the TransformNode
  19069. * @param affectedTransformNode TransformNode associated with the bone
  19070. */
  19071. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19072. this._transformToBoneReferal = affectedTransformNode;
  19073. this.parent = bone;
  19074. if (bone.getWorldMatrix().determinant() < 0) {
  19075. this.scalingDeterminant *= -1;
  19076. }
  19077. return this;
  19078. };
  19079. TransformNode.prototype.detachFromBone = function () {
  19080. if (!this.parent) {
  19081. return this;
  19082. }
  19083. if (this.parent.getWorldMatrix().determinant() < 0) {
  19084. this.scalingDeterminant *= -1;
  19085. }
  19086. this._transformToBoneReferal = null;
  19087. this.parent = null;
  19088. return this;
  19089. };
  19090. /**
  19091. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19092. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19093. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19094. * The passed axis is also normalized.
  19095. * Returns the TransformNode.
  19096. */
  19097. TransformNode.prototype.rotate = function (axis, amount, space) {
  19098. axis.normalize();
  19099. if (!this.rotationQuaternion) {
  19100. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19101. this.rotation = BABYLON.Vector3.Zero();
  19102. }
  19103. var rotationQuaternion;
  19104. if (!space || space === BABYLON.Space.LOCAL) {
  19105. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19106. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19107. }
  19108. else {
  19109. if (this.parent) {
  19110. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19111. invertParentWorldMatrix.invert();
  19112. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19113. }
  19114. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19115. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19116. }
  19117. return this;
  19118. };
  19119. /**
  19120. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19121. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19122. * The passed axis is also normalized.
  19123. * Returns the TransformNode.
  19124. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19125. */
  19126. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19127. axis.normalize();
  19128. if (!this.rotationQuaternion) {
  19129. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19130. this.rotation.copyFromFloats(0, 0, 0);
  19131. }
  19132. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19133. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19134. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19135. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19136. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19137. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19138. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19139. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19140. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19141. return this;
  19142. };
  19143. /**
  19144. * Translates the mesh along the axis vector for the passed distance in the given space.
  19145. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19146. * Returns the TransformNode.
  19147. */
  19148. TransformNode.prototype.translate = function (axis, distance, space) {
  19149. var displacementVector = axis.scale(distance);
  19150. if (!space || space === BABYLON.Space.LOCAL) {
  19151. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19152. this.setPositionWithLocalVector(tempV3);
  19153. }
  19154. else {
  19155. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19156. }
  19157. return this;
  19158. };
  19159. /**
  19160. * Adds a rotation step to the mesh current rotation.
  19161. * x, y, z are Euler angles expressed in radians.
  19162. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19163. * This means this rotation is made in the mesh local space only.
  19164. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19165. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19166. * ```javascript
  19167. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19168. * ```
  19169. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19170. * 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.
  19171. * Returns the TransformNode.
  19172. */
  19173. TransformNode.prototype.addRotation = function (x, y, z) {
  19174. var rotationQuaternion;
  19175. if (this.rotationQuaternion) {
  19176. rotationQuaternion = this.rotationQuaternion;
  19177. }
  19178. else {
  19179. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19180. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19181. }
  19182. var accumulation = BABYLON.Tmp.Quaternion[0];
  19183. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19184. rotationQuaternion.multiplyInPlace(accumulation);
  19185. if (!this.rotationQuaternion) {
  19186. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19187. }
  19188. return this;
  19189. };
  19190. /**
  19191. * Computes the mesh World matrix and returns it.
  19192. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19193. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19194. * If the parameter `force`is set to `true`, the actual computation is done.
  19195. * Returns the mesh World Matrix.
  19196. */
  19197. TransformNode.prototype.computeWorldMatrix = function (force) {
  19198. if (this._isWorldMatrixFrozen) {
  19199. return this._worldMatrix;
  19200. }
  19201. if (!force && this.isSynchronized(true)) {
  19202. this._currentRenderId = this.getScene().getRenderId();
  19203. return this._worldMatrix;
  19204. }
  19205. this._cache.position.copyFrom(this.position);
  19206. this._cache.scaling.copyFrom(this.scaling);
  19207. this._cache.pivotMatrixUpdated = false;
  19208. this._cache.billboardMode = this.billboardMode;
  19209. this._currentRenderId = this.getScene().getRenderId();
  19210. this._childRenderId = this.getScene().getRenderId();
  19211. this._isDirty = false;
  19212. // Scaling
  19213. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19214. // Rotation
  19215. //rotate, if quaternion is set and rotation was used
  19216. if (this.rotationQuaternion) {
  19217. var len = this.rotation.length();
  19218. if (len) {
  19219. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19220. this.rotation.copyFromFloats(0, 0, 0);
  19221. }
  19222. }
  19223. if (this.rotationQuaternion) {
  19224. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19225. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19226. }
  19227. else {
  19228. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19229. this._cache.rotation.copyFrom(this.rotation);
  19230. }
  19231. // Translation
  19232. var camera = this.getScene().activeCamera;
  19233. if (this.infiniteDistance && !this.parent && camera) {
  19234. var cameraWorldMatrix = camera.getWorldMatrix();
  19235. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19236. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19237. }
  19238. else {
  19239. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19240. }
  19241. // Composing transformations
  19242. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19243. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19244. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19245. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19246. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19247. // Need to decompose each rotation here
  19248. var currentPosition = BABYLON.Tmp.Vector3[3];
  19249. if (this.parent && this.parent.getWorldMatrix) {
  19250. if (this._transformToBoneReferal) {
  19251. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19252. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19253. }
  19254. else {
  19255. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19256. }
  19257. }
  19258. else {
  19259. currentPosition.copyFrom(this.position);
  19260. }
  19261. currentPosition.subtractInPlace(camera.globalPosition);
  19262. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19263. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19264. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19265. }
  19266. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19267. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19268. }
  19269. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19270. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19271. }
  19272. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19273. }
  19274. else {
  19275. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19276. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19277. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19278. }
  19279. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19280. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19281. }
  19282. // Post multiply inverse of pivotMatrix
  19283. if (this._postMultiplyPivotMatrix) {
  19284. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19285. }
  19286. // Local world
  19287. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19288. // Parent
  19289. if (this.parent && this.parent.getWorldMatrix) {
  19290. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19291. if (this._transformToBoneReferal) {
  19292. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19293. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19294. }
  19295. else {
  19296. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19297. }
  19298. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19299. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19300. this._worldMatrix.copyFrom(this._localWorld);
  19301. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19302. }
  19303. else {
  19304. if (this._transformToBoneReferal) {
  19305. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19306. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19307. }
  19308. else {
  19309. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19310. }
  19311. }
  19312. this._markSyncedWithParent();
  19313. }
  19314. else {
  19315. this._worldMatrix.copyFrom(this._localWorld);
  19316. }
  19317. // Normal matrix
  19318. if (!this.ignoreNonUniformScaling) {
  19319. if (this.scaling.isNonUniform) {
  19320. this._updateNonUniformScalingState(true);
  19321. }
  19322. else if (this.parent && this.parent._nonUniformScaling) {
  19323. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19324. }
  19325. else {
  19326. this._updateNonUniformScalingState(false);
  19327. }
  19328. }
  19329. else {
  19330. this._updateNonUniformScalingState(false);
  19331. }
  19332. this._afterComputeWorldMatrix();
  19333. // Absolute position
  19334. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19335. // Callbacks
  19336. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19337. if (!this._poseMatrix) {
  19338. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19339. }
  19340. // Cache the determinant
  19341. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19342. return this._worldMatrix;
  19343. };
  19344. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19345. };
  19346. /**
  19347. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19348. * @param func: callback function to add
  19349. *
  19350. * Returns the TransformNode.
  19351. */
  19352. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19353. this.onAfterWorldMatrixUpdateObservable.add(func);
  19354. return this;
  19355. };
  19356. /**
  19357. * Removes a registered callback function.
  19358. * Returns the TransformNode.
  19359. */
  19360. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19361. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19362. return this;
  19363. };
  19364. /**
  19365. * Clone the current transform node
  19366. * Returns the new transform node
  19367. * @param name Name of the new clone
  19368. * @param newParent New parent for the clone
  19369. * @param doNotCloneChildren Do not clone children hierarchy
  19370. */
  19371. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19372. var _this = this;
  19373. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19374. result.name = name;
  19375. result.id = name;
  19376. if (newParent) {
  19377. result.parent = newParent;
  19378. }
  19379. if (!doNotCloneChildren) {
  19380. // Children
  19381. var directDescendants = this.getDescendants(true);
  19382. for (var index = 0; index < directDescendants.length; index++) {
  19383. var child = directDescendants[index];
  19384. if (child.clone) {
  19385. child.clone(name + "." + child.name, result);
  19386. }
  19387. }
  19388. }
  19389. return result;
  19390. };
  19391. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19392. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19393. serializationObject.type = this.getClassName();
  19394. // Parent
  19395. if (this.parent) {
  19396. serializationObject.parentId = this.parent.id;
  19397. }
  19398. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19399. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19400. }
  19401. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19402. serializationObject.isEnabled = this.isEnabled();
  19403. // Parent
  19404. if (this.parent) {
  19405. serializationObject.parentId = this.parent.id;
  19406. }
  19407. return serializationObject;
  19408. };
  19409. // Statics
  19410. /**
  19411. * Returns a new TransformNode object parsed from the source provided.
  19412. * The parameter `parsedMesh` is the source.
  19413. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19414. */
  19415. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19416. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19417. if (BABYLON.Tags) {
  19418. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19419. }
  19420. if (parsedTransformNode.localMatrix) {
  19421. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19422. }
  19423. else if (parsedTransformNode.pivotMatrix) {
  19424. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19425. }
  19426. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19427. // Parent
  19428. if (parsedTransformNode.parentId) {
  19429. transformNode._waitingParentId = parsedTransformNode.parentId;
  19430. }
  19431. return transformNode;
  19432. };
  19433. /**
  19434. * Releases resources associated with this transform node.
  19435. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19436. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19437. */
  19438. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19439. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19440. // Animations
  19441. this.getScene().stopAnimation(this);
  19442. // Remove from scene
  19443. this.getScene().removeTransformNode(this);
  19444. this.onAfterWorldMatrixUpdateObservable.clear();
  19445. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19446. };
  19447. // Statics
  19448. TransformNode.BILLBOARDMODE_NONE = 0;
  19449. TransformNode.BILLBOARDMODE_X = 1;
  19450. TransformNode.BILLBOARDMODE_Y = 2;
  19451. TransformNode.BILLBOARDMODE_Z = 4;
  19452. TransformNode.BILLBOARDMODE_ALL = 7;
  19453. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19454. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19455. __decorate([
  19456. BABYLON.serializeAsVector3()
  19457. ], TransformNode.prototype, "_rotation", void 0);
  19458. __decorate([
  19459. BABYLON.serializeAsQuaternion()
  19460. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19461. __decorate([
  19462. BABYLON.serializeAsVector3()
  19463. ], TransformNode.prototype, "_scaling", void 0);
  19464. __decorate([
  19465. BABYLON.serialize()
  19466. ], TransformNode.prototype, "billboardMode", void 0);
  19467. __decorate([
  19468. BABYLON.serialize()
  19469. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19470. __decorate([
  19471. BABYLON.serialize()
  19472. ], TransformNode.prototype, "infiniteDistance", void 0);
  19473. __decorate([
  19474. BABYLON.serialize()
  19475. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19476. __decorate([
  19477. BABYLON.serializeAsVector3()
  19478. ], TransformNode.prototype, "position", void 0);
  19479. return TransformNode;
  19480. }(BABYLON.Node));
  19481. BABYLON.TransformNode = TransformNode;
  19482. })(BABYLON || (BABYLON = {}));
  19483. //# sourceMappingURL=babylon.transformNode.js.map
  19484. var BABYLON;
  19485. (function (BABYLON) {
  19486. /**
  19487. * Class used to store all common mesh properties
  19488. */
  19489. var AbstractMesh = /** @class */ (function (_super) {
  19490. __extends(AbstractMesh, _super);
  19491. // Constructor
  19492. /**
  19493. * Creates a new AbstractMesh
  19494. * @param name defines the name of the mesh
  19495. * @param scene defines the hosting scene
  19496. */
  19497. function AbstractMesh(name, scene) {
  19498. if (scene === void 0) { scene = null; }
  19499. var _this = _super.call(this, name, scene, false) || this;
  19500. _this._facetNb = 0; // facet number
  19501. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19502. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19503. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19504. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19505. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19506. _this._subDiv = {
  19507. max: 1,
  19508. X: 1,
  19509. Y: 1,
  19510. Z: 1
  19511. };
  19512. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19513. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19514. /** Gets ot sets the culling strategy to use to find visible meshes */
  19515. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19516. // Events
  19517. /**
  19518. * An event triggered when this mesh collides with another one
  19519. */
  19520. _this.onCollideObservable = new BABYLON.Observable();
  19521. /**
  19522. * An event triggered when the collision's position changes
  19523. */
  19524. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19525. /**
  19526. * An event triggered when material is changed
  19527. */
  19528. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19529. // Properties
  19530. /**
  19531. * Gets or sets the orientation for POV movement & rotation
  19532. */
  19533. _this.definedFacingForward = true;
  19534. /**
  19535. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19536. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19537. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  19538. * @see http://doc.babylonjs.com/features/occlusionquery
  19539. */
  19540. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19541. /**
  19542. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  19543. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19544. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19545. * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  19546. * @see http://doc.babylonjs.com/features/occlusionquery
  19547. */
  19548. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19549. /**
  19550. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  19551. * The default value is -1 which means don't break the query and wait till the result
  19552. * @see http://doc.babylonjs.com/features/occlusionquery
  19553. */
  19554. _this.occlusionRetryCount = -1;
  19555. /** @hidden */
  19556. _this._occlusionInternalRetryCounter = 0;
  19557. /** @hidden */
  19558. _this._isOccluded = false;
  19559. /** @hidden */
  19560. _this._isOcclusionQueryInProgress = false;
  19561. _this._visibility = 1.0;
  19562. /** Gets or sets the alpha index used to sort transparent meshes
  19563. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19564. */
  19565. _this.alphaIndex = Number.MAX_VALUE;
  19566. /**
  19567. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19568. */
  19569. _this.isVisible = true;
  19570. /**
  19571. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19572. */
  19573. _this.isPickable = true;
  19574. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19575. _this.showSubMeshesBoundingBox = false;
  19576. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19577. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19578. */
  19579. _this.isBlocker = false;
  19580. /**
  19581. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19582. */
  19583. _this.enablePointerMoveEvents = false;
  19584. /**
  19585. * Specifies the rendering group id for this mesh (0 by default)
  19586. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19587. */
  19588. _this.renderingGroupId = 0;
  19589. _this._receiveShadows = false;
  19590. /** Defines color to use when rendering outline */
  19591. _this.outlineColor = BABYLON.Color3.Red();
  19592. /** Define width to use when rendering outline */
  19593. _this.outlineWidth = 0.02;
  19594. /** Defines color to use when rendering overlay */
  19595. _this.overlayColor = BABYLON.Color3.Red();
  19596. /** Defines alpha to use when rendering overlay */
  19597. _this.overlayAlpha = 0.5;
  19598. _this._hasVertexAlpha = false;
  19599. _this._useVertexColors = true;
  19600. _this._computeBonesUsingShaders = true;
  19601. _this._numBoneInfluencers = 4;
  19602. _this._applyFog = true;
  19603. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19604. _this.useOctreeForRenderingSelection = true;
  19605. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19606. _this.useOctreeForPicking = true;
  19607. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19608. _this.useOctreeForCollisions = true;
  19609. _this._layerMask = 0x0FFFFFFF;
  19610. /**
  19611. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19612. */
  19613. _this.alwaysSelectAsActiveMesh = false;
  19614. /**
  19615. * Gets or sets the current action manager
  19616. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19617. */
  19618. _this.actionManager = null;
  19619. /**
  19620. * Gets or sets impostor used for physic simulation
  19621. * @see http://doc.babylonjs.com/features/physics_engine
  19622. */
  19623. _this.physicsImpostor = null;
  19624. // Collisions
  19625. _this._checkCollisions = false;
  19626. _this._collisionMask = -1;
  19627. _this._collisionGroup = -1;
  19628. /**
  19629. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19630. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19631. */
  19632. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19633. /**
  19634. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19635. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19636. */
  19637. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19638. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19639. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19640. // Edges
  19641. /**
  19642. * Defines edge width used when edgesRenderer is enabled
  19643. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19644. */
  19645. _this.edgesWidth = 1;
  19646. /**
  19647. * Defines edge color used when edgesRenderer is enabled
  19648. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19649. */
  19650. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19651. // Cache
  19652. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19653. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19654. /** @hidden */
  19655. _this._renderId = 0;
  19656. /** @hidden */
  19657. _this._intersectionsInProgress = new Array();
  19658. /** @hidden */
  19659. _this._unIndexed = false;
  19660. /** @hidden */
  19661. _this._lightSources = new Array();
  19662. /**
  19663. * An event triggered when the mesh is rebuilt.
  19664. */
  19665. _this.onRebuildObservable = new BABYLON.Observable();
  19666. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19667. if (collidedMesh === void 0) { collidedMesh = null; }
  19668. //TODO move this to the collision coordinator!
  19669. if (_this.getScene().workerCollisions)
  19670. newPosition.multiplyInPlace(_this._collider._radius);
  19671. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19672. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19673. _this.position.addInPlace(_this._diffPositionForCollisions);
  19674. }
  19675. if (collidedMesh) {
  19676. _this.onCollideObservable.notifyObservers(collidedMesh);
  19677. }
  19678. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19679. };
  19680. _this.getScene().addMesh(_this);
  19681. _this._resyncLightSources();
  19682. return _this;
  19683. }
  19684. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19685. /**
  19686. * No billboard
  19687. */
  19688. get: function () {
  19689. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19690. },
  19691. enumerable: true,
  19692. configurable: true
  19693. });
  19694. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19695. /** Billboard on X axis */
  19696. get: function () {
  19697. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19698. },
  19699. enumerable: true,
  19700. configurable: true
  19701. });
  19702. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19703. /** Billboard on Y axis */
  19704. get: function () {
  19705. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19706. },
  19707. enumerable: true,
  19708. configurable: true
  19709. });
  19710. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19711. /** Billboard on Z axis */
  19712. get: function () {
  19713. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19714. },
  19715. enumerable: true,
  19716. configurable: true
  19717. });
  19718. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19719. /** Billboard on all axes */
  19720. get: function () {
  19721. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19722. },
  19723. enumerable: true,
  19724. configurable: true
  19725. });
  19726. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19727. /**
  19728. * Gets the number of facets in the mesh
  19729. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19730. */
  19731. get: function () {
  19732. return this._facetNb;
  19733. },
  19734. enumerable: true,
  19735. configurable: true
  19736. });
  19737. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19738. /**
  19739. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19740. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19741. */
  19742. get: function () {
  19743. return this._partitioningSubdivisions;
  19744. },
  19745. set: function (nb) {
  19746. this._partitioningSubdivisions = nb;
  19747. },
  19748. enumerable: true,
  19749. configurable: true
  19750. });
  19751. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19752. /**
  19753. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19754. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19755. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19756. */
  19757. get: function () {
  19758. return this._partitioningBBoxRatio;
  19759. },
  19760. set: function (ratio) {
  19761. this._partitioningBBoxRatio = ratio;
  19762. },
  19763. enumerable: true,
  19764. configurable: true
  19765. });
  19766. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19767. /**
  19768. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19769. * Works only for updatable meshes.
  19770. * Doesn't work with multi-materials
  19771. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19772. */
  19773. get: function () {
  19774. return this._facetDepthSort;
  19775. },
  19776. set: function (sort) {
  19777. this._facetDepthSort = sort;
  19778. },
  19779. enumerable: true,
  19780. configurable: true
  19781. });
  19782. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19783. /**
  19784. * The location (Vector3) where the facet depth sort must be computed from.
  19785. * By default, the active camera position.
  19786. * Used only when facet depth sort is enabled
  19787. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19788. */
  19789. get: function () {
  19790. return this._facetDepthSortFrom;
  19791. },
  19792. set: function (location) {
  19793. this._facetDepthSortFrom = location;
  19794. },
  19795. enumerable: true,
  19796. configurable: true
  19797. });
  19798. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19799. /**
  19800. * gets a boolean indicating if facetData is enabled
  19801. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19802. */
  19803. get: function () {
  19804. return this._facetDataEnabled;
  19805. },
  19806. enumerable: true,
  19807. configurable: true
  19808. });
  19809. /** @hidden */
  19810. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19811. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19812. return false;
  19813. }
  19814. this._markSubMeshesAsMiscDirty();
  19815. return true;
  19816. };
  19817. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19818. /** Set a function to call when this mesh collides with another one */
  19819. set: function (callback) {
  19820. if (this._onCollideObserver) {
  19821. this.onCollideObservable.remove(this._onCollideObserver);
  19822. }
  19823. this._onCollideObserver = this.onCollideObservable.add(callback);
  19824. },
  19825. enumerable: true,
  19826. configurable: true
  19827. });
  19828. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19829. /** Set a function to call when the collision's position changes */
  19830. set: function (callback) {
  19831. if (this._onCollisionPositionChangeObserver) {
  19832. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19833. }
  19834. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19840. /**
  19841. * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not
  19842. * @see http://doc.babylonjs.com/features/occlusionquery
  19843. */
  19844. get: function () {
  19845. return this._isOccluded;
  19846. },
  19847. set: function (value) {
  19848. this._isOccluded = value;
  19849. },
  19850. enumerable: true,
  19851. configurable: true
  19852. });
  19853. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19854. /**
  19855. * Flag to check the progress status of the query
  19856. * @see http://doc.babylonjs.com/features/occlusionquery
  19857. */
  19858. get: function () {
  19859. return this._isOcclusionQueryInProgress;
  19860. },
  19861. enumerable: true,
  19862. configurable: true
  19863. });
  19864. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19865. /**
  19866. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19867. */
  19868. get: function () {
  19869. return this._visibility;
  19870. },
  19871. /**
  19872. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19873. */
  19874. set: function (value) {
  19875. if (this._visibility === value) {
  19876. return;
  19877. }
  19878. this._visibility = value;
  19879. this._markSubMeshesAsMiscDirty();
  19880. },
  19881. enumerable: true,
  19882. configurable: true
  19883. });
  19884. Object.defineProperty(AbstractMesh.prototype, "material", {
  19885. /** Gets or sets current material */
  19886. get: function () {
  19887. return this._material;
  19888. },
  19889. set: function (value) {
  19890. if (this._material === value) {
  19891. return;
  19892. }
  19893. this._material = value;
  19894. if (this.onMaterialChangedObservable.hasObservers) {
  19895. this.onMaterialChangedObservable.notifyObservers(this);
  19896. }
  19897. if (!this.subMeshes) {
  19898. return;
  19899. }
  19900. this._unBindEffect();
  19901. },
  19902. enumerable: true,
  19903. configurable: true
  19904. });
  19905. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19906. /**
  19907. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19908. * @see http://doc.babylonjs.com/babylon101/shadows
  19909. */
  19910. get: function () {
  19911. return this._receiveShadows;
  19912. },
  19913. set: function (value) {
  19914. if (this._receiveShadows === value) {
  19915. return;
  19916. }
  19917. this._receiveShadows = value;
  19918. this._markSubMeshesAsLightDirty();
  19919. },
  19920. enumerable: true,
  19921. configurable: true
  19922. });
  19923. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19924. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19925. get: function () {
  19926. return this._hasVertexAlpha;
  19927. },
  19928. set: function (value) {
  19929. if (this._hasVertexAlpha === value) {
  19930. return;
  19931. }
  19932. this._hasVertexAlpha = value;
  19933. this._markSubMeshesAsAttributesDirty();
  19934. this._markSubMeshesAsMiscDirty();
  19935. },
  19936. enumerable: true,
  19937. configurable: true
  19938. });
  19939. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19940. /** 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) */
  19941. get: function () {
  19942. return this._useVertexColors;
  19943. },
  19944. set: function (value) {
  19945. if (this._useVertexColors === value) {
  19946. return;
  19947. }
  19948. this._useVertexColors = value;
  19949. this._markSubMeshesAsAttributesDirty();
  19950. },
  19951. enumerable: true,
  19952. configurable: true
  19953. });
  19954. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19955. /**
  19956. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19957. */
  19958. get: function () {
  19959. return this._computeBonesUsingShaders;
  19960. },
  19961. set: function (value) {
  19962. if (this._computeBonesUsingShaders === value) {
  19963. return;
  19964. }
  19965. this._computeBonesUsingShaders = value;
  19966. this._markSubMeshesAsAttributesDirty();
  19967. },
  19968. enumerable: true,
  19969. configurable: true
  19970. });
  19971. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19972. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19973. get: function () {
  19974. return this._numBoneInfluencers;
  19975. },
  19976. set: function (value) {
  19977. if (this._numBoneInfluencers === value) {
  19978. return;
  19979. }
  19980. this._numBoneInfluencers = value;
  19981. this._markSubMeshesAsAttributesDirty();
  19982. },
  19983. enumerable: true,
  19984. configurable: true
  19985. });
  19986. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19987. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19988. get: function () {
  19989. return this._applyFog;
  19990. },
  19991. set: function (value) {
  19992. if (this._applyFog === value) {
  19993. return;
  19994. }
  19995. this._applyFog = value;
  19996. this._markSubMeshesAsMiscDirty();
  19997. },
  19998. enumerable: true,
  19999. configurable: true
  20000. });
  20001. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20002. /**
  20003. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20004. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20005. */
  20006. get: function () {
  20007. return this._layerMask;
  20008. },
  20009. set: function (value) {
  20010. if (value === this._layerMask) {
  20011. return;
  20012. }
  20013. this._layerMask = value;
  20014. this._resyncLightSources();
  20015. },
  20016. enumerable: true,
  20017. configurable: true
  20018. });
  20019. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20020. /**
  20021. * Gets or sets a collision mask used to mask collisions (default is -1).
  20022. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20023. */
  20024. get: function () {
  20025. return this._collisionMask;
  20026. },
  20027. set: function (mask) {
  20028. this._collisionMask = !isNaN(mask) ? mask : -1;
  20029. },
  20030. enumerable: true,
  20031. configurable: true
  20032. });
  20033. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20034. /**
  20035. * Gets or sets the current collision group mask (-1 by default).
  20036. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20037. */
  20038. get: function () {
  20039. return this._collisionGroup;
  20040. },
  20041. set: function (mask) {
  20042. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20043. },
  20044. enumerable: true,
  20045. configurable: true
  20046. });
  20047. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20048. /** @hidden */
  20049. get: function () {
  20050. return null;
  20051. },
  20052. enumerable: true,
  20053. configurable: true
  20054. });
  20055. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20056. get: function () {
  20057. return this._skeleton;
  20058. },
  20059. /**
  20060. * Gets or sets a skeleton to apply skining transformations
  20061. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20062. */
  20063. set: function (value) {
  20064. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20065. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20066. }
  20067. if (value && value.needInitialSkinMatrix) {
  20068. value._registerMeshWithPoseMatrix(this);
  20069. }
  20070. this._skeleton = value;
  20071. if (!this._skeleton) {
  20072. this._bonesTransformMatrices = null;
  20073. }
  20074. this._markSubMeshesAsAttributesDirty();
  20075. },
  20076. enumerable: true,
  20077. configurable: true
  20078. });
  20079. /**
  20080. * Returns the string "AbstractMesh"
  20081. * @returns "AbstractMesh"
  20082. */
  20083. AbstractMesh.prototype.getClassName = function () {
  20084. return "AbstractMesh";
  20085. };
  20086. /**
  20087. * Gets a string representation of the current mesh
  20088. * @param fullDetails defines a boolean indicating if full details must be included
  20089. * @returns a string representation of the current mesh
  20090. */
  20091. AbstractMesh.prototype.toString = function (fullDetails) {
  20092. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20093. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20094. if (this._skeleton) {
  20095. ret += ", skeleton: " + this._skeleton.name;
  20096. }
  20097. if (fullDetails) {
  20098. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20099. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20100. }
  20101. return ret;
  20102. };
  20103. /** @hidden */
  20104. AbstractMesh.prototype._rebuild = function () {
  20105. this.onRebuildObservable.notifyObservers(this);
  20106. if (this._occlusionQuery) {
  20107. this._occlusionQuery = null;
  20108. }
  20109. if (!this.subMeshes) {
  20110. return;
  20111. }
  20112. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20113. var subMesh = _a[_i];
  20114. subMesh._rebuild();
  20115. }
  20116. };
  20117. /** @hidden */
  20118. AbstractMesh.prototype._resyncLightSources = function () {
  20119. this._lightSources.length = 0;
  20120. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20121. var light = _a[_i];
  20122. if (!light.isEnabled()) {
  20123. continue;
  20124. }
  20125. if (light.canAffectMesh(this)) {
  20126. this._lightSources.push(light);
  20127. }
  20128. }
  20129. this._markSubMeshesAsLightDirty();
  20130. };
  20131. /** @hidden */
  20132. AbstractMesh.prototype._resyncLighSource = function (light) {
  20133. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20134. var index = this._lightSources.indexOf(light);
  20135. if (index === -1) {
  20136. if (!isIn) {
  20137. return;
  20138. }
  20139. this._lightSources.push(light);
  20140. }
  20141. else {
  20142. if (isIn) {
  20143. return;
  20144. }
  20145. this._lightSources.splice(index, 1);
  20146. }
  20147. this._markSubMeshesAsLightDirty();
  20148. };
  20149. /** @hidden */
  20150. AbstractMesh.prototype._unBindEffect = function () {
  20151. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20152. var subMesh = _a[_i];
  20153. subMesh.setEffect(null);
  20154. }
  20155. };
  20156. /** @hidden */
  20157. AbstractMesh.prototype._removeLightSource = function (light) {
  20158. var index = this._lightSources.indexOf(light);
  20159. if (index === -1) {
  20160. return;
  20161. }
  20162. this._lightSources.splice(index, 1);
  20163. this._markSubMeshesAsLightDirty();
  20164. };
  20165. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20166. if (!this.subMeshes) {
  20167. return;
  20168. }
  20169. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20170. var subMesh = _a[_i];
  20171. if (subMesh._materialDefines) {
  20172. func(subMesh._materialDefines);
  20173. }
  20174. }
  20175. };
  20176. /** @hidden */
  20177. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20178. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20179. };
  20180. /** @hidden */
  20181. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20182. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20183. };
  20184. /** @hidden */
  20185. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20186. if (!this.subMeshes) {
  20187. return;
  20188. }
  20189. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20190. var subMesh = _a[_i];
  20191. var material = subMesh.getMaterial();
  20192. if (material) {
  20193. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20194. }
  20195. }
  20196. };
  20197. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20198. /**
  20199. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20200. */
  20201. get: function () {
  20202. return this._scaling;
  20203. },
  20204. set: function (newScaling) {
  20205. this._scaling = newScaling;
  20206. if (this.physicsImpostor) {
  20207. this.physicsImpostor.forceUpdate();
  20208. }
  20209. },
  20210. enumerable: true,
  20211. configurable: true
  20212. });
  20213. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20214. // Methods
  20215. /**
  20216. * Returns true if the mesh is blocked. Implemented by child classes
  20217. */
  20218. get: function () {
  20219. return false;
  20220. },
  20221. enumerable: true,
  20222. configurable: true
  20223. });
  20224. /**
  20225. * Returns the mesh itself by default. Implemented by child classes
  20226. * @param camera defines the camera to use to pick the right LOD level
  20227. * @returns the currentAbstractMesh
  20228. */
  20229. AbstractMesh.prototype.getLOD = function (camera) {
  20230. return this;
  20231. };
  20232. /**
  20233. * Returns 0 by default. Implemented by child classes
  20234. * @returns an integer
  20235. */
  20236. AbstractMesh.prototype.getTotalVertices = function () {
  20237. return 0;
  20238. };
  20239. /**
  20240. * Returns null by default. Implemented by child classes
  20241. * @returns null
  20242. */
  20243. AbstractMesh.prototype.getIndices = function () {
  20244. return null;
  20245. };
  20246. /**
  20247. * Returns the array of the requested vertex data kind. Implemented by child classes
  20248. * @param kind defines the vertex data kind to use
  20249. * @returns null
  20250. */
  20251. AbstractMesh.prototype.getVerticesData = function (kind) {
  20252. return null;
  20253. };
  20254. /**
  20255. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20256. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20257. * Note that a new underlying VertexBuffer object is created each call.
  20258. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20259. * @param kind defines vertex data kind:
  20260. * * BABYLON.VertexBuffer.PositionKind
  20261. * * BABYLON.VertexBuffer.UVKind
  20262. * * BABYLON.VertexBuffer.UV2Kind
  20263. * * BABYLON.VertexBuffer.UV3Kind
  20264. * * BABYLON.VertexBuffer.UV4Kind
  20265. * * BABYLON.VertexBuffer.UV5Kind
  20266. * * BABYLON.VertexBuffer.UV6Kind
  20267. * * BABYLON.VertexBuffer.ColorKind
  20268. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20269. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20270. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20271. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20272. * @param data defines the data source
  20273. * @param updatable defines if the data must be flagged as updatable (or static)
  20274. * @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
  20275. * @returns the current mesh
  20276. */
  20277. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20278. return this;
  20279. };
  20280. /**
  20281. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20282. * If the mesh has no geometry, it is simply returned as it is.
  20283. * @param kind defines vertex data kind:
  20284. * * BABYLON.VertexBuffer.PositionKind
  20285. * * BABYLON.VertexBuffer.UVKind
  20286. * * BABYLON.VertexBuffer.UV2Kind
  20287. * * BABYLON.VertexBuffer.UV3Kind
  20288. * * BABYLON.VertexBuffer.UV4Kind
  20289. * * BABYLON.VertexBuffer.UV5Kind
  20290. * * BABYLON.VertexBuffer.UV6Kind
  20291. * * BABYLON.VertexBuffer.ColorKind
  20292. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20293. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20294. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20295. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20296. * @param data defines the data source
  20297. * @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
  20298. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20299. * @returns the current mesh
  20300. */
  20301. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20302. return this;
  20303. };
  20304. /**
  20305. * Sets the mesh indices,
  20306. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20307. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20308. * @param totalVertices Defines the total number of vertices
  20309. * @returns the current mesh
  20310. */
  20311. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20312. return this;
  20313. };
  20314. /**
  20315. * Gets a boolean indicating if specific vertex data is present
  20316. * @param kind defines the vertex data kind to use
  20317. * @returns true is data kind is present
  20318. */
  20319. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20320. return false;
  20321. };
  20322. /**
  20323. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20324. * @returns a BoundingInfo
  20325. */
  20326. AbstractMesh.prototype.getBoundingInfo = function () {
  20327. if (this._masterMesh) {
  20328. return this._masterMesh.getBoundingInfo();
  20329. }
  20330. if (!this._boundingInfo) {
  20331. // this._boundingInfo is being created here
  20332. this._updateBoundingInfo();
  20333. }
  20334. // cannot be null.
  20335. return this._boundingInfo;
  20336. };
  20337. /**
  20338. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20339. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20340. * @returns the current mesh
  20341. */
  20342. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20343. if (includeDescendants === void 0) { includeDescendants = true; }
  20344. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20345. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20346. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20347. if (maxDimension === 0) {
  20348. return this;
  20349. }
  20350. var scale = 1 / maxDimension;
  20351. this.scaling.scaleInPlace(scale);
  20352. return this;
  20353. };
  20354. /**
  20355. * Overwrite the current bounding info
  20356. * @param boundingInfo defines the new bounding info
  20357. * @returns the current mesh
  20358. */
  20359. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20360. this._boundingInfo = boundingInfo;
  20361. return this;
  20362. };
  20363. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20364. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20365. get: function () {
  20366. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20367. },
  20368. enumerable: true,
  20369. configurable: true
  20370. });
  20371. /** @hidden */
  20372. AbstractMesh.prototype._preActivate = function () {
  20373. };
  20374. /** @hidden */
  20375. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20376. };
  20377. /** @hidden */
  20378. AbstractMesh.prototype._activate = function (renderId) {
  20379. this._renderId = renderId;
  20380. };
  20381. /**
  20382. * Gets the current world matrix
  20383. * @returns a Matrix
  20384. */
  20385. AbstractMesh.prototype.getWorldMatrix = function () {
  20386. if (this._masterMesh) {
  20387. return this._masterMesh.getWorldMatrix();
  20388. }
  20389. return _super.prototype.getWorldMatrix.call(this);
  20390. };
  20391. /** @hidden */
  20392. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20393. if (this._masterMesh) {
  20394. return this._masterMesh._getWorldMatrixDeterminant();
  20395. }
  20396. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20397. };
  20398. // ================================== Point of View Movement =================================
  20399. /**
  20400. * Perform relative position change from the point of view of behind the front of the mesh.
  20401. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20402. * Supports definition of mesh facing forward or backward
  20403. * @param amountRight defines the distance on the right axis
  20404. * @param amountUp defines the distance on the up axis
  20405. * @param amountForward defines the distance on the forward axis
  20406. * @returns the current mesh
  20407. */
  20408. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20409. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20410. return this;
  20411. };
  20412. /**
  20413. * Calculate relative position change from the point of view of behind the front of the mesh.
  20414. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20415. * Supports definition of mesh facing forward or backward
  20416. * @param amountRight defines the distance on the right axis
  20417. * @param amountUp defines the distance on the up axis
  20418. * @param amountForward defines the distance on the forward axis
  20419. * @returns the new displacement vector
  20420. */
  20421. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20422. var rotMatrix = new BABYLON.Matrix();
  20423. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20424. rotQuaternion.toRotationMatrix(rotMatrix);
  20425. var translationDelta = BABYLON.Vector3.Zero();
  20426. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20427. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20428. return translationDelta;
  20429. };
  20430. // ================================== Point of View Rotation =================================
  20431. /**
  20432. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20433. * Supports definition of mesh facing forward or backward
  20434. * @param flipBack defines the flip
  20435. * @param twirlClockwise defines the twirl
  20436. * @param tiltRight defines the tilt
  20437. * @returns the current mesh
  20438. */
  20439. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20440. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20441. return this;
  20442. };
  20443. /**
  20444. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20445. * Supports definition of mesh facing forward or backward.
  20446. * @param flipBack defines the flip
  20447. * @param twirlClockwise defines the twirl
  20448. * @param tiltRight defines the tilt
  20449. * @returns the new rotation vector
  20450. */
  20451. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20452. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20453. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20454. };
  20455. /**
  20456. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20457. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20458. * @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
  20459. * @returns the new bounding vectors
  20460. */
  20461. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20462. if (includeDescendants === void 0) { includeDescendants = true; }
  20463. if (predicate === void 0) { predicate = null; }
  20464. // Ensures that all world matrix will be recomputed.
  20465. this.getScene().incrementRenderId();
  20466. this.computeWorldMatrix(true);
  20467. var min;
  20468. var max;
  20469. var boundingInfo = this.getBoundingInfo();
  20470. if (!this.subMeshes) {
  20471. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20472. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20473. }
  20474. else {
  20475. min = boundingInfo.boundingBox.minimumWorld;
  20476. max = boundingInfo.boundingBox.maximumWorld;
  20477. }
  20478. if (includeDescendants) {
  20479. var descendants = this.getDescendants(false);
  20480. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20481. var descendant = descendants_1[_i];
  20482. var childMesh = descendant;
  20483. childMesh.computeWorldMatrix(true);
  20484. // Filters meshes based on custom predicate function.
  20485. if (predicate && !predicate(childMesh)) {
  20486. continue;
  20487. }
  20488. //make sure we have the needed params to get mix and max
  20489. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20490. continue;
  20491. }
  20492. var childBoundingInfo = childMesh.getBoundingInfo();
  20493. var boundingBox = childBoundingInfo.boundingBox;
  20494. var minBox = boundingBox.minimumWorld;
  20495. var maxBox = boundingBox.maximumWorld;
  20496. BABYLON.Tools.CheckExtends(minBox, min, max);
  20497. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20498. }
  20499. }
  20500. return {
  20501. min: min,
  20502. max: max
  20503. };
  20504. };
  20505. /** @hidden */
  20506. AbstractMesh.prototype._updateBoundingInfo = function () {
  20507. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20508. this._boundingInfo.update(this.worldMatrixFromCache);
  20509. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20510. return this;
  20511. };
  20512. /** @hidden */
  20513. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20514. if (!this.subMeshes) {
  20515. return this;
  20516. }
  20517. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20518. var subMesh = this.subMeshes[subIndex];
  20519. if (!subMesh.IsGlobal) {
  20520. subMesh.updateBoundingInfo(matrix);
  20521. }
  20522. }
  20523. return this;
  20524. };
  20525. /** @hidden */
  20526. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20527. // Bounding info
  20528. this._updateBoundingInfo();
  20529. };
  20530. /**
  20531. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20532. * A mesh is in the frustum if its bounding box intersects the frustum
  20533. * @param frustumPlanes defines the frustum to test
  20534. * @returns true if the mesh is in the frustum planes
  20535. */
  20536. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20537. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20538. };
  20539. /**
  20540. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20541. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20542. * @param frustumPlanes defines the frustum to test
  20543. * @returns true if the mesh is completely in the frustum planes
  20544. */
  20545. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20546. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20547. };
  20548. /**
  20549. * True if the mesh intersects another mesh or a SolidParticle object
  20550. * @param mesh defines a target mesh or SolidParticle to test
  20551. * @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)
  20552. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20553. * @returns true if there is an intersection
  20554. */
  20555. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20556. if (precise === void 0) { precise = false; }
  20557. if (!this._boundingInfo || !mesh._boundingInfo) {
  20558. return false;
  20559. }
  20560. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20561. return true;
  20562. }
  20563. if (includeDescendants) {
  20564. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20565. var child = _a[_i];
  20566. if (child.intersectsMesh(mesh, precise, true)) {
  20567. return true;
  20568. }
  20569. }
  20570. }
  20571. return false;
  20572. };
  20573. /**
  20574. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20575. * @param point defines the point to test
  20576. * @returns true if there is an intersection
  20577. */
  20578. AbstractMesh.prototype.intersectsPoint = function (point) {
  20579. if (!this._boundingInfo) {
  20580. return false;
  20581. }
  20582. return this._boundingInfo.intersectsPoint(point);
  20583. };
  20584. /**
  20585. * Gets the current physics impostor
  20586. * @see http://doc.babylonjs.com/features/physics_engine
  20587. * @returns a physics impostor or null
  20588. */
  20589. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20590. return this.physicsImpostor;
  20591. };
  20592. /**
  20593. * Gets the position of the current mesh in camera space
  20594. * @param camera defines the camera to use
  20595. * @returns a position
  20596. */
  20597. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20598. if (camera === void 0) { camera = null; }
  20599. if (!camera) {
  20600. camera = this.getScene().activeCamera;
  20601. }
  20602. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20603. };
  20604. /**
  20605. * Returns the distance from the mesh to the active camera
  20606. * @param camera defines the camera to use
  20607. * @returns the distance
  20608. */
  20609. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20610. if (camera === void 0) { camera = null; }
  20611. if (!camera) {
  20612. camera = this.getScene().activeCamera;
  20613. }
  20614. return this.absolutePosition.subtract(camera.position).length();
  20615. };
  20616. /**
  20617. * Apply a physic impulse to the mesh
  20618. * @param force defines the force to apply
  20619. * @param contactPoint defines where to apply the force
  20620. * @returns the current mesh
  20621. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20622. */
  20623. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20624. if (!this.physicsImpostor) {
  20625. return this;
  20626. }
  20627. this.physicsImpostor.applyImpulse(force, contactPoint);
  20628. return this;
  20629. };
  20630. /**
  20631. * Creates a physic joint between two meshes
  20632. * @param otherMesh defines the other mesh to use
  20633. * @param pivot1 defines the pivot to use on this mesh
  20634. * @param pivot2 defines the pivot to use on the other mesh
  20635. * @param options defines additional options (can be plugin dependent)
  20636. * @returns the current mesh
  20637. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20638. */
  20639. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20640. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20641. return this;
  20642. }
  20643. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20644. mainPivot: pivot1,
  20645. connectedPivot: pivot2,
  20646. nativeParams: options
  20647. });
  20648. return this;
  20649. };
  20650. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20651. // Collisions
  20652. /**
  20653. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20654. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20655. */
  20656. get: function () {
  20657. return this._checkCollisions;
  20658. },
  20659. set: function (collisionEnabled) {
  20660. this._checkCollisions = collisionEnabled;
  20661. if (this.getScene().workerCollisions) {
  20662. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20663. }
  20664. },
  20665. enumerable: true,
  20666. configurable: true
  20667. });
  20668. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20669. /**
  20670. * Gets Collider object used to compute collisions (not physics)
  20671. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20672. */
  20673. get: function () {
  20674. return this._collider;
  20675. },
  20676. enumerable: true,
  20677. configurable: true
  20678. });
  20679. /**
  20680. * Move the mesh using collision engine
  20681. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20682. * @param displacement defines the requested displacement vector
  20683. * @returns the current mesh
  20684. */
  20685. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20686. var globalPosition = this.getAbsolutePosition();
  20687. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20688. if (!this._collider) {
  20689. this._collider = new BABYLON.Collider();
  20690. }
  20691. this._collider._radius = this.ellipsoid;
  20692. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20693. return this;
  20694. };
  20695. // Submeshes octree
  20696. /**
  20697. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20698. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20699. * @param maxCapacity defines the maximum size of each block (64 by default)
  20700. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20701. * @returns the new octree
  20702. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20703. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20704. */
  20705. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20706. if (maxCapacity === void 0) { maxCapacity = 64; }
  20707. if (maxDepth === void 0) { maxDepth = 2; }
  20708. if (!this._submeshesOctree) {
  20709. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20710. }
  20711. this.computeWorldMatrix(true);
  20712. var boundingInfo = this.getBoundingInfo();
  20713. // Update octree
  20714. var bbox = boundingInfo.boundingBox;
  20715. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20716. return this._submeshesOctree;
  20717. };
  20718. // Collisions
  20719. /** @hidden */
  20720. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20721. this._generatePointsArray();
  20722. if (!this._positions) {
  20723. return this;
  20724. }
  20725. // Transformation
  20726. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20727. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20728. subMesh._lastColliderWorldVertices = [];
  20729. subMesh._trianglePlanes = [];
  20730. var start = subMesh.verticesStart;
  20731. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20732. for (var i = start; i < end; i++) {
  20733. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20734. }
  20735. }
  20736. // Collide
  20737. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20738. if (collider.collisionFound) {
  20739. collider.collidedMesh = this;
  20740. }
  20741. return this;
  20742. };
  20743. /** @hidden */
  20744. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20745. var subMeshes;
  20746. var len;
  20747. // Octrees
  20748. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20749. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20750. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20751. len = intersections.length;
  20752. subMeshes = intersections.data;
  20753. }
  20754. else {
  20755. subMeshes = this.subMeshes;
  20756. len = subMeshes.length;
  20757. }
  20758. for (var index = 0; index < len; index++) {
  20759. var subMesh = subMeshes[index];
  20760. // Bounding test
  20761. if (len > 1 && !subMesh._checkCollision(collider))
  20762. continue;
  20763. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20764. }
  20765. return this;
  20766. };
  20767. /** @hidden */
  20768. AbstractMesh.prototype._checkCollision = function (collider) {
  20769. // Bounding box test
  20770. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20771. return this;
  20772. // Transformation matrix
  20773. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20774. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20775. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20776. return this;
  20777. };
  20778. // Picking
  20779. /** @hidden */
  20780. AbstractMesh.prototype._generatePointsArray = function () {
  20781. return false;
  20782. };
  20783. /**
  20784. * Checks if the passed Ray intersects with the mesh
  20785. * @param ray defines the ray to use
  20786. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20787. * @returns the picking info
  20788. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20789. */
  20790. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20791. var pickingInfo = new BABYLON.PickingInfo();
  20792. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20793. return pickingInfo;
  20794. }
  20795. if (!this._generatePointsArray()) {
  20796. return pickingInfo;
  20797. }
  20798. var intersectInfo = null;
  20799. // Octrees
  20800. var subMeshes;
  20801. var len;
  20802. if (this._submeshesOctree && this.useOctreeForPicking) {
  20803. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20804. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20805. len = intersections.length;
  20806. subMeshes = intersections.data;
  20807. }
  20808. else {
  20809. subMeshes = this.subMeshes;
  20810. len = subMeshes.length;
  20811. }
  20812. for (var index = 0; index < len; index++) {
  20813. var subMesh = subMeshes[index];
  20814. // Bounding test
  20815. if (len > 1 && !subMesh.canIntersects(ray))
  20816. continue;
  20817. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20818. if (currentIntersectInfo) {
  20819. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20820. intersectInfo = currentIntersectInfo;
  20821. intersectInfo.subMeshId = index;
  20822. if (fastCheck) {
  20823. break;
  20824. }
  20825. }
  20826. }
  20827. }
  20828. if (intersectInfo) {
  20829. // Get picked point
  20830. var world = this.getWorldMatrix();
  20831. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20832. var direction = ray.direction.clone();
  20833. direction = direction.scale(intersectInfo.distance);
  20834. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20835. var pickedPoint = worldOrigin.add(worldDirection);
  20836. // Return result
  20837. pickingInfo.hit = true;
  20838. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20839. pickingInfo.pickedPoint = pickedPoint;
  20840. pickingInfo.pickedMesh = this;
  20841. pickingInfo.bu = intersectInfo.bu || 0;
  20842. pickingInfo.bv = intersectInfo.bv || 0;
  20843. pickingInfo.faceId = intersectInfo.faceId;
  20844. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20845. return pickingInfo;
  20846. }
  20847. return pickingInfo;
  20848. };
  20849. /**
  20850. * Clones the current mesh
  20851. * @param name defines the mesh name
  20852. * @param newParent defines the new mesh parent
  20853. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20854. * @returns the new mesh
  20855. */
  20856. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20857. return null;
  20858. };
  20859. /**
  20860. * Disposes all the submeshes of the current meshnp
  20861. * @returns the current mesh
  20862. */
  20863. AbstractMesh.prototype.releaseSubMeshes = function () {
  20864. if (this.subMeshes) {
  20865. while (this.subMeshes.length) {
  20866. this.subMeshes[0].dispose();
  20867. }
  20868. }
  20869. else {
  20870. this.subMeshes = new Array();
  20871. }
  20872. return this;
  20873. };
  20874. /**
  20875. * Releases resources associated with this abstract mesh.
  20876. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20877. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20878. */
  20879. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20880. var _this = this;
  20881. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20882. var index;
  20883. // Smart Array Retainers.
  20884. this.getScene().freeActiveMeshes();
  20885. this.getScene().freeRenderingGroups();
  20886. // Action manager
  20887. if (this.actionManager !== undefined && this.actionManager !== null) {
  20888. this.actionManager.dispose();
  20889. this.actionManager = null;
  20890. }
  20891. // Skeleton
  20892. this._skeleton = null;
  20893. // Physics
  20894. if (this.physicsImpostor) {
  20895. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20896. }
  20897. // Intersections in progress
  20898. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20899. var other = this._intersectionsInProgress[index];
  20900. var pos = other._intersectionsInProgress.indexOf(this);
  20901. other._intersectionsInProgress.splice(pos, 1);
  20902. }
  20903. this._intersectionsInProgress = [];
  20904. // Lights
  20905. var lights = this.getScene().lights;
  20906. lights.forEach(function (light) {
  20907. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20908. if (meshIndex !== -1) {
  20909. light.includedOnlyMeshes.splice(meshIndex, 1);
  20910. }
  20911. meshIndex = light.excludedMeshes.indexOf(_this);
  20912. if (meshIndex !== -1) {
  20913. light.excludedMeshes.splice(meshIndex, 1);
  20914. }
  20915. // Shadow generators
  20916. var generator = light.getShadowGenerator();
  20917. if (generator) {
  20918. var shadowMap = generator.getShadowMap();
  20919. if (shadowMap && shadowMap.renderList) {
  20920. meshIndex = shadowMap.renderList.indexOf(_this);
  20921. if (meshIndex !== -1) {
  20922. shadowMap.renderList.splice(meshIndex, 1);
  20923. }
  20924. }
  20925. }
  20926. });
  20927. // SubMeshes
  20928. if (this.getClassName() !== "InstancedMesh") {
  20929. this.releaseSubMeshes();
  20930. }
  20931. // Octree
  20932. var sceneOctree = this.getScene().selectionOctree;
  20933. if (sceneOctree !== undefined && sceneOctree !== null) {
  20934. var index = sceneOctree.dynamicContent.indexOf(this);
  20935. if (index !== -1) {
  20936. sceneOctree.dynamicContent.splice(index, 1);
  20937. }
  20938. }
  20939. // Query
  20940. var engine = this.getScene().getEngine();
  20941. if (this._occlusionQuery) {
  20942. this._isOcclusionQueryInProgress = false;
  20943. engine.deleteQuery(this._occlusionQuery);
  20944. this._occlusionQuery = null;
  20945. }
  20946. // Engine
  20947. engine.wipeCaches();
  20948. // Remove from scene
  20949. this.getScene().removeMesh(this);
  20950. if (disposeMaterialAndTextures) {
  20951. if (this.material) {
  20952. this.material.dispose(false, true);
  20953. }
  20954. }
  20955. if (!doNotRecurse) {
  20956. // Particles
  20957. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20958. if (this.getScene().particleSystems[index].emitter === this) {
  20959. this.getScene().particleSystems[index].dispose();
  20960. index--;
  20961. }
  20962. }
  20963. }
  20964. // facet data
  20965. if (this._facetDataEnabled) {
  20966. this.disableFacetData();
  20967. }
  20968. this.onAfterWorldMatrixUpdateObservable.clear();
  20969. this.onCollideObservable.clear();
  20970. this.onCollisionPositionChangeObservable.clear();
  20971. this.onRebuildObservable.clear();
  20972. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20973. };
  20974. /**
  20975. * Adds the passed mesh as a child to the current mesh
  20976. * @param mesh defines the child mesh
  20977. * @returns the current mesh
  20978. */
  20979. AbstractMesh.prototype.addChild = function (mesh) {
  20980. mesh.setParent(this);
  20981. return this;
  20982. };
  20983. /**
  20984. * Removes the passed mesh from the current mesh children list
  20985. * @param mesh defines the child mesh
  20986. * @returns the current mesh
  20987. */
  20988. AbstractMesh.prototype.removeChild = function (mesh) {
  20989. mesh.setParent(null);
  20990. return this;
  20991. };
  20992. // Facet data
  20993. /** @hidden */
  20994. AbstractMesh.prototype._initFacetData = function () {
  20995. if (!this._facetNormals) {
  20996. this._facetNormals = new Array();
  20997. }
  20998. if (!this._facetPositions) {
  20999. this._facetPositions = new Array();
  21000. }
  21001. if (!this._facetPartitioning) {
  21002. this._facetPartitioning = new Array();
  21003. }
  21004. this._facetNb = (this.getIndices().length / 3) | 0;
  21005. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21006. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21007. for (var f = 0; f < this._facetNb; f++) {
  21008. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21009. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21010. }
  21011. this._facetDataEnabled = true;
  21012. return this;
  21013. };
  21014. /**
  21015. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21016. * This method can be called within the render loop.
  21017. * 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
  21018. * @returns the current mesh
  21019. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21020. */
  21021. AbstractMesh.prototype.updateFacetData = function () {
  21022. if (!this._facetDataEnabled) {
  21023. this._initFacetData();
  21024. }
  21025. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21026. var indices = this.getIndices();
  21027. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21028. var bInfo = this.getBoundingInfo();
  21029. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21030. // init arrays, matrix and sort function on first call
  21031. this._facetDepthSortEnabled = true;
  21032. if (indices instanceof Uint16Array) {
  21033. this._depthSortedIndices = new Uint16Array(indices);
  21034. }
  21035. else if (indices instanceof Uint32Array) {
  21036. this._depthSortedIndices = new Uint32Array(indices);
  21037. }
  21038. else {
  21039. var needs32bits = false;
  21040. for (var i = 0; i < indices.length; i++) {
  21041. if (indices[i] > 65535) {
  21042. needs32bits = true;
  21043. break;
  21044. }
  21045. }
  21046. if (needs32bits) {
  21047. this._depthSortedIndices = new Uint32Array(indices);
  21048. }
  21049. else {
  21050. this._depthSortedIndices = new Uint16Array(indices);
  21051. }
  21052. }
  21053. this._facetDepthSortFunction = function (f1, f2) {
  21054. return (f2.sqDistance - f1.sqDistance);
  21055. };
  21056. if (!this._facetDepthSortFrom) {
  21057. var camera = this.getScene().activeCamera;
  21058. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21059. }
  21060. this._depthSortedFacets = [];
  21061. for (var f = 0; f < this._facetNb; f++) {
  21062. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21063. this._depthSortedFacets.push(depthSortedFacet);
  21064. }
  21065. this._invertedMatrix = BABYLON.Matrix.Identity();
  21066. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21067. }
  21068. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21069. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21070. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21071. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21072. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21073. this._subDiv.max = this._partitioningSubdivisions;
  21074. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21075. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21076. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21077. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21078. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21079. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21080. // set the parameters for ComputeNormals()
  21081. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21082. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21083. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21084. this._facetParameters.bInfo = bInfo;
  21085. this._facetParameters.bbSize = this._bbSize;
  21086. this._facetParameters.subDiv = this._subDiv;
  21087. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21088. this._facetParameters.depthSort = this._facetDepthSort;
  21089. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21090. this.computeWorldMatrix(true);
  21091. this._worldMatrix.invertToRef(this._invertedMatrix);
  21092. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21093. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21094. }
  21095. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21096. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21097. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21098. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21099. var l = (this._depthSortedIndices.length / 3) | 0;
  21100. for (var f = 0; f < l; f++) {
  21101. var sind = this._depthSortedFacets[f].ind;
  21102. this._depthSortedIndices[f * 3] = indices[sind];
  21103. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21104. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21105. }
  21106. this.updateIndices(this._depthSortedIndices);
  21107. }
  21108. return this;
  21109. };
  21110. /**
  21111. * Returns the facetLocalNormals array.
  21112. * The normals are expressed in the mesh local spac
  21113. * @returns an array of Vector3
  21114. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21115. */
  21116. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21117. if (!this._facetNormals) {
  21118. this.updateFacetData();
  21119. }
  21120. return this._facetNormals;
  21121. };
  21122. /**
  21123. * Returns the facetLocalPositions array.
  21124. * The facet positions are expressed in the mesh local space
  21125. * @returns an array of Vector3
  21126. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21127. */
  21128. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21129. if (!this._facetPositions) {
  21130. this.updateFacetData();
  21131. }
  21132. return this._facetPositions;
  21133. };
  21134. /**
  21135. * Returns the facetLocalPartioning array
  21136. * @returns an array of array of numbers
  21137. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21138. */
  21139. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21140. if (!this._facetPartitioning) {
  21141. this.updateFacetData();
  21142. }
  21143. return this._facetPartitioning;
  21144. };
  21145. /**
  21146. * Returns the i-th facet position in the world system.
  21147. * This method allocates a new Vector3 per call
  21148. * @param i defines the facet index
  21149. * @returns a new Vector3
  21150. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21151. */
  21152. AbstractMesh.prototype.getFacetPosition = function (i) {
  21153. var pos = BABYLON.Vector3.Zero();
  21154. this.getFacetPositionToRef(i, pos);
  21155. return pos;
  21156. };
  21157. /**
  21158. * Sets the reference Vector3 with the i-th facet position in the world system
  21159. * @param i defines the facet index
  21160. * @param ref defines the target vector
  21161. * @returns the current mesh
  21162. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21163. */
  21164. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21165. var localPos = (this.getFacetLocalPositions())[i];
  21166. var world = this.getWorldMatrix();
  21167. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21168. return this;
  21169. };
  21170. /**
  21171. * Returns the i-th facet normal in the world system.
  21172. * This method allocates a new Vector3 per call
  21173. * @param i defines the facet index
  21174. * @returns a new Vector3
  21175. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21176. */
  21177. AbstractMesh.prototype.getFacetNormal = function (i) {
  21178. var norm = BABYLON.Vector3.Zero();
  21179. this.getFacetNormalToRef(i, norm);
  21180. return norm;
  21181. };
  21182. /**
  21183. * Sets the reference Vector3 with the i-th facet normal in the world system
  21184. * @param i defines the facet index
  21185. * @param ref defines the target vector
  21186. * @returns the current mesh
  21187. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21188. */
  21189. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21190. var localNorm = (this.getFacetLocalNormals())[i];
  21191. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21192. return this;
  21193. };
  21194. /**
  21195. * 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)
  21196. * @param x defines x coordinate
  21197. * @param y defines y coordinate
  21198. * @param z defines z coordinate
  21199. * @returns the array of facet indexes
  21200. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21201. */
  21202. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21203. var bInfo = this.getBoundingInfo();
  21204. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21205. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21206. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21207. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21208. return null;
  21209. }
  21210. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21211. };
  21212. /**
  21213. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21214. * @param projected sets as the (x,y,z) world projection on the facet
  21215. * @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
  21216. * @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
  21217. * @param x defines x coordinate
  21218. * @param y defines y coordinate
  21219. * @param z defines z coordinate
  21220. * @returns the face index if found (or null instead)
  21221. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21222. */
  21223. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21224. if (checkFace === void 0) { checkFace = false; }
  21225. if (facing === void 0) { facing = true; }
  21226. var world = this.getWorldMatrix();
  21227. var invMat = BABYLON.Tmp.Matrix[5];
  21228. world.invertToRef(invMat);
  21229. var invVect = BABYLON.Tmp.Vector3[8];
  21230. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21231. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21232. if (projected) {
  21233. // tranform the local computed projected vector to world coordinates
  21234. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21235. }
  21236. return closest;
  21237. };
  21238. /**
  21239. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21240. * @param projected sets as the (x,y,z) local projection on the facet
  21241. * @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
  21242. * @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
  21243. * @param x defines x coordinate
  21244. * @param y defines y coordinate
  21245. * @param z defines z coordinate
  21246. * @returns the face index if found (or null instead)
  21247. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21248. */
  21249. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21250. if (checkFace === void 0) { checkFace = false; }
  21251. if (facing === void 0) { facing = true; }
  21252. var closest = null;
  21253. var tmpx = 0.0;
  21254. var tmpy = 0.0;
  21255. var tmpz = 0.0;
  21256. var d = 0.0; // tmp dot facet normal * facet position
  21257. var t0 = 0.0;
  21258. var projx = 0.0;
  21259. var projy = 0.0;
  21260. var projz = 0.0;
  21261. // Get all the facets in the same partitioning block than (x, y, z)
  21262. var facetPositions = this.getFacetLocalPositions();
  21263. var facetNormals = this.getFacetLocalNormals();
  21264. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21265. if (!facetsInBlock) {
  21266. return null;
  21267. }
  21268. // Get the closest facet to (x, y, z)
  21269. var shortest = Number.MAX_VALUE; // init distance vars
  21270. var tmpDistance = shortest;
  21271. var fib; // current facet in the block
  21272. var norm; // current facet normal
  21273. var p0; // current facet barycenter position
  21274. // loop on all the facets in the current partitioning block
  21275. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21276. fib = facetsInBlock[idx];
  21277. norm = facetNormals[fib];
  21278. p0 = facetPositions[fib];
  21279. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21280. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21281. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21282. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21283. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21284. projx = x + norm.x * t0;
  21285. projy = y + norm.y * t0;
  21286. projz = z + norm.z * t0;
  21287. tmpx = projx - x;
  21288. tmpy = projy - y;
  21289. tmpz = projz - z;
  21290. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21291. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21292. shortest = tmpDistance;
  21293. closest = fib;
  21294. if (projected) {
  21295. projected.x = projx;
  21296. projected.y = projy;
  21297. projected.z = projz;
  21298. }
  21299. }
  21300. }
  21301. }
  21302. return closest;
  21303. };
  21304. /**
  21305. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21306. * @returns the parameters
  21307. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21308. */
  21309. AbstractMesh.prototype.getFacetDataParameters = function () {
  21310. return this._facetParameters;
  21311. };
  21312. /**
  21313. * Disables the feature FacetData and frees the related memory
  21314. * @returns the current mesh
  21315. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21316. */
  21317. AbstractMesh.prototype.disableFacetData = function () {
  21318. if (this._facetDataEnabled) {
  21319. this._facetDataEnabled = false;
  21320. this._facetPositions = new Array();
  21321. this._facetNormals = new Array();
  21322. this._facetPartitioning = new Array();
  21323. this._facetParameters = null;
  21324. this._depthSortedIndices = new Uint32Array(0);
  21325. }
  21326. return this;
  21327. };
  21328. /**
  21329. * Updates the AbstractMesh indices array
  21330. * @param indices defines the data source
  21331. * @returns the current mesh
  21332. */
  21333. AbstractMesh.prototype.updateIndices = function (indices) {
  21334. return this;
  21335. };
  21336. /**
  21337. * Creates new normals data for the mesh
  21338. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21339. * @returns the current mesh
  21340. */
  21341. AbstractMesh.prototype.createNormals = function (updatable) {
  21342. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21343. var indices = this.getIndices();
  21344. var normals;
  21345. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21346. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21347. }
  21348. else {
  21349. normals = [];
  21350. }
  21351. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21352. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21353. return this;
  21354. };
  21355. /**
  21356. * Align the mesh with a normal
  21357. * @param normal defines the normal to use
  21358. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21359. * @returns the current mesh
  21360. */
  21361. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21362. if (!upDirection) {
  21363. upDirection = BABYLON.Axis.Y;
  21364. }
  21365. var axisX = BABYLON.Tmp.Vector3[0];
  21366. var axisZ = BABYLON.Tmp.Vector3[1];
  21367. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21368. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21369. if (this.rotationQuaternion) {
  21370. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21371. }
  21372. else {
  21373. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21374. }
  21375. return this;
  21376. };
  21377. /** @hidden */
  21378. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21379. this._isOccluded = false;
  21380. };
  21381. /** No occlusion */
  21382. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21383. /** Occlusion set to optimisitic */
  21384. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21385. /** Occlusion set to strict */
  21386. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21387. /** Use an accurante occlusion algorithm */
  21388. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21389. /** Use a conservative occlusion algorithm */
  21390. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21391. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21392. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21393. /** Culling strategy with bounding sphere only and then frustum culling */
  21394. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21395. return AbstractMesh;
  21396. }(BABYLON.TransformNode));
  21397. BABYLON.AbstractMesh = AbstractMesh;
  21398. })(BABYLON || (BABYLON = {}));
  21399. //# sourceMappingURL=babylon.abstractMesh.js.map
  21400. var BABYLON;
  21401. (function (BABYLON) {
  21402. /**
  21403. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21404. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21405. * 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.
  21406. */
  21407. var Light = /** @class */ (function (_super) {
  21408. __extends(Light, _super);
  21409. /**
  21410. * Creates a Light object in the scene.
  21411. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21412. * @param name The firendly name of the light
  21413. * @param scene The scene the light belongs too
  21414. */
  21415. function Light(name, scene) {
  21416. var _this = _super.call(this, name, scene) || this;
  21417. /**
  21418. * Diffuse gives the basic color to an object.
  21419. */
  21420. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21421. /**
  21422. * Specular produces a highlight color on an object.
  21423. * Note: This is note affecting PBR materials.
  21424. */
  21425. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21426. /**
  21427. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21428. * falling off base on range or angle.
  21429. * This can be set to any values in Light.FALLOFF_x.
  21430. *
  21431. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21432. * other types of materials.
  21433. */
  21434. _this.falloffType = Light.FALLOFF_DEFAULT;
  21435. /**
  21436. * Strength of the light.
  21437. * Note: By default it is define in the framework own unit.
  21438. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21439. */
  21440. _this.intensity = 1.0;
  21441. _this._range = Number.MAX_VALUE;
  21442. _this._inverseSquaredRange = 0;
  21443. /**
  21444. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21445. * of light.
  21446. */
  21447. _this._photometricScale = 1.0;
  21448. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21449. _this._radius = 0.00001;
  21450. /**
  21451. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21452. * exceeding the number allowed of the materials.
  21453. */
  21454. _this.renderPriority = 0;
  21455. _this._shadowEnabled = true;
  21456. _this._excludeWithLayerMask = 0;
  21457. _this._includeOnlyWithLayerMask = 0;
  21458. _this._lightmapMode = 0;
  21459. /**
  21460. * @hidden Internal use only.
  21461. */
  21462. _this._excludedMeshesIds = new Array();
  21463. /**
  21464. * @hidden Internal use only.
  21465. */
  21466. _this._includedOnlyMeshesIds = new Array();
  21467. _this.getScene().addLight(_this);
  21468. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21469. _this._buildUniformLayout();
  21470. _this.includedOnlyMeshes = new Array();
  21471. _this.excludedMeshes = new Array();
  21472. _this._resyncMeshes();
  21473. return _this;
  21474. }
  21475. Object.defineProperty(Light.prototype, "range", {
  21476. /**
  21477. * Defines how far from the source the light is impacting in scene units.
  21478. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21479. */
  21480. get: function () {
  21481. return this._range;
  21482. },
  21483. /**
  21484. * Defines how far from the source the light is impacting in scene units.
  21485. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21486. */
  21487. set: function (value) {
  21488. this._range = value;
  21489. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21490. },
  21491. enumerable: true,
  21492. configurable: true
  21493. });
  21494. Object.defineProperty(Light.prototype, "intensityMode", {
  21495. /**
  21496. * Gets the photometric scale used to interpret the intensity.
  21497. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21498. */
  21499. get: function () {
  21500. return this._intensityMode;
  21501. },
  21502. /**
  21503. * Sets the photometric scale used to interpret the intensity.
  21504. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21505. */
  21506. set: function (value) {
  21507. this._intensityMode = value;
  21508. this._computePhotometricScale();
  21509. },
  21510. enumerable: true,
  21511. configurable: true
  21512. });
  21513. ;
  21514. ;
  21515. Object.defineProperty(Light.prototype, "radius", {
  21516. /**
  21517. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21518. */
  21519. get: function () {
  21520. return this._radius;
  21521. },
  21522. /**
  21523. * sets the light radius used by PBR Materials to simulate soft area lights.
  21524. */
  21525. set: function (value) {
  21526. this._radius = value;
  21527. this._computePhotometricScale();
  21528. },
  21529. enumerable: true,
  21530. configurable: true
  21531. });
  21532. ;
  21533. ;
  21534. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21535. /**
  21536. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21537. * the current shadow generator.
  21538. */
  21539. get: function () {
  21540. return this._shadowEnabled;
  21541. },
  21542. /**
  21543. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21544. * the current shadow generator.
  21545. */
  21546. set: function (value) {
  21547. if (this._shadowEnabled === value) {
  21548. return;
  21549. }
  21550. this._shadowEnabled = value;
  21551. this._markMeshesAsLightDirty();
  21552. },
  21553. enumerable: true,
  21554. configurable: true
  21555. });
  21556. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21557. /**
  21558. * Gets the only meshes impacted by this light.
  21559. */
  21560. get: function () {
  21561. return this._includedOnlyMeshes;
  21562. },
  21563. /**
  21564. * Sets the only meshes impacted by this light.
  21565. */
  21566. set: function (value) {
  21567. this._includedOnlyMeshes = value;
  21568. this._hookArrayForIncludedOnly(value);
  21569. },
  21570. enumerable: true,
  21571. configurable: true
  21572. });
  21573. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21574. /**
  21575. * Gets the meshes not impacted by this light.
  21576. */
  21577. get: function () {
  21578. return this._excludedMeshes;
  21579. },
  21580. /**
  21581. * Sets the meshes not impacted by this light.
  21582. */
  21583. set: function (value) {
  21584. this._excludedMeshes = value;
  21585. this._hookArrayForExcluded(value);
  21586. },
  21587. enumerable: true,
  21588. configurable: true
  21589. });
  21590. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21591. /**
  21592. * Gets the layer id use to find what meshes are not impacted by the light.
  21593. * Inactive if 0
  21594. */
  21595. get: function () {
  21596. return this._excludeWithLayerMask;
  21597. },
  21598. /**
  21599. * Sets the layer id use to find what meshes are not impacted by the light.
  21600. * Inactive if 0
  21601. */
  21602. set: function (value) {
  21603. this._excludeWithLayerMask = value;
  21604. this._resyncMeshes();
  21605. },
  21606. enumerable: true,
  21607. configurable: true
  21608. });
  21609. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21610. /**
  21611. * Gets the layer id use to find what meshes are impacted by the light.
  21612. * Inactive if 0
  21613. */
  21614. get: function () {
  21615. return this._includeOnlyWithLayerMask;
  21616. },
  21617. /**
  21618. * Sets the layer id use to find what meshes are impacted by the light.
  21619. * Inactive if 0
  21620. */
  21621. set: function (value) {
  21622. this._includeOnlyWithLayerMask = value;
  21623. this._resyncMeshes();
  21624. },
  21625. enumerable: true,
  21626. configurable: true
  21627. });
  21628. Object.defineProperty(Light.prototype, "lightmapMode", {
  21629. /**
  21630. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21631. */
  21632. get: function () {
  21633. return this._lightmapMode;
  21634. },
  21635. /**
  21636. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21637. */
  21638. set: function (value) {
  21639. if (this._lightmapMode === value) {
  21640. return;
  21641. }
  21642. this._lightmapMode = value;
  21643. this._markMeshesAsLightDirty();
  21644. },
  21645. enumerable: true,
  21646. configurable: true
  21647. });
  21648. /**
  21649. * Returns the string "Light".
  21650. * @returns the class name
  21651. */
  21652. Light.prototype.getClassName = function () {
  21653. return "Light";
  21654. };
  21655. /**
  21656. * Converts the light information to a readable string for debug purpose.
  21657. * @param fullDetails Supports for multiple levels of logging within scene loading
  21658. * @returns the human readable light info
  21659. */
  21660. Light.prototype.toString = function (fullDetails) {
  21661. var ret = "Name: " + this.name;
  21662. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21663. if (this.animations) {
  21664. for (var i = 0; i < this.animations.length; i++) {
  21665. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21666. }
  21667. }
  21668. if (fullDetails) {
  21669. }
  21670. return ret;
  21671. };
  21672. /**
  21673. * Set the enabled state of this node.
  21674. * @param value - the new enabled state
  21675. */
  21676. Light.prototype.setEnabled = function (value) {
  21677. _super.prototype.setEnabled.call(this, value);
  21678. this._resyncMeshes();
  21679. };
  21680. /**
  21681. * Returns the Light associated shadow generator if any.
  21682. * @return the associated shadow generator.
  21683. */
  21684. Light.prototype.getShadowGenerator = function () {
  21685. return this._shadowGenerator;
  21686. };
  21687. /**
  21688. * Returns a Vector3, the absolute light position in the World.
  21689. * @returns the world space position of the light
  21690. */
  21691. Light.prototype.getAbsolutePosition = function () {
  21692. return BABYLON.Vector3.Zero();
  21693. };
  21694. /**
  21695. * Specifies if the light will affect the passed mesh.
  21696. * @param mesh The mesh to test against the light
  21697. * @return true the mesh is affected otherwise, false.
  21698. */
  21699. Light.prototype.canAffectMesh = function (mesh) {
  21700. if (!mesh) {
  21701. return true;
  21702. }
  21703. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21704. return false;
  21705. }
  21706. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21707. return false;
  21708. }
  21709. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21710. return false;
  21711. }
  21712. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21713. return false;
  21714. }
  21715. return true;
  21716. };
  21717. /**
  21718. * Computes and Returns the light World matrix.
  21719. * @returns the world matrix
  21720. */
  21721. Light.prototype.getWorldMatrix = function () {
  21722. this._currentRenderId = this.getScene().getRenderId();
  21723. this._childRenderId = this._currentRenderId;
  21724. var worldMatrix = this._getWorldMatrix();
  21725. if (this.parent && this.parent.getWorldMatrix) {
  21726. if (!this._parentedWorldMatrix) {
  21727. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21728. }
  21729. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21730. this._markSyncedWithParent();
  21731. return this._parentedWorldMatrix;
  21732. }
  21733. return worldMatrix;
  21734. };
  21735. /**
  21736. * Sort function to order lights for rendering.
  21737. * @param a First Light object to compare to second.
  21738. * @param b Second Light object to compare first.
  21739. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21740. */
  21741. Light.CompareLightsPriority = function (a, b) {
  21742. //shadow-casting lights have priority over non-shadow-casting lights
  21743. //the renderPrioirty is a secondary sort criterion
  21744. if (a.shadowEnabled !== b.shadowEnabled) {
  21745. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21746. }
  21747. return b.renderPriority - a.renderPriority;
  21748. };
  21749. /**
  21750. * Releases resources associated with this node.
  21751. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21752. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21753. */
  21754. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21755. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21756. if (this._shadowGenerator) {
  21757. this._shadowGenerator.dispose();
  21758. this._shadowGenerator = null;
  21759. }
  21760. // Animations
  21761. this.getScene().stopAnimation(this);
  21762. // Remove from meshes
  21763. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21764. var mesh = _a[_i];
  21765. mesh._removeLightSource(this);
  21766. }
  21767. this._uniformBuffer.dispose();
  21768. // Remove from scene
  21769. this.getScene().removeLight(this);
  21770. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21771. };
  21772. /**
  21773. * Returns the light type ID (integer).
  21774. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21775. */
  21776. Light.prototype.getTypeID = function () {
  21777. return 0;
  21778. };
  21779. /**
  21780. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21781. * @returns the scaled intensity in intensity mode unit
  21782. */
  21783. Light.prototype.getScaledIntensity = function () {
  21784. return this._photometricScale * this.intensity;
  21785. };
  21786. /**
  21787. * Returns a new Light object, named "name", from the current one.
  21788. * @param name The name of the cloned light
  21789. * @returns the new created light
  21790. */
  21791. Light.prototype.clone = function (name) {
  21792. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21793. if (!constructor) {
  21794. return null;
  21795. }
  21796. return BABYLON.SerializationHelper.Clone(constructor, this);
  21797. };
  21798. /**
  21799. * Serializes the current light into a Serialization object.
  21800. * @returns the serialized object.
  21801. */
  21802. Light.prototype.serialize = function () {
  21803. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21804. // Type
  21805. serializationObject.type = this.getTypeID();
  21806. // Parent
  21807. if (this.parent) {
  21808. serializationObject.parentId = this.parent.id;
  21809. }
  21810. // Inclusion / exclusions
  21811. if (this.excludedMeshes.length > 0) {
  21812. serializationObject.excludedMeshesIds = [];
  21813. this.excludedMeshes.forEach(function (mesh) {
  21814. serializationObject.excludedMeshesIds.push(mesh.id);
  21815. });
  21816. }
  21817. if (this.includedOnlyMeshes.length > 0) {
  21818. serializationObject.includedOnlyMeshesIds = [];
  21819. this.includedOnlyMeshes.forEach(function (mesh) {
  21820. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21821. });
  21822. }
  21823. // Animations
  21824. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21825. serializationObject.ranges = this.serializeAnimationRanges();
  21826. return serializationObject;
  21827. };
  21828. /**
  21829. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21830. * This new light is named "name" and added to the passed scene.
  21831. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21832. * @param name The friendly name of the light
  21833. * @param scene The scene the new light will belong to
  21834. * @returns the constructor function
  21835. */
  21836. Light.GetConstructorFromName = function (type, name, scene) {
  21837. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21838. if (constructorFunc) {
  21839. return constructorFunc;
  21840. }
  21841. // Default to no light for none present once.
  21842. return null;
  21843. };
  21844. /**
  21845. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21846. * @param parsedLight The JSON representation of the light
  21847. * @param scene The scene to create the parsed light in
  21848. * @returns the created light after parsing
  21849. */
  21850. Light.Parse = function (parsedLight, scene) {
  21851. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21852. if (!constructor) {
  21853. return null;
  21854. }
  21855. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21856. // Inclusion / exclusions
  21857. if (parsedLight.excludedMeshesIds) {
  21858. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21859. }
  21860. if (parsedLight.includedOnlyMeshesIds) {
  21861. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21862. }
  21863. // Parent
  21864. if (parsedLight.parentId) {
  21865. light._waitingParentId = parsedLight.parentId;
  21866. }
  21867. // Animations
  21868. if (parsedLight.animations) {
  21869. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21870. var parsedAnimation = parsedLight.animations[animationIndex];
  21871. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21872. }
  21873. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21874. }
  21875. if (parsedLight.autoAnimate) {
  21876. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21877. }
  21878. return light;
  21879. };
  21880. Light.prototype._hookArrayForExcluded = function (array) {
  21881. var _this = this;
  21882. var oldPush = array.push;
  21883. array.push = function () {
  21884. var items = [];
  21885. for (var _i = 0; _i < arguments.length; _i++) {
  21886. items[_i] = arguments[_i];
  21887. }
  21888. var result = oldPush.apply(array, items);
  21889. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21890. var item = items_1[_a];
  21891. item._resyncLighSource(_this);
  21892. }
  21893. return result;
  21894. };
  21895. var oldSplice = array.splice;
  21896. array.splice = function (index, deleteCount) {
  21897. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21898. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21899. var item = deleted_1[_i];
  21900. item._resyncLighSource(_this);
  21901. }
  21902. return deleted;
  21903. };
  21904. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21905. var item = array_1[_i];
  21906. item._resyncLighSource(this);
  21907. }
  21908. };
  21909. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21910. var _this = this;
  21911. var oldPush = array.push;
  21912. array.push = function () {
  21913. var items = [];
  21914. for (var _i = 0; _i < arguments.length; _i++) {
  21915. items[_i] = arguments[_i];
  21916. }
  21917. var result = oldPush.apply(array, items);
  21918. _this._resyncMeshes();
  21919. return result;
  21920. };
  21921. var oldSplice = array.splice;
  21922. array.splice = function (index, deleteCount) {
  21923. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21924. _this._resyncMeshes();
  21925. return deleted;
  21926. };
  21927. this._resyncMeshes();
  21928. };
  21929. Light.prototype._resyncMeshes = function () {
  21930. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21931. var mesh = _a[_i];
  21932. mesh._resyncLighSource(this);
  21933. }
  21934. };
  21935. /**
  21936. * Forces the meshes to update their light related information in their rendering used effects
  21937. * @hidden Internal Use Only
  21938. */
  21939. Light.prototype._markMeshesAsLightDirty = function () {
  21940. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21941. var mesh = _a[_i];
  21942. if (mesh._lightSources.indexOf(this) !== -1) {
  21943. mesh._markSubMeshesAsLightDirty();
  21944. }
  21945. }
  21946. };
  21947. /**
  21948. * Recomputes the cached photometric scale if needed.
  21949. */
  21950. Light.prototype._computePhotometricScale = function () {
  21951. this._photometricScale = this._getPhotometricScale();
  21952. this.getScene().resetCachedMaterial();
  21953. };
  21954. /**
  21955. * Returns the Photometric Scale according to the light type and intensity mode.
  21956. */
  21957. Light.prototype._getPhotometricScale = function () {
  21958. var photometricScale = 0.0;
  21959. var lightTypeID = this.getTypeID();
  21960. //get photometric mode
  21961. var photometricMode = this.intensityMode;
  21962. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21963. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21964. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21965. }
  21966. else {
  21967. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21968. }
  21969. }
  21970. //compute photometric scale
  21971. switch (lightTypeID) {
  21972. case Light.LIGHTTYPEID_POINTLIGHT:
  21973. case Light.LIGHTTYPEID_SPOTLIGHT:
  21974. switch (photometricMode) {
  21975. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21976. photometricScale = 1.0 / (4.0 * Math.PI);
  21977. break;
  21978. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21979. photometricScale = 1.0;
  21980. break;
  21981. case Light.INTENSITYMODE_LUMINANCE:
  21982. photometricScale = this.radius * this.radius;
  21983. break;
  21984. }
  21985. break;
  21986. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21987. switch (photometricMode) {
  21988. case Light.INTENSITYMODE_ILLUMINANCE:
  21989. photometricScale = 1.0;
  21990. break;
  21991. case Light.INTENSITYMODE_LUMINANCE:
  21992. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21993. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21994. var apexAngleRadians = this.radius;
  21995. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21996. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21997. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21998. photometricScale = solidAngle;
  21999. break;
  22000. }
  22001. break;
  22002. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22003. // No fall off in hemisperic light.
  22004. photometricScale = 1.0;
  22005. break;
  22006. }
  22007. return photometricScale;
  22008. };
  22009. /**
  22010. * Reorder the light in the scene according to their defined priority.
  22011. * @hidden Internal Use Only
  22012. */
  22013. Light.prototype._reorderLightsInScene = function () {
  22014. var scene = this.getScene();
  22015. if (this._renderPriority != 0) {
  22016. scene.requireLightSorting = true;
  22017. }
  22018. this.getScene().sortLightsByPriority();
  22019. };
  22020. /**
  22021. * Falloff Default: light is falling off following the material specification:
  22022. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22023. */
  22024. Light.FALLOFF_DEFAULT = 0;
  22025. /**
  22026. * Falloff Physical: light is falling off following the inverse squared distance law.
  22027. */
  22028. Light.FALLOFF_PHYSICAL = 1;
  22029. /**
  22030. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22031. * to enhance interoperability with other engines.
  22032. */
  22033. Light.FALLOFF_GLTF = 2;
  22034. /**
  22035. * Falloff Standard: light is falling off like in the standard material
  22036. * to enhance interoperability with other materials.
  22037. */
  22038. Light.FALLOFF_STANDARD = 3;
  22039. //lightmapMode Consts
  22040. /**
  22041. * If every light affecting the material is in this lightmapMode,
  22042. * material.lightmapTexture adds or multiplies
  22043. * (depends on material.useLightmapAsShadowmap)
  22044. * after every other light calculations.
  22045. */
  22046. Light.LIGHTMAP_DEFAULT = 0;
  22047. /**
  22048. * material.lightmapTexture as only diffuse lighting from this light
  22049. * adds only specular lighting from this light
  22050. * adds dynamic shadows
  22051. */
  22052. Light.LIGHTMAP_SPECULAR = 1;
  22053. /**
  22054. * material.lightmapTexture as only lighting
  22055. * no light calculation from this light
  22056. * only adds dynamic shadows from this light
  22057. */
  22058. Light.LIGHTMAP_SHADOWSONLY = 2;
  22059. // Intensity Mode Consts
  22060. /**
  22061. * Each light type uses the default quantity according to its type:
  22062. * point/spot lights use luminous intensity
  22063. * directional lights use illuminance
  22064. */
  22065. Light.INTENSITYMODE_AUTOMATIC = 0;
  22066. /**
  22067. * lumen (lm)
  22068. */
  22069. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22070. /**
  22071. * candela (lm/sr)
  22072. */
  22073. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22074. /**
  22075. * lux (lm/m^2)
  22076. */
  22077. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22078. /**
  22079. * nit (cd/m^2)
  22080. */
  22081. Light.INTENSITYMODE_LUMINANCE = 4;
  22082. // Light types ids const.
  22083. /**
  22084. * Light type const id of the point light.
  22085. */
  22086. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22087. /**
  22088. * Light type const id of the directional light.
  22089. */
  22090. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22091. /**
  22092. * Light type const id of the spot light.
  22093. */
  22094. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22095. /**
  22096. * Light type const id of the hemispheric light.
  22097. */
  22098. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22099. __decorate([
  22100. BABYLON.serializeAsColor3()
  22101. ], Light.prototype, "diffuse", void 0);
  22102. __decorate([
  22103. BABYLON.serializeAsColor3()
  22104. ], Light.prototype, "specular", void 0);
  22105. __decorate([
  22106. BABYLON.serialize()
  22107. ], Light.prototype, "falloffType", void 0);
  22108. __decorate([
  22109. BABYLON.serialize()
  22110. ], Light.prototype, "intensity", void 0);
  22111. __decorate([
  22112. BABYLON.serialize()
  22113. ], Light.prototype, "range", null);
  22114. __decorate([
  22115. BABYLON.serialize()
  22116. ], Light.prototype, "intensityMode", null);
  22117. __decorate([
  22118. BABYLON.serialize()
  22119. ], Light.prototype, "radius", null);
  22120. __decorate([
  22121. BABYLON.serialize()
  22122. ], Light.prototype, "_renderPriority", void 0);
  22123. __decorate([
  22124. BABYLON.expandToProperty("_reorderLightsInScene")
  22125. ], Light.prototype, "renderPriority", void 0);
  22126. __decorate([
  22127. BABYLON.serialize("shadowEnabled")
  22128. ], Light.prototype, "_shadowEnabled", void 0);
  22129. __decorate([
  22130. BABYLON.serialize("excludeWithLayerMask")
  22131. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22132. __decorate([
  22133. BABYLON.serialize("includeOnlyWithLayerMask")
  22134. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22135. __decorate([
  22136. BABYLON.serialize("lightmapMode")
  22137. ], Light.prototype, "_lightmapMode", void 0);
  22138. return Light;
  22139. }(BABYLON.Node));
  22140. BABYLON.Light = Light;
  22141. })(BABYLON || (BABYLON = {}));
  22142. //# sourceMappingURL=babylon.light.js.map
  22143. var BABYLON;
  22144. (function (BABYLON) {
  22145. var Camera = /** @class */ (function (_super) {
  22146. __extends(Camera, _super);
  22147. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22148. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22149. var _this = _super.call(this, name, scene) || this;
  22150. /**
  22151. * The vector the camera should consider as up.
  22152. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22153. */
  22154. _this.upVector = BABYLON.Vector3.Up();
  22155. _this.orthoLeft = null;
  22156. _this.orthoRight = null;
  22157. _this.orthoBottom = null;
  22158. _this.orthoTop = null;
  22159. /**
  22160. * FOV is set in Radians. (default is 0.8)
  22161. */
  22162. _this.fov = 0.8;
  22163. _this.minZ = 1;
  22164. _this.maxZ = 10000.0;
  22165. _this.inertia = 0.9;
  22166. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22167. _this.isIntermediate = false;
  22168. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22169. /**
  22170. * Restricts the camera to viewing objects with the same layerMask.
  22171. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22172. */
  22173. _this.layerMask = 0x0FFFFFFF;
  22174. /**
  22175. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22176. */
  22177. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22178. // Camera rig members
  22179. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22180. /** @hidden */
  22181. _this._rigCameras = new Array();
  22182. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22183. /** @hidden */
  22184. _this._skipRendering = false;
  22185. _this.customRenderTargets = new Array();
  22186. // Observables
  22187. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22188. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22189. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22190. _this.onRestoreStateObservable = new BABYLON.Observable();
  22191. // Cache
  22192. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22193. _this._projectionMatrix = new BABYLON.Matrix();
  22194. _this._doNotComputeProjectionMatrix = false;
  22195. _this._worldMatrix = BABYLON.Matrix.Identity();
  22196. _this._postProcesses = new Array();
  22197. _this._transformMatrix = BABYLON.Matrix.Zero();
  22198. _this._activeMeshes = new BABYLON.SmartArray(256);
  22199. _this._globalPosition = BABYLON.Vector3.Zero();
  22200. _this._refreshFrustumPlanes = true;
  22201. _this.getScene().addCamera(_this);
  22202. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22203. _this.getScene().activeCamera = _this;
  22204. }
  22205. _this.position = position;
  22206. return _this;
  22207. }
  22208. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22209. get: function () {
  22210. return Camera._PERSPECTIVE_CAMERA;
  22211. },
  22212. enumerable: true,
  22213. configurable: true
  22214. });
  22215. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22216. get: function () {
  22217. return Camera._ORTHOGRAPHIC_CAMERA;
  22218. },
  22219. enumerable: true,
  22220. configurable: true
  22221. });
  22222. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22223. /**
  22224. * This is the default FOV mode for perspective cameras.
  22225. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22226. *
  22227. */
  22228. get: function () {
  22229. return Camera._FOVMODE_VERTICAL_FIXED;
  22230. },
  22231. enumerable: true,
  22232. configurable: true
  22233. });
  22234. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22235. /**
  22236. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22237. *
  22238. */
  22239. get: function () {
  22240. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22241. },
  22242. enumerable: true,
  22243. configurable: true
  22244. });
  22245. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22246. get: function () {
  22247. return Camera._RIG_MODE_NONE;
  22248. },
  22249. enumerable: true,
  22250. configurable: true
  22251. });
  22252. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22253. get: function () {
  22254. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22255. },
  22256. enumerable: true,
  22257. configurable: true
  22258. });
  22259. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22260. get: function () {
  22261. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22262. },
  22263. enumerable: true,
  22264. configurable: true
  22265. });
  22266. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22267. get: function () {
  22268. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22269. },
  22270. enumerable: true,
  22271. configurable: true
  22272. });
  22273. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22274. get: function () {
  22275. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22276. },
  22277. enumerable: true,
  22278. configurable: true
  22279. });
  22280. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22281. get: function () {
  22282. return Camera._RIG_MODE_VR;
  22283. },
  22284. enumerable: true,
  22285. configurable: true
  22286. });
  22287. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22288. get: function () {
  22289. return Camera._RIG_MODE_WEBVR;
  22290. },
  22291. enumerable: true,
  22292. configurable: true
  22293. });
  22294. /**
  22295. * Store current camera state (fov, position, etc..)
  22296. */
  22297. Camera.prototype.storeState = function () {
  22298. this._stateStored = true;
  22299. this._storedFov = this.fov;
  22300. return this;
  22301. };
  22302. /**
  22303. * Restores the camera state values if it has been stored. You must call storeState() first
  22304. */
  22305. Camera.prototype._restoreStateValues = function () {
  22306. if (!this._stateStored) {
  22307. return false;
  22308. }
  22309. this.fov = this._storedFov;
  22310. return true;
  22311. };
  22312. /**
  22313. * Restored camera state. You must call storeState() first
  22314. */
  22315. Camera.prototype.restoreState = function () {
  22316. if (this._restoreStateValues()) {
  22317. this.onRestoreStateObservable.notifyObservers(this);
  22318. return true;
  22319. }
  22320. return false;
  22321. };
  22322. Camera.prototype.getClassName = function () {
  22323. return "Camera";
  22324. };
  22325. /**
  22326. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22327. */
  22328. Camera.prototype.toString = function (fullDetails) {
  22329. var ret = "Name: " + this.name;
  22330. ret += ", type: " + this.getClassName();
  22331. if (this.animations) {
  22332. for (var i = 0; i < this.animations.length; i++) {
  22333. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22334. }
  22335. }
  22336. if (fullDetails) {
  22337. }
  22338. return ret;
  22339. };
  22340. Object.defineProperty(Camera.prototype, "globalPosition", {
  22341. get: function () {
  22342. return this._globalPosition;
  22343. },
  22344. enumerable: true,
  22345. configurable: true
  22346. });
  22347. Camera.prototype.getActiveMeshes = function () {
  22348. return this._activeMeshes;
  22349. };
  22350. Camera.prototype.isActiveMesh = function (mesh) {
  22351. return (this._activeMeshes.indexOf(mesh) !== -1);
  22352. };
  22353. /**
  22354. * Is this camera ready to be used/rendered
  22355. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22356. * @return true if the camera is ready
  22357. */
  22358. Camera.prototype.isReady = function (completeCheck) {
  22359. if (completeCheck === void 0) { completeCheck = false; }
  22360. if (completeCheck) {
  22361. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22362. var pp = _a[_i];
  22363. if (pp && !pp.isReady()) {
  22364. return false;
  22365. }
  22366. }
  22367. }
  22368. return _super.prototype.isReady.call(this, completeCheck);
  22369. };
  22370. //Cache
  22371. /** @hidden */
  22372. Camera.prototype._initCache = function () {
  22373. _super.prototype._initCache.call(this);
  22374. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22375. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22376. this._cache.mode = undefined;
  22377. this._cache.minZ = undefined;
  22378. this._cache.maxZ = undefined;
  22379. this._cache.fov = undefined;
  22380. this._cache.fovMode = undefined;
  22381. this._cache.aspectRatio = undefined;
  22382. this._cache.orthoLeft = undefined;
  22383. this._cache.orthoRight = undefined;
  22384. this._cache.orthoBottom = undefined;
  22385. this._cache.orthoTop = undefined;
  22386. this._cache.renderWidth = undefined;
  22387. this._cache.renderHeight = undefined;
  22388. };
  22389. /** @hidden */
  22390. Camera.prototype._updateCache = function (ignoreParentClass) {
  22391. if (!ignoreParentClass) {
  22392. _super.prototype._updateCache.call(this);
  22393. }
  22394. this._cache.position.copyFrom(this.position);
  22395. this._cache.upVector.copyFrom(this.upVector);
  22396. };
  22397. // Synchronized
  22398. /** @hidden */
  22399. Camera.prototype._isSynchronized = function () {
  22400. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22401. };
  22402. /** @hidden */
  22403. Camera.prototype._isSynchronizedViewMatrix = function () {
  22404. if (!_super.prototype._isSynchronized.call(this))
  22405. return false;
  22406. return this._cache.position.equals(this.position)
  22407. && this._cache.upVector.equals(this.upVector)
  22408. && this.isSynchronizedWithParent();
  22409. };
  22410. /** @hidden */
  22411. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22412. var check = this._cache.mode === this.mode
  22413. && this._cache.minZ === this.minZ
  22414. && this._cache.maxZ === this.maxZ;
  22415. if (!check) {
  22416. return false;
  22417. }
  22418. var engine = this.getEngine();
  22419. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22420. check = this._cache.fov === this.fov
  22421. && this._cache.fovMode === this.fovMode
  22422. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22423. }
  22424. else {
  22425. check = this._cache.orthoLeft === this.orthoLeft
  22426. && this._cache.orthoRight === this.orthoRight
  22427. && this._cache.orthoBottom === this.orthoBottom
  22428. && this._cache.orthoTop === this.orthoTop
  22429. && this._cache.renderWidth === engine.getRenderWidth()
  22430. && this._cache.renderHeight === engine.getRenderHeight();
  22431. }
  22432. return check;
  22433. };
  22434. // Controls
  22435. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22436. };
  22437. Camera.prototype.detachControl = function (element) {
  22438. };
  22439. Camera.prototype.update = function () {
  22440. this._checkInputs();
  22441. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22442. this._updateRigCameras();
  22443. }
  22444. };
  22445. /** @hidden */
  22446. Camera.prototype._checkInputs = function () {
  22447. this.onAfterCheckInputsObservable.notifyObservers(this);
  22448. };
  22449. Object.defineProperty(Camera.prototype, "rigCameras", {
  22450. get: function () {
  22451. return this._rigCameras;
  22452. },
  22453. enumerable: true,
  22454. configurable: true
  22455. });
  22456. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22457. get: function () {
  22458. return this._rigPostProcess;
  22459. },
  22460. enumerable: true,
  22461. configurable: true
  22462. });
  22463. /**
  22464. * Internal, gets the first post proces.
  22465. * @returns the first post process to be run on this camera.
  22466. */
  22467. Camera.prototype._getFirstPostProcess = function () {
  22468. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22469. if (this._postProcesses[ppIndex] !== null) {
  22470. return this._postProcesses[ppIndex];
  22471. }
  22472. }
  22473. return null;
  22474. };
  22475. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22476. // invalidate framebuffer
  22477. var firstPostProcess = this._getFirstPostProcess();
  22478. if (firstPostProcess) {
  22479. firstPostProcess.markTextureDirty();
  22480. }
  22481. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22482. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22483. var cam = this._rigCameras[i];
  22484. var rigPostProcess = cam._rigPostProcess;
  22485. // for VR rig, there does not have to be a post process
  22486. if (rigPostProcess) {
  22487. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22488. if (isPass) {
  22489. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22490. cam.isIntermediate = this._postProcesses.length === 0;
  22491. }
  22492. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22493. rigPostProcess.markTextureDirty();
  22494. }
  22495. else {
  22496. cam._postProcesses = this._postProcesses.slice(0);
  22497. }
  22498. }
  22499. };
  22500. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22501. if (insertAt === void 0) { insertAt = null; }
  22502. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22503. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22504. return 0;
  22505. }
  22506. if (insertAt == null || insertAt < 0) {
  22507. this._postProcesses.push(postProcess);
  22508. }
  22509. else if (this._postProcesses[insertAt] === null) {
  22510. this._postProcesses[insertAt] = postProcess;
  22511. }
  22512. else {
  22513. this._postProcesses.splice(insertAt, 0, postProcess);
  22514. }
  22515. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22516. return this._postProcesses.indexOf(postProcess);
  22517. };
  22518. Camera.prototype.detachPostProcess = function (postProcess) {
  22519. var idx = this._postProcesses.indexOf(postProcess);
  22520. if (idx !== -1) {
  22521. this._postProcesses[idx] = null;
  22522. }
  22523. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22524. };
  22525. Camera.prototype.getWorldMatrix = function () {
  22526. if (this._isSynchronizedViewMatrix()) {
  22527. return this._worldMatrix;
  22528. }
  22529. // Getting the the view matrix will also compute the world matrix.
  22530. this.getViewMatrix();
  22531. return this._worldMatrix;
  22532. };
  22533. /** @hidden */
  22534. Camera.prototype._getViewMatrix = function () {
  22535. return BABYLON.Matrix.Identity();
  22536. };
  22537. Camera.prototype.getViewMatrix = function (force) {
  22538. if (!force && this._isSynchronizedViewMatrix()) {
  22539. return this._computedViewMatrix;
  22540. }
  22541. this.updateCache();
  22542. this._computedViewMatrix = this._getViewMatrix();
  22543. this._currentRenderId = this.getScene().getRenderId();
  22544. this._childRenderId = this._currentRenderId;
  22545. this._refreshFrustumPlanes = true;
  22546. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22547. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22548. }
  22549. this.onViewMatrixChangedObservable.notifyObservers(this);
  22550. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22551. return this._computedViewMatrix;
  22552. };
  22553. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22554. this._doNotComputeProjectionMatrix = true;
  22555. if (projection !== undefined) {
  22556. this._projectionMatrix = projection;
  22557. }
  22558. };
  22559. ;
  22560. Camera.prototype.unfreezeProjectionMatrix = function () {
  22561. this._doNotComputeProjectionMatrix = false;
  22562. };
  22563. ;
  22564. Camera.prototype.getProjectionMatrix = function (force) {
  22565. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22566. return this._projectionMatrix;
  22567. }
  22568. // Cache
  22569. this._cache.mode = this.mode;
  22570. this._cache.minZ = this.minZ;
  22571. this._cache.maxZ = this.maxZ;
  22572. // Matrix
  22573. this._refreshFrustumPlanes = true;
  22574. var engine = this.getEngine();
  22575. var scene = this.getScene();
  22576. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22577. this._cache.fov = this.fov;
  22578. this._cache.fovMode = this.fovMode;
  22579. this._cache.aspectRatio = engine.getAspectRatio(this);
  22580. if (this.minZ <= 0) {
  22581. this.minZ = 0.1;
  22582. }
  22583. if (scene.useRightHandedSystem) {
  22584. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22585. }
  22586. else {
  22587. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22588. }
  22589. }
  22590. else {
  22591. var halfWidth = engine.getRenderWidth() / 2.0;
  22592. var halfHeight = engine.getRenderHeight() / 2.0;
  22593. if (scene.useRightHandedSystem) {
  22594. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22595. }
  22596. else {
  22597. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22598. }
  22599. this._cache.orthoLeft = this.orthoLeft;
  22600. this._cache.orthoRight = this.orthoRight;
  22601. this._cache.orthoBottom = this.orthoBottom;
  22602. this._cache.orthoTop = this.orthoTop;
  22603. this._cache.renderWidth = engine.getRenderWidth();
  22604. this._cache.renderHeight = engine.getRenderHeight();
  22605. }
  22606. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22607. return this._projectionMatrix;
  22608. };
  22609. /**
  22610. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22611. * @returns a Matrix
  22612. */
  22613. Camera.prototype.getTransformationMatrix = function () {
  22614. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22615. return this._transformMatrix;
  22616. };
  22617. Camera.prototype.updateFrustumPlanes = function () {
  22618. if (!this._refreshFrustumPlanes) {
  22619. return;
  22620. }
  22621. this.getTransformationMatrix();
  22622. if (!this._frustumPlanes) {
  22623. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22624. }
  22625. else {
  22626. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22627. }
  22628. this._refreshFrustumPlanes = false;
  22629. };
  22630. Camera.prototype.isInFrustum = function (target) {
  22631. this.updateFrustumPlanes();
  22632. return target.isInFrustum(this._frustumPlanes);
  22633. };
  22634. Camera.prototype.isCompletelyInFrustum = function (target) {
  22635. this.updateFrustumPlanes();
  22636. return target.isCompletelyInFrustum(this._frustumPlanes);
  22637. };
  22638. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22639. if (length === void 0) { length = 100; }
  22640. if (!transform) {
  22641. transform = this.getWorldMatrix();
  22642. }
  22643. if (!origin) {
  22644. origin = this.position;
  22645. }
  22646. var forward = new BABYLON.Vector3(0, 0, 1);
  22647. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22648. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22649. return new BABYLON.Ray(origin, direction, length);
  22650. };
  22651. /**
  22652. * Releases resources associated with this node.
  22653. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22654. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22655. */
  22656. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22657. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22658. // Observables
  22659. this.onViewMatrixChangedObservable.clear();
  22660. this.onProjectionMatrixChangedObservable.clear();
  22661. this.onAfterCheckInputsObservable.clear();
  22662. this.onRestoreStateObservable.clear();
  22663. // Inputs
  22664. if (this.inputs) {
  22665. this.inputs.clear();
  22666. }
  22667. // Animations
  22668. this.getScene().stopAnimation(this);
  22669. // Remove from scene
  22670. this.getScene().removeCamera(this);
  22671. while (this._rigCameras.length > 0) {
  22672. var camera = this._rigCameras.pop();
  22673. if (camera) {
  22674. camera.dispose();
  22675. }
  22676. }
  22677. // Postprocesses
  22678. if (this._rigPostProcess) {
  22679. this._rigPostProcess.dispose(this);
  22680. this._rigPostProcess = null;
  22681. this._postProcesses = [];
  22682. }
  22683. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22684. this._rigPostProcess = null;
  22685. this._postProcesses = [];
  22686. }
  22687. else {
  22688. var i = this._postProcesses.length;
  22689. while (--i >= 0) {
  22690. var postProcess = this._postProcesses[i];
  22691. if (postProcess) {
  22692. postProcess.dispose(this);
  22693. }
  22694. }
  22695. }
  22696. // Render targets
  22697. var i = this.customRenderTargets.length;
  22698. while (--i >= 0) {
  22699. this.customRenderTargets[i].dispose();
  22700. }
  22701. this.customRenderTargets = [];
  22702. // Active Meshes
  22703. this._activeMeshes.dispose();
  22704. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22705. };
  22706. Object.defineProperty(Camera.prototype, "leftCamera", {
  22707. // ---- Camera rigs section ----
  22708. get: function () {
  22709. if (this._rigCameras.length < 1) {
  22710. return null;
  22711. }
  22712. return this._rigCameras[0];
  22713. },
  22714. enumerable: true,
  22715. configurable: true
  22716. });
  22717. Object.defineProperty(Camera.prototype, "rightCamera", {
  22718. get: function () {
  22719. if (this._rigCameras.length < 2) {
  22720. return null;
  22721. }
  22722. return this._rigCameras[1];
  22723. },
  22724. enumerable: true,
  22725. configurable: true
  22726. });
  22727. Camera.prototype.getLeftTarget = function () {
  22728. if (this._rigCameras.length < 1) {
  22729. return null;
  22730. }
  22731. return this._rigCameras[0].getTarget();
  22732. };
  22733. Camera.prototype.getRightTarget = function () {
  22734. if (this._rigCameras.length < 2) {
  22735. return null;
  22736. }
  22737. return this._rigCameras[1].getTarget();
  22738. };
  22739. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22740. if (this.cameraRigMode === mode) {
  22741. return;
  22742. }
  22743. while (this._rigCameras.length > 0) {
  22744. var camera = this._rigCameras.pop();
  22745. if (camera) {
  22746. camera.dispose();
  22747. }
  22748. }
  22749. this.cameraRigMode = mode;
  22750. this._cameraRigParams = {};
  22751. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22752. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22753. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22754. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22755. // create the rig cameras, unless none
  22756. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22757. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22758. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22759. if (leftCamera && rightCamera) {
  22760. this._rigCameras.push(leftCamera);
  22761. this._rigCameras.push(rightCamera);
  22762. }
  22763. }
  22764. switch (this.cameraRigMode) {
  22765. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22766. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22767. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22768. break;
  22769. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22770. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22771. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22772. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22773. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22774. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22775. break;
  22776. case Camera.RIG_MODE_VR:
  22777. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22778. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22779. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22780. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22781. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22782. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22783. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22784. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22785. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22786. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22787. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22788. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22789. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22790. if (metrics.compensateDistortion) {
  22791. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22792. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22793. }
  22794. break;
  22795. case Camera.RIG_MODE_WEBVR:
  22796. if (rigParams.vrDisplay) {
  22797. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22798. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22799. //Left eye
  22800. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22801. this._rigCameras[0].setCameraRigParameter("left", true);
  22802. //leaving this for future reference
  22803. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22804. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22805. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22806. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22807. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22808. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22809. this._rigCameras[0].parent = this;
  22810. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22811. //Right eye
  22812. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22813. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22814. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22815. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22816. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22817. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22818. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22819. this._rigCameras[1].parent = this;
  22820. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22821. if (Camera.UseAlternateWebVRRendering) {
  22822. this._rigCameras[1]._skipRendering = true;
  22823. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22824. }
  22825. }
  22826. break;
  22827. }
  22828. this._cascadePostProcessesToRigCams();
  22829. this.update();
  22830. };
  22831. Camera.prototype._getVRProjectionMatrix = function () {
  22832. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22833. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22834. return this._projectionMatrix;
  22835. };
  22836. Camera.prototype._updateCameraRotationMatrix = function () {
  22837. //Here for WebVR
  22838. };
  22839. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22840. //Here for WebVR
  22841. };
  22842. /**
  22843. * This function MUST be overwritten by the different WebVR cameras available.
  22844. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22845. */
  22846. Camera.prototype._getWebVRProjectionMatrix = function () {
  22847. return BABYLON.Matrix.Identity();
  22848. };
  22849. /**
  22850. * This function MUST be overwritten by the different WebVR cameras available.
  22851. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22852. */
  22853. Camera.prototype._getWebVRViewMatrix = function () {
  22854. return BABYLON.Matrix.Identity();
  22855. };
  22856. Camera.prototype.setCameraRigParameter = function (name, value) {
  22857. if (!this._cameraRigParams) {
  22858. this._cameraRigParams = {};
  22859. }
  22860. this._cameraRigParams[name] = value;
  22861. //provisionnally:
  22862. if (name === "interaxialDistance") {
  22863. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22864. }
  22865. };
  22866. /**
  22867. * needs to be overridden by children so sub has required properties to be copied
  22868. */
  22869. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22870. return null;
  22871. };
  22872. /**
  22873. * May need to be overridden by children
  22874. * @hidden
  22875. */
  22876. Camera.prototype._updateRigCameras = function () {
  22877. for (var i = 0; i < this._rigCameras.length; i++) {
  22878. this._rigCameras[i].minZ = this.minZ;
  22879. this._rigCameras[i].maxZ = this.maxZ;
  22880. this._rigCameras[i].fov = this.fov;
  22881. }
  22882. // only update viewport when ANAGLYPH
  22883. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22884. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22885. }
  22886. };
  22887. /** @hidden */
  22888. Camera.prototype._setupInputs = function () {
  22889. };
  22890. Camera.prototype.serialize = function () {
  22891. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22892. // Type
  22893. serializationObject.type = this.getClassName();
  22894. // Parent
  22895. if (this.parent) {
  22896. serializationObject.parentId = this.parent.id;
  22897. }
  22898. if (this.inputs) {
  22899. this.inputs.serialize(serializationObject);
  22900. }
  22901. // Animations
  22902. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22903. serializationObject.ranges = this.serializeAnimationRanges();
  22904. return serializationObject;
  22905. };
  22906. Camera.prototype.clone = function (name) {
  22907. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22908. };
  22909. Camera.prototype.getDirection = function (localAxis) {
  22910. var result = BABYLON.Vector3.Zero();
  22911. this.getDirectionToRef(localAxis, result);
  22912. return result;
  22913. };
  22914. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22915. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22916. };
  22917. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22918. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22919. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22920. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22921. interaxial_distance: interaxial_distance,
  22922. isStereoscopicSideBySide: isStereoscopicSideBySide
  22923. });
  22924. if (constructorFunc) {
  22925. return constructorFunc;
  22926. }
  22927. // Default to universal camera
  22928. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22929. };
  22930. Camera.prototype.computeWorldMatrix = function () {
  22931. return this.getWorldMatrix();
  22932. };
  22933. Camera.Parse = function (parsedCamera, scene) {
  22934. var type = parsedCamera.type;
  22935. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22936. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22937. // Parent
  22938. if (parsedCamera.parentId) {
  22939. camera._waitingParentId = parsedCamera.parentId;
  22940. }
  22941. //If camera has an input manager, let it parse inputs settings
  22942. if (camera.inputs) {
  22943. camera.inputs.parse(parsedCamera);
  22944. camera._setupInputs();
  22945. }
  22946. if (camera.setPosition) { // need to force position
  22947. camera.position.copyFromFloats(0, 0, 0);
  22948. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22949. }
  22950. // Target
  22951. if (parsedCamera.target) {
  22952. if (camera.setTarget) {
  22953. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22954. }
  22955. }
  22956. // Apply 3d rig, when found
  22957. if (parsedCamera.cameraRigMode) {
  22958. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22959. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22960. }
  22961. // Animations
  22962. if (parsedCamera.animations) {
  22963. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22964. var parsedAnimation = parsedCamera.animations[animationIndex];
  22965. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22966. }
  22967. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22968. }
  22969. if (parsedCamera.autoAnimate) {
  22970. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22971. }
  22972. return camera;
  22973. };
  22974. // Statics
  22975. Camera._PERSPECTIVE_CAMERA = 0;
  22976. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22977. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22978. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22979. Camera._RIG_MODE_NONE = 0;
  22980. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22981. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22982. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22983. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22984. Camera._RIG_MODE_VR = 20;
  22985. Camera._RIG_MODE_WEBVR = 21;
  22986. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22987. Camera.UseAlternateWebVRRendering = false;
  22988. __decorate([
  22989. BABYLON.serializeAsVector3()
  22990. ], Camera.prototype, "position", void 0);
  22991. __decorate([
  22992. BABYLON.serializeAsVector3()
  22993. ], Camera.prototype, "upVector", void 0);
  22994. __decorate([
  22995. BABYLON.serialize()
  22996. ], Camera.prototype, "orthoLeft", void 0);
  22997. __decorate([
  22998. BABYLON.serialize()
  22999. ], Camera.prototype, "orthoRight", void 0);
  23000. __decorate([
  23001. BABYLON.serialize()
  23002. ], Camera.prototype, "orthoBottom", void 0);
  23003. __decorate([
  23004. BABYLON.serialize()
  23005. ], Camera.prototype, "orthoTop", void 0);
  23006. __decorate([
  23007. BABYLON.serialize()
  23008. ], Camera.prototype, "fov", void 0);
  23009. __decorate([
  23010. BABYLON.serialize()
  23011. ], Camera.prototype, "minZ", void 0);
  23012. __decorate([
  23013. BABYLON.serialize()
  23014. ], Camera.prototype, "maxZ", void 0);
  23015. __decorate([
  23016. BABYLON.serialize()
  23017. ], Camera.prototype, "inertia", void 0);
  23018. __decorate([
  23019. BABYLON.serialize()
  23020. ], Camera.prototype, "mode", void 0);
  23021. __decorate([
  23022. BABYLON.serialize()
  23023. ], Camera.prototype, "layerMask", void 0);
  23024. __decorate([
  23025. BABYLON.serialize()
  23026. ], Camera.prototype, "fovMode", void 0);
  23027. __decorate([
  23028. BABYLON.serialize()
  23029. ], Camera.prototype, "cameraRigMode", void 0);
  23030. __decorate([
  23031. BABYLON.serialize()
  23032. ], Camera.prototype, "interaxialDistance", void 0);
  23033. __decorate([
  23034. BABYLON.serialize()
  23035. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23036. return Camera;
  23037. }(BABYLON.Node));
  23038. BABYLON.Camera = Camera;
  23039. })(BABYLON || (BABYLON = {}));
  23040. //# sourceMappingURL=babylon.camera.js.map
  23041. var BABYLON;
  23042. (function (BABYLON) {
  23043. var RenderingManager = /** @class */ (function () {
  23044. function RenderingManager(scene) {
  23045. /**
  23046. * @hidden
  23047. */
  23048. this._useSceneAutoClearSetup = false;
  23049. this._renderingGroups = new Array();
  23050. this._autoClearDepthStencil = {};
  23051. this._customOpaqueSortCompareFn = {};
  23052. this._customAlphaTestSortCompareFn = {};
  23053. this._customTransparentSortCompareFn = {};
  23054. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23055. this._scene = scene;
  23056. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23057. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23058. }
  23059. }
  23060. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23061. if (depth === void 0) { depth = true; }
  23062. if (stencil === void 0) { stencil = true; }
  23063. if (this._depthStencilBufferAlreadyCleaned) {
  23064. return;
  23065. }
  23066. this._scene.getEngine().clear(null, false, depth, stencil);
  23067. this._depthStencilBufferAlreadyCleaned = true;
  23068. };
  23069. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23070. // Update the observable context (not null as it only goes away on dispose)
  23071. var info = this._renderingGroupInfo;
  23072. info.scene = this._scene;
  23073. info.camera = this._scene.activeCamera;
  23074. // Dispatch sprites
  23075. if (this._scene.spriteManagers && renderSprites) {
  23076. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23077. var manager = this._scene.spriteManagers[index];
  23078. this.dispatchSprites(manager);
  23079. }
  23080. }
  23081. // Render
  23082. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23083. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23084. var renderingGroup = this._renderingGroups[index];
  23085. if (!renderingGroup)
  23086. continue;
  23087. var renderingGroupMask = Math.pow(2, index);
  23088. info.renderingGroupId = index;
  23089. // Before Observable
  23090. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23091. // Clear depth/stencil if needed
  23092. if (RenderingManager.AUTOCLEAR) {
  23093. var autoClear = this._useSceneAutoClearSetup ?
  23094. this._scene.getAutoClearDepthStencilSetup(index) :
  23095. this._autoClearDepthStencil[index];
  23096. if (autoClear && autoClear.autoClear) {
  23097. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23098. }
  23099. }
  23100. // Render
  23101. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23102. var step = _a[_i];
  23103. step.action(index);
  23104. }
  23105. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23106. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23107. var step = _c[_b];
  23108. step.action(index);
  23109. }
  23110. // After Observable
  23111. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23112. }
  23113. };
  23114. RenderingManager.prototype.reset = function () {
  23115. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23116. var renderingGroup = this._renderingGroups[index];
  23117. if (renderingGroup) {
  23118. renderingGroup.prepare();
  23119. }
  23120. }
  23121. };
  23122. RenderingManager.prototype.dispose = function () {
  23123. this.freeRenderingGroups();
  23124. this._renderingGroups.length = 0;
  23125. this._renderingGroupInfo = null;
  23126. };
  23127. /**
  23128. * Clear the info related to rendering groups preventing retention points during dispose.
  23129. */
  23130. RenderingManager.prototype.freeRenderingGroups = function () {
  23131. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23132. var renderingGroup = this._renderingGroups[index];
  23133. if (renderingGroup) {
  23134. renderingGroup.dispose();
  23135. }
  23136. }
  23137. };
  23138. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23139. if (this._renderingGroups[renderingGroupId] === undefined) {
  23140. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23141. }
  23142. };
  23143. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23144. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23145. this._prepareRenderingGroup(renderingGroupId);
  23146. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23147. };
  23148. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23149. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23150. this._prepareRenderingGroup(renderingGroupId);
  23151. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23152. };
  23153. /**
  23154. * @param subMesh The submesh to dispatch
  23155. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23156. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23157. */
  23158. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23159. if (mesh === undefined) {
  23160. mesh = subMesh.getMesh();
  23161. }
  23162. var renderingGroupId = mesh.renderingGroupId || 0;
  23163. this._prepareRenderingGroup(renderingGroupId);
  23164. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23165. };
  23166. /**
  23167. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23168. * This allowed control for front to back rendering or reversly depending of the special needs.
  23169. *
  23170. * @param renderingGroupId The rendering group id corresponding to its index
  23171. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23172. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23173. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23174. */
  23175. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23176. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23177. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23178. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23179. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23180. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23181. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23182. if (this._renderingGroups[renderingGroupId]) {
  23183. var group = this._renderingGroups[renderingGroupId];
  23184. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23185. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23186. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23187. }
  23188. };
  23189. /**
  23190. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23191. *
  23192. * @param renderingGroupId The rendering group id corresponding to its index
  23193. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23194. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23195. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23196. */
  23197. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23198. if (depth === void 0) { depth = true; }
  23199. if (stencil === void 0) { stencil = true; }
  23200. this._autoClearDepthStencil[renderingGroupId] = {
  23201. autoClear: autoClearDepthStencil,
  23202. depth: depth,
  23203. stencil: stencil
  23204. };
  23205. };
  23206. /**
  23207. * Gets the current auto clear configuration for one rendering group of the rendering
  23208. * manager.
  23209. * @param index the rendering group index to get the information for
  23210. * @returns The auto clear setup for the requested rendering group
  23211. */
  23212. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23213. return this._autoClearDepthStencil[index];
  23214. };
  23215. /**
  23216. * The max id used for rendering groups (not included)
  23217. */
  23218. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23219. /**
  23220. * The min id used for rendering groups (included)
  23221. */
  23222. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23223. /**
  23224. * Used to globally prevent autoclearing scenes.
  23225. */
  23226. RenderingManager.AUTOCLEAR = true;
  23227. return RenderingManager;
  23228. }());
  23229. BABYLON.RenderingManager = RenderingManager;
  23230. })(BABYLON || (BABYLON = {}));
  23231. //# sourceMappingURL=babylon.renderingManager.js.map
  23232. var BABYLON;
  23233. (function (BABYLON) {
  23234. var RenderingGroup = /** @class */ (function () {
  23235. /**
  23236. * Creates a new rendering group.
  23237. * @param index The rendering group index
  23238. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23239. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23240. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23241. */
  23242. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23243. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23244. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23245. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23246. this.index = index;
  23247. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23248. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23249. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23250. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23251. this._particleSystems = new BABYLON.SmartArray(256);
  23252. this._spriteManagers = new BABYLON.SmartArray(256);
  23253. this._edgesRenderers = new BABYLON.SmartArray(16);
  23254. this._scene = scene;
  23255. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23256. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23257. this.transparentSortCompareFn = transparentSortCompareFn;
  23258. }
  23259. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23260. /**
  23261. * Set the opaque sort comparison function.
  23262. * If null the sub meshes will be render in the order they were created
  23263. */
  23264. set: function (value) {
  23265. this._opaqueSortCompareFn = value;
  23266. if (value) {
  23267. this._renderOpaque = this.renderOpaqueSorted;
  23268. }
  23269. else {
  23270. this._renderOpaque = RenderingGroup.renderUnsorted;
  23271. }
  23272. },
  23273. enumerable: true,
  23274. configurable: true
  23275. });
  23276. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23277. /**
  23278. * Set the alpha test sort comparison function.
  23279. * If null the sub meshes will be render in the order they were created
  23280. */
  23281. set: function (value) {
  23282. this._alphaTestSortCompareFn = value;
  23283. if (value) {
  23284. this._renderAlphaTest = this.renderAlphaTestSorted;
  23285. }
  23286. else {
  23287. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23288. }
  23289. },
  23290. enumerable: true,
  23291. configurable: true
  23292. });
  23293. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23294. /**
  23295. * Set the transparent sort comparison function.
  23296. * If null the sub meshes will be render in the order they were created
  23297. */
  23298. set: function (value) {
  23299. if (value) {
  23300. this._transparentSortCompareFn = value;
  23301. }
  23302. else {
  23303. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23304. }
  23305. this._renderTransparent = this.renderTransparentSorted;
  23306. },
  23307. enumerable: true,
  23308. configurable: true
  23309. });
  23310. /**
  23311. * Render all the sub meshes contained in the group.
  23312. * @param customRenderFunction Used to override the default render behaviour of the group.
  23313. * @returns true if rendered some submeshes.
  23314. */
  23315. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23316. if (customRenderFunction) {
  23317. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23318. return;
  23319. }
  23320. var engine = this._scene.getEngine();
  23321. // Depth only
  23322. if (this._depthOnlySubMeshes.length !== 0) {
  23323. engine.setColorWrite(false);
  23324. this._renderAlphaTest(this._depthOnlySubMeshes);
  23325. engine.setColorWrite(true);
  23326. }
  23327. // Opaque
  23328. if (this._opaqueSubMeshes.length !== 0) {
  23329. this._renderOpaque(this._opaqueSubMeshes);
  23330. }
  23331. // Alpha test
  23332. if (this._alphaTestSubMeshes.length !== 0) {
  23333. this._renderAlphaTest(this._alphaTestSubMeshes);
  23334. }
  23335. var stencilState = engine.getStencilBuffer();
  23336. engine.setStencilBuffer(false);
  23337. // Sprites
  23338. if (renderSprites) {
  23339. this._renderSprites();
  23340. }
  23341. // Particles
  23342. if (renderParticles) {
  23343. this._renderParticles(activeMeshes);
  23344. }
  23345. if (this.onBeforeTransparentRendering) {
  23346. this.onBeforeTransparentRendering();
  23347. }
  23348. // Transparent
  23349. if (this._transparentSubMeshes.length !== 0) {
  23350. this._renderTransparent(this._transparentSubMeshes);
  23351. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23352. }
  23353. // Set back stencil to false in case it changes before the edge renderer.
  23354. engine.setStencilBuffer(false);
  23355. // Edges
  23356. if (this._edgesRenderers.length) {
  23357. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23358. this._edgesRenderers.data[edgesRendererIndex].render();
  23359. }
  23360. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23361. }
  23362. // Restore Stencil state.
  23363. engine.setStencilBuffer(stencilState);
  23364. };
  23365. /**
  23366. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23367. * @param subMeshes The submeshes to render
  23368. */
  23369. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23370. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23371. };
  23372. /**
  23373. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23374. * @param subMeshes The submeshes to render
  23375. */
  23376. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23377. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23378. };
  23379. /**
  23380. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23381. * @param subMeshes The submeshes to render
  23382. */
  23383. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23384. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23385. };
  23386. /**
  23387. * Renders the submeshes in a specified order.
  23388. * @param subMeshes The submeshes to sort before render
  23389. * @param sortCompareFn The comparison function use to sort
  23390. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23391. * @param transparent Specifies to activate blending if true
  23392. */
  23393. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23394. var subIndex = 0;
  23395. var subMesh;
  23396. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23397. for (; subIndex < subMeshes.length; subIndex++) {
  23398. subMesh = subMeshes.data[subIndex];
  23399. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23400. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23401. }
  23402. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23403. if (sortCompareFn) {
  23404. sortedArray.sort(sortCompareFn);
  23405. }
  23406. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23407. subMesh = sortedArray[subIndex];
  23408. if (transparent) {
  23409. var material = subMesh.getMaterial();
  23410. if (material && material.needDepthPrePass) {
  23411. var engine = material.getScene().getEngine();
  23412. engine.setColorWrite(false);
  23413. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23414. subMesh.render(false);
  23415. engine.setColorWrite(true);
  23416. }
  23417. }
  23418. subMesh.render(transparent);
  23419. }
  23420. };
  23421. /**
  23422. * Renders the submeshes in the order they were dispatched (no sort applied).
  23423. * @param subMeshes The submeshes to render
  23424. */
  23425. RenderingGroup.renderUnsorted = function (subMeshes) {
  23426. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23427. var submesh = subMeshes.data[subIndex];
  23428. submesh.render(false);
  23429. }
  23430. };
  23431. /**
  23432. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23433. * are rendered back to front if in the same alpha index.
  23434. *
  23435. * @param a The first submesh
  23436. * @param b The second submesh
  23437. * @returns The result of the comparison
  23438. */
  23439. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23440. // Alpha index first
  23441. if (a._alphaIndex > b._alphaIndex) {
  23442. return 1;
  23443. }
  23444. if (a._alphaIndex < b._alphaIndex) {
  23445. return -1;
  23446. }
  23447. // Then distance to camera
  23448. return RenderingGroup.backToFrontSortCompare(a, b);
  23449. };
  23450. /**
  23451. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23452. * are rendered back to front.
  23453. *
  23454. * @param a The first submesh
  23455. * @param b The second submesh
  23456. * @returns The result of the comparison
  23457. */
  23458. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23459. // Then distance to camera
  23460. if (a._distanceToCamera < b._distanceToCamera) {
  23461. return 1;
  23462. }
  23463. if (a._distanceToCamera > b._distanceToCamera) {
  23464. return -1;
  23465. }
  23466. return 0;
  23467. };
  23468. /**
  23469. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23470. * are rendered front to back (prevent overdraw).
  23471. *
  23472. * @param a The first submesh
  23473. * @param b The second submesh
  23474. * @returns The result of the comparison
  23475. */
  23476. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23477. // Then distance to camera
  23478. if (a._distanceToCamera < b._distanceToCamera) {
  23479. return -1;
  23480. }
  23481. if (a._distanceToCamera > b._distanceToCamera) {
  23482. return 1;
  23483. }
  23484. return 0;
  23485. };
  23486. /**
  23487. * Resets the different lists of submeshes to prepare a new frame.
  23488. */
  23489. RenderingGroup.prototype.prepare = function () {
  23490. this._opaqueSubMeshes.reset();
  23491. this._transparentSubMeshes.reset();
  23492. this._alphaTestSubMeshes.reset();
  23493. this._depthOnlySubMeshes.reset();
  23494. this._particleSystems.reset();
  23495. this._spriteManagers.reset();
  23496. this._edgesRenderers.reset();
  23497. };
  23498. RenderingGroup.prototype.dispose = function () {
  23499. this._opaqueSubMeshes.dispose();
  23500. this._transparentSubMeshes.dispose();
  23501. this._alphaTestSubMeshes.dispose();
  23502. this._depthOnlySubMeshes.dispose();
  23503. this._particleSystems.dispose();
  23504. this._spriteManagers.dispose();
  23505. this._edgesRenderers.dispose();
  23506. };
  23507. /**
  23508. * Inserts the submesh in its correct queue depending on its material.
  23509. * @param subMesh The submesh to dispatch
  23510. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23511. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23512. */
  23513. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23514. // Get mesh and materials if not provided
  23515. if (mesh === undefined) {
  23516. mesh = subMesh.getMesh();
  23517. }
  23518. if (material === undefined) {
  23519. material = subMesh.getMaterial();
  23520. }
  23521. if (material === null || material === undefined) {
  23522. return;
  23523. }
  23524. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23525. this._transparentSubMeshes.push(subMesh);
  23526. }
  23527. else if (material.needAlphaTesting()) { // Alpha test
  23528. if (material.needDepthPrePass) {
  23529. this._depthOnlySubMeshes.push(subMesh);
  23530. }
  23531. this._alphaTestSubMeshes.push(subMesh);
  23532. }
  23533. else {
  23534. if (material.needDepthPrePass) {
  23535. this._depthOnlySubMeshes.push(subMesh);
  23536. }
  23537. this._opaqueSubMeshes.push(subMesh); // Opaque
  23538. }
  23539. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23540. this._edgesRenderers.push(mesh._edgesRenderer);
  23541. }
  23542. };
  23543. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23544. this._spriteManagers.push(spriteManager);
  23545. };
  23546. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23547. this._particleSystems.push(particleSystem);
  23548. };
  23549. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23550. if (this._particleSystems.length === 0) {
  23551. return;
  23552. }
  23553. // Particles
  23554. var activeCamera = this._scene.activeCamera;
  23555. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23556. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23557. var particleSystem = this._particleSystems.data[particleIndex];
  23558. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23559. continue;
  23560. }
  23561. var emitter = particleSystem.emitter;
  23562. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23563. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23564. }
  23565. }
  23566. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23567. };
  23568. RenderingGroup.prototype._renderSprites = function () {
  23569. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23570. return;
  23571. }
  23572. // Sprites
  23573. var activeCamera = this._scene.activeCamera;
  23574. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23575. for (var id = 0; id < this._spriteManagers.length; id++) {
  23576. var spriteManager = this._spriteManagers.data[id];
  23577. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23578. spriteManager.render();
  23579. }
  23580. }
  23581. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23582. };
  23583. return RenderingGroup;
  23584. }());
  23585. BABYLON.RenderingGroup = RenderingGroup;
  23586. })(BABYLON || (BABYLON = {}));
  23587. //# sourceMappingURL=babylon.renderingGroup.js.map
  23588. var BABYLON;
  23589. (function (BABYLON) {
  23590. /**
  23591. * Groups all the scene component constants in one place to ease maintenance.
  23592. * @hidden
  23593. */
  23594. var SceneComponentConstants = /** @class */ (function () {
  23595. function SceneComponentConstants() {
  23596. }
  23597. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23598. SceneComponentConstants.NAME_LAYER = "Layer";
  23599. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23600. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23601. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23602. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23603. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23604. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23605. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23606. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23607. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23608. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23609. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23610. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23611. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23612. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23613. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23614. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23615. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23616. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23617. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23618. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  23619. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23620. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23621. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23622. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23623. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23624. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23625. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23626. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23627. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23628. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23629. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  23630. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  23631. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  23632. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  23633. SceneComponentConstants.STEP_REBUILDGEOMETRY_POSTPROCESSRENDERPIPELINEMANAGER = 0;
  23634. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  23635. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  23636. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  23637. return SceneComponentConstants;
  23638. }());
  23639. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23640. /**
  23641. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23642. * @hidden
  23643. */
  23644. var Stage = /** @class */ (function (_super) {
  23645. __extends(Stage, _super);
  23646. /**
  23647. * Hide ctor from the rest of the world.
  23648. * @param items The items to add.
  23649. */
  23650. function Stage(items) {
  23651. return _super.apply(this, items) || this;
  23652. }
  23653. /**
  23654. * Creates a new Stage.
  23655. * @returns A new instance of a Stage
  23656. */
  23657. Stage.Create = function () {
  23658. return Object.create(Stage.prototype);
  23659. };
  23660. /**
  23661. * Registers a step in an ordered way in the targeted stage.
  23662. * @param index Defines the position to register the step in
  23663. * @param component Defines the component attached to the step
  23664. * @param action Defines the action to launch during the step
  23665. */
  23666. Stage.prototype.registerStep = function (index, component, action) {
  23667. var i = 0;
  23668. var maxIndex = Number.MAX_VALUE;
  23669. for (; i < this.length && i < maxIndex; i++) {
  23670. var step = this[i];
  23671. maxIndex = step.index;
  23672. }
  23673. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23674. };
  23675. /**
  23676. * Clears all the steps from the stage.
  23677. */
  23678. Stage.prototype.clear = function () {
  23679. this.length = 0;
  23680. };
  23681. return Stage;
  23682. }(Array));
  23683. BABYLON.Stage = Stage;
  23684. })(BABYLON || (BABYLON = {}));
  23685. //# sourceMappingURL=babylon.sceneComponent.js.map
  23686. var BABYLON;
  23687. (function (BABYLON) {
  23688. /**
  23689. * Base class of the scene acting as a container for the different elements composing a scene.
  23690. * This class is dynamically extended by the different components of the scene increasing
  23691. * flexibility and reducing coupling
  23692. */
  23693. var AbstractScene = /** @class */ (function () {
  23694. function AbstractScene() {
  23695. /**
  23696. * Gets the list of root nodes (ie. nodes with no parent)
  23697. */
  23698. this.rootNodes = new Array();
  23699. /** All of the cameras added to this scene
  23700. * @see http://doc.babylonjs.com/babylon101/cameras
  23701. */
  23702. this.cameras = new Array();
  23703. /**
  23704. * All of the lights added to this scene
  23705. * @see http://doc.babylonjs.com/babylon101/lights
  23706. */
  23707. this.lights = new Array();
  23708. /**
  23709. * All of the (abstract) meshes added to this scene
  23710. */
  23711. this.meshes = new Array();
  23712. /**
  23713. * The list of skeletons added to the scene
  23714. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23715. */
  23716. this.skeletons = new Array();
  23717. /**
  23718. * All of the particle systems added to this scene
  23719. * @see http://doc.babylonjs.com/babylon101/particles
  23720. */
  23721. this.particleSystems = new Array();
  23722. /**
  23723. * Gets a list of Animations associated with the scene
  23724. */
  23725. this.animations = [];
  23726. /**
  23727. * All of the animation groups added to this scene
  23728. * @see http://doc.babylonjs.com/how_to/group
  23729. */
  23730. this.animationGroups = new Array();
  23731. /**
  23732. * All of the multi-materials added to this scene
  23733. * @see http://doc.babylonjs.com/how_to/multi_materials
  23734. */
  23735. this.multiMaterials = new Array();
  23736. /**
  23737. * All of the materials added to this scene
  23738. * @see http://doc.babylonjs.com/babylon101/materials
  23739. */
  23740. this.materials = new Array();
  23741. /**
  23742. * The list of morph target managers added to the scene
  23743. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23744. */
  23745. this.morphTargetManagers = new Array();
  23746. /**
  23747. * The list of geometries used in the scene.
  23748. */
  23749. this.geometries = new Array();
  23750. /**
  23751. * All of the tranform nodes added to this scene
  23752. * @see http://doc.babylonjs.com/how_to/transformnode
  23753. */
  23754. this.transformNodes = new Array();
  23755. /**
  23756. * ActionManagers available on the scene.
  23757. */
  23758. this.actionManagers = new Array();
  23759. /**
  23760. * Sounds to keep.
  23761. */
  23762. this.sounds = new Array();
  23763. /**
  23764. * Textures to keep.
  23765. */
  23766. this.textures = new Array();
  23767. }
  23768. /**
  23769. * Adds a parser in the list of available ones
  23770. * @param name Defines the name of the parser
  23771. * @param parser Defines the parser to add
  23772. */
  23773. AbstractScene.AddParser = function (name, parser) {
  23774. this._BabylonFileParsers[name] = parser;
  23775. };
  23776. /**
  23777. * Gets a general parser from the list of avaialble ones
  23778. * @param name Defines the name of the parser
  23779. * @returns the requested parser or null
  23780. */
  23781. AbstractScene.GetParser = function (name) {
  23782. if (this._BabylonFileParsers[name]) {
  23783. return this._BabylonFileParsers[name];
  23784. }
  23785. return null;
  23786. };
  23787. /**
  23788. * Adds n individual parser in the list of available ones
  23789. * @param name Defines the name of the parser
  23790. * @param parser Defines the parser to add
  23791. */
  23792. AbstractScene.AddIndividualParser = function (name, parser) {
  23793. this._IndividualBabylonFileParsers[name] = parser;
  23794. };
  23795. /**
  23796. * Gets an individual parser from the list of avaialble ones
  23797. * @param name Defines the name of the parser
  23798. * @returns the requested parser or null
  23799. */
  23800. AbstractScene.GetIndividualParser = function (name) {
  23801. if (this._IndividualBabylonFileParsers[name]) {
  23802. return this._IndividualBabylonFileParsers[name];
  23803. }
  23804. return null;
  23805. };
  23806. /**
  23807. * Parser json data and populate both a scene and its associated container object
  23808. * @param jsonData Defines the data to parse
  23809. * @param scene Defines the scene to parse the data for
  23810. * @param container Defines the container attached to the parsing sequence
  23811. * @param rootUrl Defines the root url of the data
  23812. */
  23813. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23814. for (var parserName in this._BabylonFileParsers) {
  23815. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23816. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23817. }
  23818. }
  23819. };
  23820. /**
  23821. * Stores the list of available parsers in the application.
  23822. */
  23823. AbstractScene._BabylonFileParsers = {};
  23824. /**
  23825. * Stores the list of available individual parsers in the application.
  23826. */
  23827. AbstractScene._IndividualBabylonFileParsers = {};
  23828. return AbstractScene;
  23829. }());
  23830. BABYLON.AbstractScene = AbstractScene;
  23831. })(BABYLON || (BABYLON = {}));
  23832. //# sourceMappingURL=babylon.abstractScene.js.map
  23833. var BABYLON;
  23834. (function (BABYLON) {
  23835. /** @hidden */
  23836. var ClickInfo = /** @class */ (function () {
  23837. function ClickInfo() {
  23838. this._singleClick = false;
  23839. this._doubleClick = false;
  23840. this._hasSwiped = false;
  23841. this._ignore = false;
  23842. }
  23843. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23844. get: function () {
  23845. return this._singleClick;
  23846. },
  23847. set: function (b) {
  23848. this._singleClick = b;
  23849. },
  23850. enumerable: true,
  23851. configurable: true
  23852. });
  23853. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23854. get: function () {
  23855. return this._doubleClick;
  23856. },
  23857. set: function (b) {
  23858. this._doubleClick = b;
  23859. },
  23860. enumerable: true,
  23861. configurable: true
  23862. });
  23863. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23864. get: function () {
  23865. return this._hasSwiped;
  23866. },
  23867. set: function (b) {
  23868. this._hasSwiped = b;
  23869. },
  23870. enumerable: true,
  23871. configurable: true
  23872. });
  23873. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23874. get: function () {
  23875. return this._ignore;
  23876. },
  23877. set: function (b) {
  23878. this._ignore = b;
  23879. },
  23880. enumerable: true,
  23881. configurable: true
  23882. });
  23883. return ClickInfo;
  23884. }());
  23885. /**
  23886. * This class is used by the onRenderingGroupObservable
  23887. */
  23888. var RenderingGroupInfo = /** @class */ (function () {
  23889. function RenderingGroupInfo() {
  23890. }
  23891. return RenderingGroupInfo;
  23892. }());
  23893. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23894. /**
  23895. * Represents a scene to be rendered by the engine.
  23896. * @see http://doc.babylonjs.com/features/scene
  23897. */
  23898. var Scene = /** @class */ (function (_super) {
  23899. __extends(Scene, _super);
  23900. /**
  23901. * Creates a new Scene
  23902. * @param engine defines the engine to use to render this scene
  23903. */
  23904. function Scene(engine) {
  23905. var _this = _super.call(this) || this;
  23906. // Members
  23907. /**
  23908. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23909. */
  23910. _this.autoClear = true;
  23911. /**
  23912. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23913. */
  23914. _this.autoClearDepthAndStencil = true;
  23915. /**
  23916. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23917. */
  23918. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23919. /**
  23920. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23921. */
  23922. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23923. _this._forceWireframe = false;
  23924. _this._forcePointsCloud = false;
  23925. /**
  23926. * Gets or sets a boolean indicating if animations are enabled
  23927. */
  23928. _this.animationsEnabled = true;
  23929. _this._animationPropertiesOverride = null;
  23930. /**
  23931. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23932. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23933. */
  23934. _this.useConstantAnimationDeltaTime = false;
  23935. /**
  23936. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23937. * Please note that it requires to run a ray cast through the scene on every frame
  23938. */
  23939. _this.constantlyUpdateMeshUnderPointer = false;
  23940. /**
  23941. * Defines the HTML cursor to use when hovering over interactive elements
  23942. */
  23943. _this.hoverCursor = "pointer";
  23944. /**
  23945. * Defines the HTML default cursor to use (empty by default)
  23946. */
  23947. _this.defaultCursor = "";
  23948. /**
  23949. * This is used to call preventDefault() on pointer down
  23950. * in order to block unwanted artifacts like system double clicks
  23951. */
  23952. _this.preventDefaultOnPointerDown = true;
  23953. // Metadata
  23954. /**
  23955. * Gets or sets user defined metadata
  23956. */
  23957. _this.metadata = null;
  23958. /**
  23959. * Use this array to add regular expressions used to disable offline support for specific urls
  23960. */
  23961. _this.disableOfflineSupportExceptionRules = new Array();
  23962. /**
  23963. * An event triggered when the scene is disposed.
  23964. */
  23965. _this.onDisposeObservable = new BABYLON.Observable();
  23966. _this._onDisposeObserver = null;
  23967. /**
  23968. * An event triggered before rendering the scene (right after animations and physics)
  23969. */
  23970. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23971. _this._onBeforeRenderObserver = null;
  23972. /**
  23973. * An event triggered after rendering the scene
  23974. */
  23975. _this.onAfterRenderObservable = new BABYLON.Observable();
  23976. _this._onAfterRenderObserver = null;
  23977. /**
  23978. * An event triggered before animating the scene
  23979. */
  23980. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23981. /**
  23982. * An event triggered after animations processing
  23983. */
  23984. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23985. /**
  23986. * An event triggered before draw calls are ready to be sent
  23987. */
  23988. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23989. /**
  23990. * An event triggered after draw calls have been sent
  23991. */
  23992. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23993. /**
  23994. * An event triggered when physic simulation is about to be run
  23995. */
  23996. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23997. /**
  23998. * An event triggered when physic simulation has been done
  23999. */
  24000. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24001. /**
  24002. * An event triggered when the scene is ready
  24003. */
  24004. _this.onReadyObservable = new BABYLON.Observable();
  24005. /**
  24006. * An event triggered before rendering a camera
  24007. */
  24008. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24009. _this._onBeforeCameraRenderObserver = null;
  24010. /**
  24011. * An event triggered after rendering a camera
  24012. */
  24013. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24014. _this._onAfterCameraRenderObserver = null;
  24015. /**
  24016. * An event triggered when active meshes evaluation is about to start
  24017. */
  24018. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24019. /**
  24020. * An event triggered when active meshes evaluation is done
  24021. */
  24022. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24023. /**
  24024. * An event triggered when particles rendering is about to start
  24025. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24026. */
  24027. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24028. /**
  24029. * An event triggered when particles rendering is done
  24030. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24031. */
  24032. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24033. /**
  24034. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24035. */
  24036. _this.onDataLoadedObservable = new BABYLON.Observable();
  24037. /**
  24038. * An event triggered when a camera is created
  24039. */
  24040. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24041. /**
  24042. * An event triggered when a camera is removed
  24043. */
  24044. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24045. /**
  24046. * An event triggered when a light is created
  24047. */
  24048. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24049. /**
  24050. * An event triggered when a light is removed
  24051. */
  24052. _this.onLightRemovedObservable = new BABYLON.Observable();
  24053. /**
  24054. * An event triggered when a geometry is created
  24055. */
  24056. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24057. /**
  24058. * An event triggered when a geometry is removed
  24059. */
  24060. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24061. /**
  24062. * An event triggered when a transform node is created
  24063. */
  24064. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24065. /**
  24066. * An event triggered when a transform node is removed
  24067. */
  24068. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24069. /**
  24070. * An event triggered when a mesh is created
  24071. */
  24072. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24073. /**
  24074. * An event triggered when a mesh is removed
  24075. */
  24076. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24077. /**
  24078. * An event triggered when render targets are about to be rendered
  24079. * Can happen multiple times per frame.
  24080. */
  24081. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24082. /**
  24083. * An event triggered when render targets were rendered.
  24084. * Can happen multiple times per frame.
  24085. */
  24086. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24087. /**
  24088. * An event triggered before calculating deterministic simulation step
  24089. */
  24090. _this.onBeforeStepObservable = new BABYLON.Observable();
  24091. /**
  24092. * An event triggered after calculating deterministic simulation step
  24093. */
  24094. _this.onAfterStepObservable = new BABYLON.Observable();
  24095. /**
  24096. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24097. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24098. * 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)
  24099. */
  24100. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24101. /**
  24102. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24103. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24104. * 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)
  24105. */
  24106. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24107. // Animations
  24108. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24109. /**
  24110. * 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).
  24111. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24112. */
  24113. _this.onPrePointerObservable = new BABYLON.Observable();
  24114. /**
  24115. * Observable event triggered each time an input event is received from the rendering canvas
  24116. */
  24117. _this.onPointerObservable = new BABYLON.Observable();
  24118. _this._meshPickProceed = false;
  24119. _this._currentPickResult = null;
  24120. _this._previousPickResult = null;
  24121. _this._totalPointersPressed = 0;
  24122. _this._doubleClickOccured = false;
  24123. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24124. _this.cameraToUseForPointers = null;
  24125. _this._pointerX = 0;
  24126. _this._pointerY = 0;
  24127. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24128. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24129. _this._startingPointerTime = 0;
  24130. _this._previousStartingPointerTime = 0;
  24131. _this._pointerCaptures = {};
  24132. // Deterministic lockstep
  24133. _this._timeAccumulator = 0;
  24134. _this._currentStepId = 0;
  24135. _this._currentInternalStep = 0;
  24136. // Keyboard
  24137. /**
  24138. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24139. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24140. */
  24141. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24142. /**
  24143. * Observable event triggered each time an keyboard event is received from the hosting window
  24144. */
  24145. _this.onKeyboardObservable = new BABYLON.Observable();
  24146. // Coordinates system
  24147. _this._useRightHandedSystem = false;
  24148. // Fog
  24149. _this._fogEnabled = true;
  24150. _this._fogMode = Scene.FOGMODE_NONE;
  24151. /**
  24152. * Gets or sets the fog color to use
  24153. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24154. */
  24155. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24156. /**
  24157. * Gets or sets the fog density to use
  24158. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24159. */
  24160. _this.fogDensity = 0.1;
  24161. /**
  24162. * Gets or sets the fog start distance to use
  24163. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24164. */
  24165. _this.fogStart = 0;
  24166. /**
  24167. * Gets or sets the fog end distance to use
  24168. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24169. */
  24170. _this.fogEnd = 1000.0;
  24171. // Lights
  24172. _this._shadowsEnabled = true;
  24173. _this._lightsEnabled = true;
  24174. /** All of the active cameras added to this scene. */
  24175. _this.activeCameras = new Array();
  24176. // Textures
  24177. _this._texturesEnabled = true;
  24178. // Particles
  24179. /**
  24180. * Gets or sets a boolean indicating if particles are enabled on this scene
  24181. */
  24182. _this.particlesEnabled = true;
  24183. // Sprites
  24184. /**
  24185. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24186. */
  24187. _this.spritesEnabled = true;
  24188. // Skeletons
  24189. _this._skeletonsEnabled = true;
  24190. // Lens flares
  24191. /**
  24192. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24193. */
  24194. _this.lensFlaresEnabled = true;
  24195. // Collisions
  24196. /**
  24197. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24198. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24199. */
  24200. _this.collisionsEnabled = true;
  24201. /**
  24202. * Defines the gravity applied to this scene (used only for collisions)
  24203. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24204. */
  24205. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24206. // Postprocesses
  24207. /**
  24208. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24209. */
  24210. _this.postProcessesEnabled = true;
  24211. /**
  24212. * The list of postprocesses added to the scene
  24213. */
  24214. _this.postProcesses = new Array();
  24215. // Customs render targets
  24216. /**
  24217. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24218. */
  24219. _this.renderTargetsEnabled = true;
  24220. /**
  24221. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24222. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24223. */
  24224. _this.dumpNextRenderTargets = false;
  24225. /**
  24226. * The list of user defined render targets added to the scene
  24227. */
  24228. _this.customRenderTargets = new Array();
  24229. /**
  24230. * Gets the list of meshes imported to the scene through SceneLoader
  24231. */
  24232. _this.importedMeshesFiles = new Array();
  24233. // Probes
  24234. /**
  24235. * Gets or sets a boolean indicating if probes are enabled on this scene
  24236. */
  24237. _this.probesEnabled = true;
  24238. /**
  24239. * The list of reflection probes added to the scene
  24240. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24241. */
  24242. _this.reflectionProbes = new Array();
  24243. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24244. // Procedural textures
  24245. /**
  24246. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24247. */
  24248. _this.proceduralTexturesEnabled = true;
  24249. /**
  24250. * The list of sound tracks added to the scene
  24251. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24252. */
  24253. _this.soundTracks = new Array();
  24254. _this._audioEnabled = true;
  24255. _this._headphone = false;
  24256. // Performance counters
  24257. _this._totalVertices = new BABYLON.PerfCounter();
  24258. /** @hidden */
  24259. _this._activeIndices = new BABYLON.PerfCounter();
  24260. /** @hidden */
  24261. _this._activeParticles = new BABYLON.PerfCounter();
  24262. /** @hidden */
  24263. _this._activeBones = new BABYLON.PerfCounter();
  24264. _this._animationTime = 0;
  24265. /**
  24266. * Gets or sets a general scale for animation speed
  24267. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24268. */
  24269. _this.animationTimeScale = 1;
  24270. _this._renderId = 0;
  24271. _this._executeWhenReadyTimeoutId = -1;
  24272. _this._intermediateRendering = false;
  24273. _this._viewUpdateFlag = -1;
  24274. _this._projectionUpdateFlag = -1;
  24275. _this._alternateViewUpdateFlag = -1;
  24276. _this._alternateProjectionUpdateFlag = -1;
  24277. /** @hidden */
  24278. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24279. _this._activeRequests = new Array();
  24280. _this._pendingData = new Array();
  24281. _this._isDisposed = false;
  24282. /**
  24283. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24284. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24285. */
  24286. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24287. _this._activeMeshes = new BABYLON.SmartArray(256);
  24288. _this._processedMaterials = new BABYLON.SmartArray(256);
  24289. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24290. /** @hidden */
  24291. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24292. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24293. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24294. /** @hidden */
  24295. _this._activeAnimatables = new Array();
  24296. _this._transformMatrix = BABYLON.Matrix.Zero();
  24297. _this._useAlternateCameraConfiguration = false;
  24298. _this._alternateRendering = false;
  24299. /**
  24300. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24301. * This is useful if there are more lights that the maximum simulteanous authorized
  24302. */
  24303. _this.requireLightSorting = false;
  24304. /**
  24305. * @hidden
  24306. * Backing store of defined scene components.
  24307. */
  24308. _this._components = [];
  24309. /**
  24310. * @hidden
  24311. * Backing store of defined scene components.
  24312. */
  24313. _this._serializableComponents = [];
  24314. /**
  24315. * List of components to register on the next registration step.
  24316. */
  24317. _this._transientComponents = [];
  24318. /**
  24319. * @hidden
  24320. * Defines the actions happening before camera updates.
  24321. */
  24322. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24323. /**
  24324. * @hidden
  24325. * Defines the actions happening before clear the canvas.
  24326. */
  24327. _this._beforeClearStage = BABYLON.Stage.Create();
  24328. /**
  24329. * @hidden
  24330. * Defines the actions happening before camera updates.
  24331. */
  24332. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24333. /**
  24334. * @hidden
  24335. * Defines the actions happening during the per mesh ready checks.
  24336. */
  24337. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24338. /**
  24339. * @hidden
  24340. * Defines the actions happening before evaluate active mesh checks.
  24341. */
  24342. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24343. /**
  24344. * @hidden
  24345. * Defines the actions happening during the evaluate sub mesh checks.
  24346. */
  24347. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24348. /**
  24349. * @hidden
  24350. * Defines the actions happening during the active mesh stage.
  24351. */
  24352. _this._activeMeshStage = BABYLON.Stage.Create();
  24353. /**
  24354. * @hidden
  24355. * Defines the actions happening during the per camera render target step.
  24356. */
  24357. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24358. /**
  24359. * @hidden
  24360. * Defines the actions happening just before the active camera is drawing.
  24361. */
  24362. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24363. /**
  24364. * @hidden
  24365. * Defines the actions happening just before a rendering group is drawing.
  24366. */
  24367. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24368. /**
  24369. * @hidden
  24370. * Defines the actions happening just before a mesh is drawing.
  24371. */
  24372. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24373. /**
  24374. * @hidden
  24375. * Defines the actions happening just after a mesh has been drawn.
  24376. */
  24377. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24378. /**
  24379. * @hidden
  24380. * Defines the actions happening just after a rendering group has been drawn.
  24381. */
  24382. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24383. /**
  24384. * @hidden
  24385. * Defines the actions happening just after the active camera has been drawn.
  24386. */
  24387. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24388. /**
  24389. * @hidden
  24390. * Defines the actions happening when Geometries are rebuilding.
  24391. */
  24392. _this._rebuildGeometryStage = BABYLON.Stage.Create();
  24393. /**
  24394. * @hidden
  24395. * Defines the actions happening when a pointer move event happens.
  24396. */
  24397. _this._pointerMoveStage = BABYLON.Stage.Create();
  24398. /**
  24399. * @hidden
  24400. * Defines the actions happening when a pointer down event happens.
  24401. */
  24402. _this._pointerDownStage = BABYLON.Stage.Create();
  24403. /**
  24404. * @hidden
  24405. * Defines the actions happening when a pointer up event happens.
  24406. */
  24407. _this._pointerUpStage = BABYLON.Stage.Create();
  24408. _this._activeMeshesFrozen = false;
  24409. /** @hidden */
  24410. _this._allowPostProcessClearColor = true;
  24411. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24412. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24413. _this.blockMaterialDirtyMechanism = false;
  24414. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24415. _this._engine.scenes.push(_this);
  24416. _this._uid = null;
  24417. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24418. if (BABYLON.PostProcessManager) {
  24419. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24420. }
  24421. if (BABYLON.Tools.IsWindowObjectExist()) {
  24422. _this.attachControl();
  24423. }
  24424. //collision coordinator initialization. For now legacy per default.
  24425. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24426. // Uniform Buffer
  24427. _this._createUbo();
  24428. // Default Image processing definition
  24429. if (BABYLON.ImageProcessingConfiguration) {
  24430. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24431. }
  24432. return _this;
  24433. }
  24434. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24435. /**
  24436. * Texture used in all pbr material as the reflection texture.
  24437. * As in the majority of the scene they are the same (exception for multi room and so on),
  24438. * this is easier to reference from here than from all the materials.
  24439. */
  24440. get: function () {
  24441. return this._environmentTexture;
  24442. },
  24443. /**
  24444. * Texture used in all pbr material as the reflection texture.
  24445. * As in the majority of the scene they are the same (exception for multi room and so on),
  24446. * this is easier to set here than in all the materials.
  24447. */
  24448. set: function (value) {
  24449. if (this._environmentTexture === value) {
  24450. return;
  24451. }
  24452. this._environmentTexture = value;
  24453. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24454. },
  24455. enumerable: true,
  24456. configurable: true
  24457. });
  24458. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24459. /**
  24460. * Default image processing configuration used either in the rendering
  24461. * Forward main pass or through the imageProcessingPostProcess if present.
  24462. * As in the majority of the scene they are the same (exception for multi camera),
  24463. * this is easier to reference from here than from all the materials and post process.
  24464. *
  24465. * No setter as we it is a shared configuration, you can set the values instead.
  24466. */
  24467. get: function () {
  24468. return this._imageProcessingConfiguration;
  24469. },
  24470. enumerable: true,
  24471. configurable: true
  24472. });
  24473. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24474. get: function () {
  24475. return this._forceWireframe;
  24476. },
  24477. /**
  24478. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24479. */
  24480. set: function (value) {
  24481. if (this._forceWireframe === value) {
  24482. return;
  24483. }
  24484. this._forceWireframe = value;
  24485. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24486. },
  24487. enumerable: true,
  24488. configurable: true
  24489. });
  24490. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24491. get: function () {
  24492. return this._forcePointsCloud;
  24493. },
  24494. /**
  24495. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24496. */
  24497. set: function (value) {
  24498. if (this._forcePointsCloud === value) {
  24499. return;
  24500. }
  24501. this._forcePointsCloud = value;
  24502. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24503. },
  24504. enumerable: true,
  24505. configurable: true
  24506. });
  24507. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24508. /**
  24509. * Gets or sets the animation properties override
  24510. */
  24511. get: function () {
  24512. return this._animationPropertiesOverride;
  24513. },
  24514. set: function (value) {
  24515. this._animationPropertiesOverride = value;
  24516. },
  24517. enumerable: true,
  24518. configurable: true
  24519. });
  24520. Object.defineProperty(Scene.prototype, "onDispose", {
  24521. /** Sets a function to be executed when this scene is disposed. */
  24522. set: function (callback) {
  24523. if (this._onDisposeObserver) {
  24524. this.onDisposeObservable.remove(this._onDisposeObserver);
  24525. }
  24526. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24527. },
  24528. enumerable: true,
  24529. configurable: true
  24530. });
  24531. Object.defineProperty(Scene.prototype, "beforeRender", {
  24532. /** Sets a function to be executed before rendering this scene */
  24533. set: function (callback) {
  24534. if (this._onBeforeRenderObserver) {
  24535. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24536. }
  24537. if (callback) {
  24538. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24539. }
  24540. },
  24541. enumerable: true,
  24542. configurable: true
  24543. });
  24544. Object.defineProperty(Scene.prototype, "afterRender", {
  24545. /** Sets a function to be executed after rendering this scene */
  24546. set: function (callback) {
  24547. if (this._onAfterRenderObserver) {
  24548. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24549. }
  24550. if (callback) {
  24551. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24552. }
  24553. },
  24554. enumerable: true,
  24555. configurable: true
  24556. });
  24557. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24558. /** Sets a function to be executed before rendering a camera*/
  24559. set: function (callback) {
  24560. if (this._onBeforeCameraRenderObserver) {
  24561. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24562. }
  24563. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24564. },
  24565. enumerable: true,
  24566. configurable: true
  24567. });
  24568. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24569. /** Sets a function to be executed after rendering a camera*/
  24570. set: function (callback) {
  24571. if (this._onAfterCameraRenderObserver) {
  24572. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24573. }
  24574. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24575. },
  24576. enumerable: true,
  24577. configurable: true
  24578. });
  24579. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24580. /**
  24581. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24582. */
  24583. get: function () {
  24584. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24585. },
  24586. enumerable: true,
  24587. configurable: true
  24588. });
  24589. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24590. get: function () {
  24591. return this._useRightHandedSystem;
  24592. },
  24593. /**
  24594. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24595. */
  24596. set: function (value) {
  24597. if (this._useRightHandedSystem === value) {
  24598. return;
  24599. }
  24600. this._useRightHandedSystem = value;
  24601. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24602. },
  24603. enumerable: true,
  24604. configurable: true
  24605. });
  24606. /**
  24607. * Sets the step Id used by deterministic lock step
  24608. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24609. * @param newStepId defines the step Id
  24610. */
  24611. Scene.prototype.setStepId = function (newStepId) {
  24612. this._currentStepId = newStepId;
  24613. };
  24614. ;
  24615. /**
  24616. * Gets the step Id used by deterministic lock step
  24617. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24618. * @returns the step Id
  24619. */
  24620. Scene.prototype.getStepId = function () {
  24621. return this._currentStepId;
  24622. };
  24623. ;
  24624. /**
  24625. * Gets the internal step used by deterministic lock step
  24626. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24627. * @returns the internal step
  24628. */
  24629. Scene.prototype.getInternalStep = function () {
  24630. return this._currentInternalStep;
  24631. };
  24632. ;
  24633. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24634. get: function () {
  24635. return this._fogEnabled;
  24636. },
  24637. /**
  24638. * Gets or sets a boolean indicating if fog is enabled on this scene
  24639. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24640. */
  24641. set: function (value) {
  24642. if (this._fogEnabled === value) {
  24643. return;
  24644. }
  24645. this._fogEnabled = value;
  24646. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24647. },
  24648. enumerable: true,
  24649. configurable: true
  24650. });
  24651. Object.defineProperty(Scene.prototype, "fogMode", {
  24652. get: function () {
  24653. return this._fogMode;
  24654. },
  24655. /**
  24656. * Gets or sets the fog mode to use
  24657. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24658. */
  24659. set: function (value) {
  24660. if (this._fogMode === value) {
  24661. return;
  24662. }
  24663. this._fogMode = value;
  24664. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24665. },
  24666. enumerable: true,
  24667. configurable: true
  24668. });
  24669. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24670. get: function () {
  24671. return this._shadowsEnabled;
  24672. },
  24673. /**
  24674. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24675. */
  24676. set: function (value) {
  24677. if (this._shadowsEnabled === value) {
  24678. return;
  24679. }
  24680. this._shadowsEnabled = value;
  24681. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24682. },
  24683. enumerable: true,
  24684. configurable: true
  24685. });
  24686. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24687. get: function () {
  24688. return this._lightsEnabled;
  24689. },
  24690. /**
  24691. * Gets or sets a boolean indicating if lights are enabled on this scene
  24692. */
  24693. set: function (value) {
  24694. if (this._lightsEnabled === value) {
  24695. return;
  24696. }
  24697. this._lightsEnabled = value;
  24698. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24699. },
  24700. enumerable: true,
  24701. configurable: true
  24702. });
  24703. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24704. /** The default material used on meshes when no material is affected */
  24705. get: function () {
  24706. if (!this._defaultMaterial) {
  24707. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24708. }
  24709. return this._defaultMaterial;
  24710. },
  24711. /** The default material used on meshes when no material is affected */
  24712. set: function (value) {
  24713. this._defaultMaterial = value;
  24714. },
  24715. enumerable: true,
  24716. configurable: true
  24717. });
  24718. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24719. get: function () {
  24720. return this._texturesEnabled;
  24721. },
  24722. /**
  24723. * Gets or sets a boolean indicating if textures are enabled on this scene
  24724. */
  24725. set: function (value) {
  24726. if (this._texturesEnabled === value) {
  24727. return;
  24728. }
  24729. this._texturesEnabled = value;
  24730. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24731. },
  24732. enumerable: true,
  24733. configurable: true
  24734. });
  24735. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24736. get: function () {
  24737. return this._skeletonsEnabled;
  24738. },
  24739. /**
  24740. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24741. */
  24742. set: function (value) {
  24743. if (this._skeletonsEnabled === value) {
  24744. return;
  24745. }
  24746. this._skeletonsEnabled = value;
  24747. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24748. },
  24749. enumerable: true,
  24750. configurable: true
  24751. });
  24752. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24753. /**
  24754. * Gets the main soundtrack associated with the scene
  24755. */
  24756. get: function () {
  24757. if (!this._mainSoundTrack) {
  24758. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24759. }
  24760. return this._mainSoundTrack;
  24761. },
  24762. enumerable: true,
  24763. configurable: true
  24764. });
  24765. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24766. /** @hidden */
  24767. get: function () {
  24768. return this._alternateRendering;
  24769. },
  24770. enumerable: true,
  24771. configurable: true
  24772. });
  24773. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24774. /**
  24775. * Gets the list of frustum planes (built from the active camera)
  24776. */
  24777. get: function () {
  24778. return this._frustumPlanes;
  24779. },
  24780. enumerable: true,
  24781. configurable: true
  24782. });
  24783. /**
  24784. * Registers the transient components if needed.
  24785. */
  24786. Scene.prototype._registerTransientComponents = function () {
  24787. // Register components that have been associated lately to the scene.
  24788. if (this._transientComponents.length > 0) {
  24789. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24790. var component = _a[_i];
  24791. component.register();
  24792. }
  24793. this._transientComponents = [];
  24794. }
  24795. };
  24796. /**
  24797. * @hidden
  24798. * Add a component to the scene.
  24799. * Note that the ccomponent could be registered on th next frame if this is called after
  24800. * the register component stage.
  24801. * @param component Defines the component to add to the scene
  24802. */
  24803. Scene.prototype._addComponent = function (component) {
  24804. this._components.push(component);
  24805. this._transientComponents.push(component);
  24806. var serializableComponent = component;
  24807. if (serializableComponent.addFromContainer) {
  24808. this._serializableComponents.push(serializableComponent);
  24809. }
  24810. };
  24811. /**
  24812. * @hidden
  24813. * Gets a component from the scene.
  24814. * @param name defines the name of the component to retrieve
  24815. * @returns the component or null if not present
  24816. */
  24817. Scene.prototype._getComponent = function (name) {
  24818. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24819. var component = _a[_i];
  24820. if (component.name === name) {
  24821. return component;
  24822. }
  24823. }
  24824. return null;
  24825. };
  24826. Object.defineProperty(Scene.prototype, "debugLayer", {
  24827. /**
  24828. * Gets the debug layer (aka Inspector) associated with the scene
  24829. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24830. */
  24831. get: function () {
  24832. if (!this._debugLayer) {
  24833. this._debugLayer = new BABYLON.DebugLayer(this);
  24834. }
  24835. return this._debugLayer;
  24836. },
  24837. enumerable: true,
  24838. configurable: true
  24839. });
  24840. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24841. /**
  24842. * Gets a boolean indicating if collisions are processed on a web worker
  24843. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24844. */
  24845. get: function () {
  24846. return this._workerCollisions;
  24847. },
  24848. set: function (enabled) {
  24849. if (!BABYLON.CollisionCoordinatorLegacy) {
  24850. return;
  24851. }
  24852. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24853. this._workerCollisions = enabled;
  24854. if (this.collisionCoordinator) {
  24855. this.collisionCoordinator.destroy();
  24856. }
  24857. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24858. this.collisionCoordinator.init(this);
  24859. },
  24860. enumerable: true,
  24861. configurable: true
  24862. });
  24863. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24864. /**
  24865. * Gets the octree used to boost mesh selection (picking)
  24866. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24867. */
  24868. get: function () {
  24869. return this._selectionOctree;
  24870. },
  24871. enumerable: true,
  24872. configurable: true
  24873. });
  24874. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24875. /**
  24876. * Gets the mesh that is currently under the pointer
  24877. */
  24878. get: function () {
  24879. return this._pointerOverMesh;
  24880. },
  24881. enumerable: true,
  24882. configurable: true
  24883. });
  24884. Object.defineProperty(Scene.prototype, "pointerX", {
  24885. /**
  24886. * Gets the current on-screen X position of the pointer
  24887. */
  24888. get: function () {
  24889. return this._pointerX;
  24890. },
  24891. enumerable: true,
  24892. configurable: true
  24893. });
  24894. Object.defineProperty(Scene.prototype, "pointerY", {
  24895. /**
  24896. * Gets the current on-screen Y position of the pointer
  24897. */
  24898. get: function () {
  24899. return this._pointerY;
  24900. },
  24901. enumerable: true,
  24902. configurable: true
  24903. });
  24904. /**
  24905. * Gets the cached material (ie. the latest rendered one)
  24906. * @returns the cached material
  24907. */
  24908. Scene.prototype.getCachedMaterial = function () {
  24909. return this._cachedMaterial;
  24910. };
  24911. /**
  24912. * Gets the cached effect (ie. the latest rendered one)
  24913. * @returns the cached effect
  24914. */
  24915. Scene.prototype.getCachedEffect = function () {
  24916. return this._cachedEffect;
  24917. };
  24918. /**
  24919. * Gets the cached visibility state (ie. the latest rendered one)
  24920. * @returns the cached visibility state
  24921. */
  24922. Scene.prototype.getCachedVisibility = function () {
  24923. return this._cachedVisibility;
  24924. };
  24925. /**
  24926. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24927. * @param material defines the current material
  24928. * @param effect defines the current effect
  24929. * @param visibility defines the current visibility state
  24930. * @returns true if one parameter is not cached
  24931. */
  24932. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24933. if (visibility === void 0) { visibility = 1; }
  24934. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24935. };
  24936. /**
  24937. * Gets the engine associated with the scene
  24938. * @returns an Engine
  24939. */
  24940. Scene.prototype.getEngine = function () {
  24941. return this._engine;
  24942. };
  24943. /**
  24944. * Gets the total number of vertices rendered per frame
  24945. * @returns the total number of vertices rendered per frame
  24946. */
  24947. Scene.prototype.getTotalVertices = function () {
  24948. return this._totalVertices.current;
  24949. };
  24950. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24951. /**
  24952. * Gets the performance counter for total vertices
  24953. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24954. */
  24955. get: function () {
  24956. return this._totalVertices;
  24957. },
  24958. enumerable: true,
  24959. configurable: true
  24960. });
  24961. /**
  24962. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24963. * @returns the total number of active indices rendered per frame
  24964. */
  24965. Scene.prototype.getActiveIndices = function () {
  24966. return this._activeIndices.current;
  24967. };
  24968. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24969. /**
  24970. * Gets the performance counter for active indices
  24971. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24972. */
  24973. get: function () {
  24974. return this._activeIndices;
  24975. },
  24976. enumerable: true,
  24977. configurable: true
  24978. });
  24979. /**
  24980. * Gets the total number of active particles rendered per frame
  24981. * @returns the total number of active particles rendered per frame
  24982. */
  24983. Scene.prototype.getActiveParticles = function () {
  24984. return this._activeParticles.current;
  24985. };
  24986. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24987. /**
  24988. * Gets the performance counter for active particles
  24989. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24990. */
  24991. get: function () {
  24992. return this._activeParticles;
  24993. },
  24994. enumerable: true,
  24995. configurable: true
  24996. });
  24997. /**
  24998. * Gets the total number of active bones rendered per frame
  24999. * @returns the total number of active bones rendered per frame
  25000. */
  25001. Scene.prototype.getActiveBones = function () {
  25002. return this._activeBones.current;
  25003. };
  25004. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25005. /**
  25006. * Gets the performance counter for active bones
  25007. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25008. */
  25009. get: function () {
  25010. return this._activeBones;
  25011. },
  25012. enumerable: true,
  25013. configurable: true
  25014. });
  25015. /** @hidden */
  25016. Scene.prototype.getInterFramePerfCounter = function () {
  25017. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25018. return 0;
  25019. };
  25020. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25021. /** @hidden */
  25022. get: function () {
  25023. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25024. return null;
  25025. },
  25026. enumerable: true,
  25027. configurable: true
  25028. });
  25029. /** @hidden */
  25030. Scene.prototype.getLastFrameDuration = function () {
  25031. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25032. return 0;
  25033. };
  25034. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25035. /** @hidden */
  25036. get: function () {
  25037. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25038. return null;
  25039. },
  25040. enumerable: true,
  25041. configurable: true
  25042. });
  25043. /** @hidden */
  25044. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25045. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25046. return 0;
  25047. };
  25048. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25049. /** @hidden */
  25050. get: function () {
  25051. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25052. return null;
  25053. },
  25054. enumerable: true,
  25055. configurable: true
  25056. });
  25057. /**
  25058. * Gets the array of active meshes
  25059. * @returns an array of AbstractMesh
  25060. */
  25061. Scene.prototype.getActiveMeshes = function () {
  25062. return this._activeMeshes;
  25063. };
  25064. /** @hidden */
  25065. Scene.prototype.getRenderTargetsDuration = function () {
  25066. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25067. return 0;
  25068. };
  25069. /** @hidden */
  25070. Scene.prototype.getRenderDuration = function () {
  25071. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25072. return 0;
  25073. };
  25074. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25075. /** @hidden */
  25076. get: function () {
  25077. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25078. return null;
  25079. },
  25080. enumerable: true,
  25081. configurable: true
  25082. });
  25083. /** @hidden */
  25084. Scene.prototype.getParticlesDuration = function () {
  25085. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25086. return 0;
  25087. };
  25088. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25089. /** @hidden */
  25090. get: function () {
  25091. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25092. return null;
  25093. },
  25094. enumerable: true,
  25095. configurable: true
  25096. });
  25097. /** @hidden */
  25098. Scene.prototype.getSpritesDuration = function () {
  25099. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25100. return 0;
  25101. };
  25102. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25103. /** @hidden */
  25104. get: function () {
  25105. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25106. return null;
  25107. },
  25108. enumerable: true,
  25109. configurable: true
  25110. });
  25111. /**
  25112. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25113. * @returns a number
  25114. */
  25115. Scene.prototype.getAnimationRatio = function () {
  25116. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25117. };
  25118. /**
  25119. * Gets an unique Id for the current frame
  25120. * @returns a number
  25121. */
  25122. Scene.prototype.getRenderId = function () {
  25123. return this._renderId;
  25124. };
  25125. /** Call this function if you want to manually increment the render Id*/
  25126. Scene.prototype.incrementRenderId = function () {
  25127. this._renderId++;
  25128. };
  25129. Scene.prototype._updatePointerPosition = function (evt) {
  25130. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25131. if (!canvasRect) {
  25132. return;
  25133. }
  25134. this._pointerX = evt.clientX - canvasRect.left;
  25135. this._pointerY = evt.clientY - canvasRect.top;
  25136. this._unTranslatedPointerX = this._pointerX;
  25137. this._unTranslatedPointerY = this._pointerY;
  25138. };
  25139. Scene.prototype._createUbo = function () {
  25140. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25141. this._sceneUbo.addUniform("viewProjection", 16);
  25142. this._sceneUbo.addUniform("view", 16);
  25143. };
  25144. Scene.prototype._createAlternateUbo = function () {
  25145. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25146. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25147. this._alternateSceneUbo.addUniform("view", 16);
  25148. };
  25149. // Pointers handling
  25150. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25151. if (pointerInfo.pickInfo) {
  25152. if (!pointerInfo.pickInfo.ray) {
  25153. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25154. }
  25155. }
  25156. };
  25157. /**
  25158. * Use this method to simulate a pointer move on a mesh
  25159. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25160. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25161. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25162. * @returns the current scene
  25163. */
  25164. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25165. var evt = new PointerEvent("pointermove", pointerEventInit);
  25166. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25167. return this;
  25168. }
  25169. return this._processPointerMove(pickResult, evt);
  25170. };
  25171. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25172. var canvas = this._engine.getRenderingCanvas();
  25173. if (!canvas) {
  25174. return this;
  25175. }
  25176. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25177. if (isMeshPicked) {
  25178. this.setPointerOverMesh(pickResult.pickedMesh);
  25179. }
  25180. else {
  25181. this.setPointerOverMesh(null);
  25182. }
  25183. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25184. var step = _a[_i];
  25185. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25186. }
  25187. if (pickResult) {
  25188. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25189. if (this.onPointerMove) {
  25190. this.onPointerMove(evt, pickResult, type);
  25191. }
  25192. if (this.onPointerObservable.hasObservers()) {
  25193. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25194. this._setRayOnPointerInfo(pi);
  25195. this.onPointerObservable.notifyObservers(pi, type);
  25196. }
  25197. }
  25198. return this;
  25199. };
  25200. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25201. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25202. if (pickResult) {
  25203. pi.ray = pickResult.ray;
  25204. }
  25205. this.onPrePointerObservable.notifyObservers(pi, type);
  25206. if (pi.skipOnPointerObservable) {
  25207. return true;
  25208. }
  25209. else {
  25210. return false;
  25211. }
  25212. };
  25213. /**
  25214. * Use this method to simulate a pointer down on a mesh
  25215. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25216. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25217. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25218. * @returns the current scene
  25219. */
  25220. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25221. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25222. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25223. return this;
  25224. }
  25225. return this._processPointerDown(pickResult, evt);
  25226. };
  25227. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25228. var _this = this;
  25229. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25230. this._pickedDownMesh = pickResult.pickedMesh;
  25231. var actionManager = pickResult.pickedMesh.actionManager;
  25232. if (actionManager) {
  25233. if (actionManager.hasPickTriggers) {
  25234. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25235. switch (evt.button) {
  25236. case 0:
  25237. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25238. break;
  25239. case 1:
  25240. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25241. break;
  25242. case 2:
  25243. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25244. break;
  25245. }
  25246. }
  25247. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25248. window.setTimeout(function () {
  25249. 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);
  25250. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25251. if (_this._totalPointersPressed !== 0 &&
  25252. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25253. !_this._isPointerSwiping()) {
  25254. _this._startingPointerTime = 0;
  25255. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25256. }
  25257. }
  25258. }, Scene.LongPressDelay);
  25259. }
  25260. }
  25261. }
  25262. else {
  25263. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25264. var step = _a[_i];
  25265. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25266. }
  25267. }
  25268. if (pickResult) {
  25269. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25270. if (this.onPointerDown) {
  25271. this.onPointerDown(evt, pickResult, type);
  25272. }
  25273. if (this.onPointerObservable.hasObservers()) {
  25274. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25275. this._setRayOnPointerInfo(pi);
  25276. this.onPointerObservable.notifyObservers(pi, type);
  25277. }
  25278. }
  25279. return this;
  25280. };
  25281. /**
  25282. * Use this method to simulate a pointer up on a mesh
  25283. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25284. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25285. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25286. * @returns the current scene
  25287. */
  25288. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25289. var evt = new PointerEvent("pointerup", pointerEventInit);
  25290. var clickInfo = new ClickInfo();
  25291. clickInfo.singleClick = true;
  25292. clickInfo.ignore = true;
  25293. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25294. return this;
  25295. }
  25296. return this._processPointerUp(pickResult, evt, clickInfo);
  25297. };
  25298. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25299. if (pickResult && pickResult && pickResult.pickedMesh) {
  25300. this._pickedUpMesh = pickResult.pickedMesh;
  25301. if (this._pickedDownMesh === this._pickedUpMesh) {
  25302. if (this.onPointerPick) {
  25303. this.onPointerPick(evt, pickResult);
  25304. }
  25305. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25306. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25307. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25308. this._setRayOnPointerInfo(pi);
  25309. this.onPointerObservable.notifyObservers(pi, type_1);
  25310. }
  25311. }
  25312. if (pickResult.pickedMesh.actionManager) {
  25313. if (clickInfo.ignore) {
  25314. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25315. }
  25316. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25317. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25318. }
  25319. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25320. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25321. }
  25322. }
  25323. }
  25324. else {
  25325. if (!clickInfo.ignore) {
  25326. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25327. var step = _a[_i];
  25328. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25329. }
  25330. }
  25331. }
  25332. if (this._pickedDownMesh &&
  25333. this._pickedDownMesh.actionManager &&
  25334. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25335. this._pickedDownMesh !== this._pickedUpMesh) {
  25336. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25337. }
  25338. var type = BABYLON.PointerEventTypes.POINTERUP;
  25339. if (this.onPointerObservable.hasObservers()) {
  25340. if (!clickInfo.ignore) {
  25341. if (!clickInfo.hasSwiped) {
  25342. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25343. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25344. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25345. this._setRayOnPointerInfo(pi);
  25346. this.onPointerObservable.notifyObservers(pi, type_2);
  25347. }
  25348. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25349. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25350. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25351. this._setRayOnPointerInfo(pi);
  25352. this.onPointerObservable.notifyObservers(pi, type_3);
  25353. }
  25354. }
  25355. }
  25356. else {
  25357. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25358. this._setRayOnPointerInfo(pi);
  25359. this.onPointerObservable.notifyObservers(pi, type);
  25360. }
  25361. }
  25362. if (this.onPointerUp) {
  25363. this.onPointerUp(evt, pickResult, type);
  25364. }
  25365. return this;
  25366. };
  25367. /**
  25368. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25369. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25370. * @returns true if the pointer was captured
  25371. */
  25372. Scene.prototype.isPointerCaptured = function (pointerId) {
  25373. if (pointerId === void 0) { pointerId = 0; }
  25374. return this._pointerCaptures[pointerId];
  25375. };
  25376. /** @hidden */
  25377. Scene.prototype._isPointerSwiping = function () {
  25378. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25379. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25380. };
  25381. /**
  25382. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25383. * @param attachUp defines if you want to attach events to pointerup
  25384. * @param attachDown defines if you want to attach events to pointerdown
  25385. * @param attachMove defines if you want to attach events to pointermove
  25386. */
  25387. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25388. var _this = this;
  25389. if (attachUp === void 0) { attachUp = true; }
  25390. if (attachDown === void 0) { attachDown = true; }
  25391. if (attachMove === void 0) { attachMove = true; }
  25392. this._initActionManager = function (act, clickInfo) {
  25393. if (!_this._meshPickProceed) {
  25394. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25395. _this._currentPickResult = pickResult;
  25396. if (pickResult) {
  25397. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25398. }
  25399. _this._meshPickProceed = true;
  25400. }
  25401. return act;
  25402. };
  25403. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25404. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25405. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25406. btn !== _this._previousButtonPressed) {
  25407. _this._doubleClickOccured = false;
  25408. clickInfo.singleClick = true;
  25409. clickInfo.ignore = false;
  25410. cb(clickInfo, _this._currentPickResult);
  25411. }
  25412. };
  25413. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25414. var clickInfo = new ClickInfo();
  25415. _this._currentPickResult = null;
  25416. var act = null;
  25417. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25418. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25419. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25420. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25421. act = _this._initActionManager(act, clickInfo);
  25422. if (act)
  25423. checkPicking = act.hasPickTriggers;
  25424. }
  25425. if (checkPicking) {
  25426. var btn = evt.button;
  25427. clickInfo.hasSwiped = _this._isPointerSwiping();
  25428. if (!clickInfo.hasSwiped) {
  25429. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25430. if (!checkSingleClickImmediately) {
  25431. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25432. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25433. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25434. act = _this._initActionManager(act, clickInfo);
  25435. if (act)
  25436. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25437. }
  25438. }
  25439. if (checkSingleClickImmediately) {
  25440. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25441. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25442. btn !== _this._previousButtonPressed) {
  25443. clickInfo.singleClick = true;
  25444. cb(clickInfo, _this._currentPickResult);
  25445. }
  25446. }
  25447. // at least one double click is required to be check and exclusive double click is enabled
  25448. else {
  25449. // wait that no double click has been raised during the double click delay
  25450. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25451. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25452. }
  25453. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25454. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25455. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25456. act = _this._initActionManager(act, clickInfo);
  25457. if (act)
  25458. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25459. }
  25460. if (checkDoubleClick) {
  25461. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25462. if (btn === _this._previousButtonPressed &&
  25463. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25464. !_this._doubleClickOccured) {
  25465. // pointer has not moved for 2 clicks, it's a double click
  25466. if (!clickInfo.hasSwiped &&
  25467. !_this._isPointerSwiping()) {
  25468. _this._previousStartingPointerTime = 0;
  25469. _this._doubleClickOccured = true;
  25470. clickInfo.doubleClick = true;
  25471. clickInfo.ignore = false;
  25472. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25473. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25474. }
  25475. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25476. cb(clickInfo, _this._currentPickResult);
  25477. }
  25478. // if the two successive clicks are too far, it's just two simple clicks
  25479. else {
  25480. _this._doubleClickOccured = false;
  25481. _this._previousStartingPointerTime = _this._startingPointerTime;
  25482. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25483. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25484. _this._previousButtonPressed = btn;
  25485. if (Scene.ExclusiveDoubleClickMode) {
  25486. if (_this._previousDelayedSimpleClickTimeout) {
  25487. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25488. }
  25489. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25490. cb(clickInfo, _this._previousPickResult);
  25491. }
  25492. else {
  25493. cb(clickInfo, _this._currentPickResult);
  25494. }
  25495. }
  25496. }
  25497. // just the first click of the double has been raised
  25498. else {
  25499. _this._doubleClickOccured = false;
  25500. _this._previousStartingPointerTime = _this._startingPointerTime;
  25501. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25502. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25503. _this._previousButtonPressed = btn;
  25504. }
  25505. }
  25506. }
  25507. }
  25508. clickInfo.ignore = true;
  25509. cb(clickInfo, _this._currentPickResult);
  25510. };
  25511. this._onPointerMove = function (evt) {
  25512. _this._updatePointerPosition(evt);
  25513. // PreObservable support
  25514. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25515. return;
  25516. }
  25517. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25518. return;
  25519. }
  25520. if (!_this.pointerMovePredicate) {
  25521. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25522. }
  25523. // Meshes
  25524. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25525. _this._processPointerMove(pickResult, evt);
  25526. };
  25527. this._onPointerDown = function (evt) {
  25528. _this._totalPointersPressed++;
  25529. _this._pickedDownMesh = null;
  25530. _this._meshPickProceed = false;
  25531. _this._updatePointerPosition(evt);
  25532. if (_this.preventDefaultOnPointerDown && canvas) {
  25533. evt.preventDefault();
  25534. canvas.focus();
  25535. }
  25536. // PreObservable support
  25537. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25538. return;
  25539. }
  25540. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25541. return;
  25542. }
  25543. _this._pointerCaptures[evt.pointerId] = true;
  25544. _this._startingPointerPosition.x = _this._pointerX;
  25545. _this._startingPointerPosition.y = _this._pointerY;
  25546. _this._startingPointerTime = Date.now();
  25547. if (!_this.pointerDownPredicate) {
  25548. _this.pointerDownPredicate = function (mesh) {
  25549. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25550. };
  25551. }
  25552. // Meshes
  25553. _this._pickedDownMesh = null;
  25554. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25555. _this._processPointerDown(pickResult, evt);
  25556. };
  25557. this._onPointerUp = function (evt) {
  25558. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25559. return; // So we need to test it the pointer down was pressed before.
  25560. }
  25561. _this._totalPointersPressed--;
  25562. _this._pickedUpMesh = null;
  25563. _this._meshPickProceed = false;
  25564. _this._updatePointerPosition(evt);
  25565. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25566. // PreObservable support
  25567. if (_this.onPrePointerObservable.hasObservers()) {
  25568. if (!clickInfo.ignore) {
  25569. if (!clickInfo.hasSwiped) {
  25570. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25571. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25572. return;
  25573. }
  25574. }
  25575. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25576. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25577. return;
  25578. }
  25579. }
  25580. }
  25581. }
  25582. else {
  25583. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25584. return;
  25585. }
  25586. }
  25587. }
  25588. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25589. return;
  25590. }
  25591. _this._pointerCaptures[evt.pointerId] = false;
  25592. if (!_this.pointerUpPredicate) {
  25593. _this.pointerUpPredicate = function (mesh) {
  25594. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25595. };
  25596. }
  25597. // Meshes
  25598. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25599. _this._initActionManager(null, clickInfo);
  25600. }
  25601. if (!pickResult) {
  25602. pickResult = _this._currentPickResult;
  25603. }
  25604. _this._processPointerUp(pickResult, evt, clickInfo);
  25605. _this._previousPickResult = _this._currentPickResult;
  25606. });
  25607. };
  25608. this._onKeyDown = function (evt) {
  25609. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25610. if (_this.onPreKeyboardObservable.hasObservers()) {
  25611. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25612. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25613. if (pi.skipOnPointerObservable) {
  25614. return;
  25615. }
  25616. }
  25617. if (_this.onKeyboardObservable.hasObservers()) {
  25618. var pi = new BABYLON.KeyboardInfo(type, evt);
  25619. _this.onKeyboardObservable.notifyObservers(pi, type);
  25620. }
  25621. if (_this.actionManager) {
  25622. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25623. }
  25624. };
  25625. this._onKeyUp = function (evt) {
  25626. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25627. if (_this.onPreKeyboardObservable.hasObservers()) {
  25628. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25629. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25630. if (pi.skipOnPointerObservable) {
  25631. return;
  25632. }
  25633. }
  25634. if (_this.onKeyboardObservable.hasObservers()) {
  25635. var pi = new BABYLON.KeyboardInfo(type, evt);
  25636. _this.onKeyboardObservable.notifyObservers(pi, type);
  25637. }
  25638. if (_this.actionManager) {
  25639. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25640. }
  25641. };
  25642. var engine = this.getEngine();
  25643. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25644. if (!canvas) {
  25645. return;
  25646. }
  25647. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25648. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25649. });
  25650. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25651. if (!canvas) {
  25652. return;
  25653. }
  25654. canvas.removeEventListener("keydown", _this._onKeyDown);
  25655. canvas.removeEventListener("keyup", _this._onKeyUp);
  25656. });
  25657. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25658. var canvas = this._engine.getRenderingCanvas();
  25659. if (!canvas) {
  25660. return;
  25661. }
  25662. if (attachMove) {
  25663. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25664. // Wheel
  25665. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25666. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25667. }
  25668. if (attachDown) {
  25669. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25670. }
  25671. if (attachUp) {
  25672. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25673. }
  25674. canvas.tabIndex = 1;
  25675. };
  25676. /** Detaches all event handlers*/
  25677. Scene.prototype.detachControl = function () {
  25678. var engine = this.getEngine();
  25679. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25680. var canvas = engine.getRenderingCanvas();
  25681. if (!canvas) {
  25682. return;
  25683. }
  25684. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25685. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25686. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25687. if (this._onCanvasBlurObserver) {
  25688. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25689. }
  25690. if (this._onCanvasFocusObserver) {
  25691. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25692. }
  25693. // Wheel
  25694. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25695. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25696. // Keyboard
  25697. canvas.removeEventListener("keydown", this._onKeyDown);
  25698. canvas.removeEventListener("keyup", this._onKeyUp);
  25699. // Observables
  25700. this.onKeyboardObservable.clear();
  25701. this.onPreKeyboardObservable.clear();
  25702. this.onPointerObservable.clear();
  25703. this.onPrePointerObservable.clear();
  25704. };
  25705. /**
  25706. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25707. * Delay loaded resources are not taking in account
  25708. * @return true if all required resources are ready
  25709. */
  25710. Scene.prototype.isReady = function () {
  25711. if (this._isDisposed) {
  25712. return false;
  25713. }
  25714. if (this._pendingData.length > 0) {
  25715. return false;
  25716. }
  25717. var index;
  25718. var engine = this.getEngine();
  25719. // Geometries
  25720. for (index = 0; index < this.geometries.length; index++) {
  25721. var geometry = this.geometries[index];
  25722. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25723. return false;
  25724. }
  25725. }
  25726. // Meshes
  25727. for (index = 0; index < this.meshes.length; index++) {
  25728. var mesh = this.meshes[index];
  25729. if (!mesh.isEnabled()) {
  25730. continue;
  25731. }
  25732. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25733. continue;
  25734. }
  25735. if (!mesh.isReady(true)) {
  25736. return false;
  25737. }
  25738. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25739. // Is Ready For Mesh
  25740. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25741. var step = _a[_i];
  25742. if (!step.action(mesh, hardwareInstancedRendering)) {
  25743. return false;
  25744. }
  25745. }
  25746. }
  25747. // Post-processes
  25748. if (this.activeCameras && this.activeCameras.length > 0) {
  25749. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25750. var camera = _c[_b];
  25751. if (!camera.isReady(true)) {
  25752. return false;
  25753. }
  25754. }
  25755. }
  25756. else if (this.activeCamera) {
  25757. if (!this.activeCamera.isReady(true)) {
  25758. return false;
  25759. }
  25760. }
  25761. // Particles
  25762. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25763. var particleSystem = _e[_d];
  25764. if (!particleSystem.isReady()) {
  25765. return false;
  25766. }
  25767. }
  25768. return true;
  25769. };
  25770. /** Resets all cached information relative to material (including effect and visibility) */
  25771. Scene.prototype.resetCachedMaterial = function () {
  25772. this._cachedMaterial = null;
  25773. this._cachedEffect = null;
  25774. this._cachedVisibility = null;
  25775. };
  25776. /**
  25777. * Registers a function to be called before every frame render
  25778. * @param func defines the function to register
  25779. */
  25780. Scene.prototype.registerBeforeRender = function (func) {
  25781. this.onBeforeRenderObservable.add(func);
  25782. };
  25783. /**
  25784. * Unregisters a function called before every frame render
  25785. * @param func defines the function to unregister
  25786. */
  25787. Scene.prototype.unregisterBeforeRender = function (func) {
  25788. this.onBeforeRenderObservable.removeCallback(func);
  25789. };
  25790. /**
  25791. * Registers a function to be called after every frame render
  25792. * @param func defines the function to register
  25793. */
  25794. Scene.prototype.registerAfterRender = function (func) {
  25795. this.onAfterRenderObservable.add(func);
  25796. };
  25797. /**
  25798. * Unregisters a function called after every frame render
  25799. * @param func defines the function to unregister
  25800. */
  25801. Scene.prototype.unregisterAfterRender = function (func) {
  25802. this.onAfterRenderObservable.removeCallback(func);
  25803. };
  25804. Scene.prototype._executeOnceBeforeRender = function (func) {
  25805. var _this = this;
  25806. var execFunc = function () {
  25807. func();
  25808. setTimeout(function () {
  25809. _this.unregisterBeforeRender(execFunc);
  25810. });
  25811. };
  25812. this.registerBeforeRender(execFunc);
  25813. };
  25814. /**
  25815. * The provided function will run before render once and will be disposed afterwards.
  25816. * A timeout delay can be provided so that the function will be executed in N ms.
  25817. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25818. * @param func The function to be executed.
  25819. * @param timeout optional delay in ms
  25820. */
  25821. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25822. var _this = this;
  25823. if (timeout !== undefined) {
  25824. setTimeout(function () {
  25825. _this._executeOnceBeforeRender(func);
  25826. }, timeout);
  25827. }
  25828. else {
  25829. this._executeOnceBeforeRender(func);
  25830. }
  25831. };
  25832. /** @hidden */
  25833. Scene.prototype._addPendingData = function (data) {
  25834. this._pendingData.push(data);
  25835. };
  25836. /** @hidden */
  25837. Scene.prototype._removePendingData = function (data) {
  25838. var wasLoading = this.isLoading;
  25839. var index = this._pendingData.indexOf(data);
  25840. if (index !== -1) {
  25841. this._pendingData.splice(index, 1);
  25842. }
  25843. if (wasLoading && !this.isLoading) {
  25844. this.onDataLoadedObservable.notifyObservers(this);
  25845. }
  25846. };
  25847. /**
  25848. * Returns the number of items waiting to be loaded
  25849. * @returns the number of items waiting to be loaded
  25850. */
  25851. Scene.prototype.getWaitingItemsCount = function () {
  25852. return this._pendingData.length;
  25853. };
  25854. Object.defineProperty(Scene.prototype, "isLoading", {
  25855. /**
  25856. * Returns a boolean indicating if the scene is still loading data
  25857. */
  25858. get: function () {
  25859. return this._pendingData.length > 0;
  25860. },
  25861. enumerable: true,
  25862. configurable: true
  25863. });
  25864. /**
  25865. * Registers a function to be executed when the scene is ready
  25866. * @param {Function} func - the function to be executed
  25867. */
  25868. Scene.prototype.executeWhenReady = function (func) {
  25869. var _this = this;
  25870. this.onReadyObservable.add(func);
  25871. if (this._executeWhenReadyTimeoutId !== -1) {
  25872. return;
  25873. }
  25874. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25875. _this._checkIsReady();
  25876. }, 150);
  25877. };
  25878. /**
  25879. * Returns a promise that resolves when the scene is ready
  25880. * @returns A promise that resolves when the scene is ready
  25881. */
  25882. Scene.prototype.whenReadyAsync = function () {
  25883. var _this = this;
  25884. return new Promise(function (resolve) {
  25885. _this.executeWhenReady(function () {
  25886. resolve();
  25887. });
  25888. });
  25889. };
  25890. /** @hidden */
  25891. Scene.prototype._checkIsReady = function () {
  25892. var _this = this;
  25893. this._registerTransientComponents();
  25894. if (this.isReady()) {
  25895. this.onReadyObservable.notifyObservers(this);
  25896. this.onReadyObservable.clear();
  25897. this._executeWhenReadyTimeoutId = -1;
  25898. return;
  25899. }
  25900. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25901. _this._checkIsReady();
  25902. }, 150);
  25903. };
  25904. // Animations
  25905. /**
  25906. * Will start the animation sequence of a given target
  25907. * @param target defines the target
  25908. * @param from defines from which frame should animation start
  25909. * @param to defines until which frame should animation run.
  25910. * @param weight defines the weight to apply to the animation (1.0 by default)
  25911. * @param loop defines if the animation loops
  25912. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25913. * @param onAnimationEnd defines the function to be executed when the animation ends
  25914. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25915. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25916. * @returns the animatable object created for this animation
  25917. */
  25918. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25919. if (weight === void 0) { weight = 1.0; }
  25920. if (speedRatio === void 0) { speedRatio = 1.0; }
  25921. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25922. returnedAnimatable.weight = weight;
  25923. return returnedAnimatable;
  25924. };
  25925. /**
  25926. * Will start the animation sequence of a given target
  25927. * @param target defines the target
  25928. * @param from defines from which frame should animation start
  25929. * @param to defines until which frame should animation run.
  25930. * @param loop defines if the animation loops
  25931. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25932. * @param onAnimationEnd defines the function to be executed when the animation ends
  25933. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25934. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25935. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25936. * @returns the animatable object created for this animation
  25937. */
  25938. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25939. if (speedRatio === void 0) { speedRatio = 1.0; }
  25940. if (stopCurrent === void 0) { stopCurrent = true; }
  25941. if (from > to && speedRatio > 0) {
  25942. speedRatio *= -1;
  25943. }
  25944. if (stopCurrent) {
  25945. this.stopAnimation(target, undefined, targetMask);
  25946. }
  25947. if (!animatable) {
  25948. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25949. }
  25950. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25951. // Local animations
  25952. if (target.animations && shouldRunTargetAnimations) {
  25953. animatable.appendAnimations(target, target.animations);
  25954. }
  25955. // Children animations
  25956. if (target.getAnimatables) {
  25957. var animatables = target.getAnimatables();
  25958. for (var index = 0; index < animatables.length; index++) {
  25959. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25960. }
  25961. }
  25962. animatable.reset();
  25963. return animatable;
  25964. };
  25965. /**
  25966. * Begin a new animation on a given node
  25967. * @param target defines the target where the animation will take place
  25968. * @param animations defines the list of animations to start
  25969. * @param from defines the initial value
  25970. * @param to defines the final value
  25971. * @param loop defines if you want animation to loop (off by default)
  25972. * @param speedRatio defines the speed ratio to apply to all animations
  25973. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25974. * @returns the list of created animatables
  25975. */
  25976. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25977. if (speedRatio === undefined) {
  25978. speedRatio = 1.0;
  25979. }
  25980. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25981. return animatable;
  25982. };
  25983. /**
  25984. * Begin a new animation on a given node and its hierarchy
  25985. * @param target defines the root node where the animation will take place
  25986. * @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.
  25987. * @param animations defines the list of animations to start
  25988. * @param from defines the initial value
  25989. * @param to defines the final value
  25990. * @param loop defines if you want animation to loop (off by default)
  25991. * @param speedRatio defines the speed ratio to apply to all animations
  25992. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25993. * @returns the list of animatables created for all nodes
  25994. */
  25995. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25996. var children = target.getDescendants(directDescendantsOnly);
  25997. var result = [];
  25998. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25999. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26000. var child = children_1[_i];
  26001. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26002. }
  26003. return result;
  26004. };
  26005. /**
  26006. * Gets the animatable associated with a specific target
  26007. * @param target defines the target of the animatable
  26008. * @returns the required animatable if found
  26009. */
  26010. Scene.prototype.getAnimatableByTarget = function (target) {
  26011. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26012. if (this._activeAnimatables[index].target === target) {
  26013. return this._activeAnimatables[index];
  26014. }
  26015. }
  26016. return null;
  26017. };
  26018. /**
  26019. * Gets all animatables associated with a given target
  26020. * @param target defines the target to look animatables for
  26021. * @returns an array of Animatables
  26022. */
  26023. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26024. var result = [];
  26025. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26026. if (this._activeAnimatables[index].target === target) {
  26027. result.push(this._activeAnimatables[index]);
  26028. }
  26029. }
  26030. return result;
  26031. };
  26032. Object.defineProperty(Scene.prototype, "animatables", {
  26033. /**
  26034. * Gets all animatable attached to the scene
  26035. */
  26036. get: function () {
  26037. return this._activeAnimatables;
  26038. },
  26039. enumerable: true,
  26040. configurable: true
  26041. });
  26042. /**
  26043. * Will stop the animation of the given target
  26044. * @param target - the target
  26045. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26046. * @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)
  26047. */
  26048. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26049. var animatables = this.getAllAnimatablesByTarget(target);
  26050. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26051. var animatable = animatables_1[_i];
  26052. animatable.stop(animationName, targetMask);
  26053. }
  26054. };
  26055. /**
  26056. * Stops and removes all animations that have been applied to the scene
  26057. */
  26058. Scene.prototype.stopAllAnimations = function () {
  26059. if (this._activeAnimatables) {
  26060. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26061. this._activeAnimatables[i].stop();
  26062. }
  26063. this._activeAnimatables = [];
  26064. }
  26065. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26066. var group = _a[_i];
  26067. group.stop();
  26068. }
  26069. };
  26070. Scene.prototype._animate = function () {
  26071. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26072. return;
  26073. }
  26074. // Getting time
  26075. var now = BABYLON.Tools.Now;
  26076. if (!this._animationTimeLast) {
  26077. if (this._pendingData.length > 0) {
  26078. return;
  26079. }
  26080. this._animationTimeLast = now;
  26081. }
  26082. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26083. this._animationTime += deltaTime;
  26084. this._animationTimeLast = now;
  26085. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26086. this._activeAnimatables[index]._animate(this._animationTime);
  26087. }
  26088. // Late animation bindings
  26089. this._processLateAnimationBindings();
  26090. };
  26091. /** @hidden */
  26092. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26093. var target = runtimeAnimation.target;
  26094. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26095. if (!target._lateAnimationHolders) {
  26096. target._lateAnimationHolders = {};
  26097. }
  26098. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26099. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26100. totalWeight: 0,
  26101. animations: [],
  26102. originalValue: originalValue
  26103. };
  26104. }
  26105. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26106. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26107. };
  26108. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26109. var normalizer = 1.0;
  26110. var finalPosition = BABYLON.Tmp.Vector3[0];
  26111. var finalScaling = BABYLON.Tmp.Vector3[1];
  26112. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26113. var startIndex = 0;
  26114. var originalAnimation = holder.animations[0];
  26115. var originalValue = holder.originalValue;
  26116. var scale = 1;
  26117. if (holder.totalWeight < 1.0) {
  26118. // We need to mix the original value in
  26119. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26120. scale = 1.0 - holder.totalWeight;
  26121. }
  26122. else {
  26123. startIndex = 1;
  26124. // We need to normalize the weights
  26125. normalizer = holder.totalWeight;
  26126. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26127. scale = originalAnimation.weight / normalizer;
  26128. if (scale == 1) {
  26129. return originalAnimation.currentValue;
  26130. }
  26131. }
  26132. finalScaling.scaleInPlace(scale);
  26133. finalPosition.scaleInPlace(scale);
  26134. finalQuaternion.scaleInPlace(scale);
  26135. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26136. var runtimeAnimation = holder.animations[animIndex];
  26137. var scale = runtimeAnimation.weight / normalizer;
  26138. var currentPosition = BABYLON.Tmp.Vector3[2];
  26139. var currentScaling = BABYLON.Tmp.Vector3[3];
  26140. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26141. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26142. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26143. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26144. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26145. }
  26146. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26147. return originalAnimation._workValue;
  26148. };
  26149. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26150. var originalAnimation = holder.animations[0];
  26151. var originalValue = holder.originalValue;
  26152. if (holder.animations.length === 1) {
  26153. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26154. return refQuaternion;
  26155. }
  26156. var normalizer = 1.0;
  26157. var quaternions;
  26158. var weights;
  26159. if (holder.totalWeight < 1.0) {
  26160. var scale = 1.0 - holder.totalWeight;
  26161. quaternions = [];
  26162. weights = [];
  26163. quaternions.push(originalValue);
  26164. weights.push(scale);
  26165. }
  26166. else {
  26167. if (holder.animations.length === 2) { // Slerp as soon as we can
  26168. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26169. return refQuaternion;
  26170. }
  26171. quaternions = [];
  26172. weights = [];
  26173. normalizer = holder.totalWeight;
  26174. }
  26175. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26176. var runtimeAnimation = holder.animations[animIndex];
  26177. quaternions.push(runtimeAnimation.currentValue);
  26178. weights.push(runtimeAnimation.weight / normalizer);
  26179. }
  26180. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26181. var cumulativeAmount = 0;
  26182. var cumulativeQuaternion = null;
  26183. for (var index = 0; index < quaternions.length;) {
  26184. if (!cumulativeQuaternion) {
  26185. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26186. cumulativeQuaternion = refQuaternion;
  26187. cumulativeAmount = weights[index] + weights[index + 1];
  26188. index += 2;
  26189. continue;
  26190. }
  26191. cumulativeAmount += weights[index];
  26192. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26193. index++;
  26194. }
  26195. return cumulativeQuaternion;
  26196. };
  26197. Scene.prototype._processLateAnimationBindings = function () {
  26198. if (!this._registeredForLateAnimationBindings.length) {
  26199. return;
  26200. }
  26201. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26202. var target = this._registeredForLateAnimationBindings.data[index];
  26203. for (var path in target._lateAnimationHolders) {
  26204. var holder = target._lateAnimationHolders[path];
  26205. var originalAnimation = holder.animations[0];
  26206. var originalValue = holder.originalValue;
  26207. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26208. var finalValue = target[path];
  26209. if (matrixDecomposeMode) {
  26210. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26211. }
  26212. else {
  26213. var quaternionMode = originalValue.w !== undefined;
  26214. if (quaternionMode) {
  26215. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26216. }
  26217. else {
  26218. var startIndex = 0;
  26219. var normalizer = 1.0;
  26220. if (holder.totalWeight < 1.0) {
  26221. // We need to mix the original value in
  26222. if (originalValue.scale) {
  26223. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26224. }
  26225. else {
  26226. finalValue = originalValue * (1.0 - holder.totalWeight);
  26227. }
  26228. }
  26229. else {
  26230. // We need to normalize the weights
  26231. normalizer = holder.totalWeight;
  26232. var scale_1 = originalAnimation.weight / normalizer;
  26233. if (scale_1 !== 1) {
  26234. if (originalAnimation.currentValue.scale) {
  26235. finalValue = originalAnimation.currentValue.scale(scale_1);
  26236. }
  26237. else {
  26238. finalValue = originalAnimation.currentValue * scale_1;
  26239. }
  26240. }
  26241. else {
  26242. finalValue = originalAnimation.currentValue;
  26243. }
  26244. startIndex = 1;
  26245. }
  26246. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26247. var runtimeAnimation = holder.animations[animIndex];
  26248. var scale = runtimeAnimation.weight / normalizer;
  26249. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26250. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26251. }
  26252. else {
  26253. finalValue += runtimeAnimation.currentValue * scale;
  26254. }
  26255. }
  26256. }
  26257. }
  26258. target[path] = finalValue;
  26259. }
  26260. target._lateAnimationHolders = {};
  26261. }
  26262. this._registeredForLateAnimationBindings.reset();
  26263. };
  26264. // Matrix
  26265. /** @hidden */
  26266. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26267. this._useAlternateCameraConfiguration = active;
  26268. };
  26269. /**
  26270. * Gets the current view matrix
  26271. * @returns a Matrix
  26272. */
  26273. Scene.prototype.getViewMatrix = function () {
  26274. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26275. };
  26276. /**
  26277. * Gets the current projection matrix
  26278. * @returns a Matrix
  26279. */
  26280. Scene.prototype.getProjectionMatrix = function () {
  26281. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26282. };
  26283. /**
  26284. * Gets the current transform matrix
  26285. * @returns a Matrix made of View * Projection
  26286. */
  26287. Scene.prototype.getTransformMatrix = function () {
  26288. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26289. };
  26290. /**
  26291. * Sets the current transform matrix
  26292. * @param view defines the View matrix to use
  26293. * @param projection defines the Projection matrix to use
  26294. */
  26295. Scene.prototype.setTransformMatrix = function (view, projection) {
  26296. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26297. return;
  26298. }
  26299. this._viewUpdateFlag = view.updateFlag;
  26300. this._projectionUpdateFlag = projection.updateFlag;
  26301. this._viewMatrix = view;
  26302. this._projectionMatrix = projection;
  26303. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26304. // Update frustum
  26305. if (!this._frustumPlanes) {
  26306. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26307. }
  26308. else {
  26309. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26310. }
  26311. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26312. var otherCamera = this.activeCamera._alternateCamera;
  26313. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26314. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26315. }
  26316. if (this._sceneUbo.useUbo) {
  26317. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26318. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26319. this._sceneUbo.update();
  26320. }
  26321. };
  26322. /** @hidden */
  26323. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26324. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26325. return;
  26326. }
  26327. this._alternateViewUpdateFlag = view.updateFlag;
  26328. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26329. this._alternateViewMatrix = view;
  26330. this._alternateProjectionMatrix = projection;
  26331. if (!this._alternateTransformMatrix) {
  26332. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26333. }
  26334. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26335. if (!this._alternateSceneUbo) {
  26336. this._createAlternateUbo();
  26337. }
  26338. if (this._alternateSceneUbo.useUbo) {
  26339. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26340. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26341. this._alternateSceneUbo.update();
  26342. }
  26343. };
  26344. /**
  26345. * Gets the uniform buffer used to store scene data
  26346. * @returns a UniformBuffer
  26347. */
  26348. Scene.prototype.getSceneUniformBuffer = function () {
  26349. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26350. };
  26351. /**
  26352. * Gets an unique (relatively to the current scene) Id
  26353. * @returns an unique number for the scene
  26354. */
  26355. Scene.prototype.getUniqueId = function () {
  26356. var result = Scene._uniqueIdCounter;
  26357. Scene._uniqueIdCounter++;
  26358. return result;
  26359. };
  26360. /**
  26361. * Add a mesh to the list of scene's meshes
  26362. * @param newMesh defines the mesh to add
  26363. * @param recursive if all child meshes should also be added to the scene
  26364. */
  26365. Scene.prototype.addMesh = function (newMesh, recursive) {
  26366. var _this = this;
  26367. if (recursive === void 0) { recursive = false; }
  26368. this.meshes.push(newMesh);
  26369. //notify the collision coordinator
  26370. if (this.collisionCoordinator) {
  26371. this.collisionCoordinator.onMeshAdded(newMesh);
  26372. }
  26373. newMesh._resyncLightSources();
  26374. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26375. if (recursive) {
  26376. newMesh.getChildMeshes().forEach(function (m) {
  26377. _this.addMesh(m);
  26378. });
  26379. }
  26380. };
  26381. /**
  26382. * Remove a mesh for the list of scene's meshes
  26383. * @param toRemove defines the mesh to remove
  26384. * @param recursive if all child meshes should also be removed from the scene
  26385. * @returns the index where the mesh was in the mesh list
  26386. */
  26387. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26388. var _this = this;
  26389. if (recursive === void 0) { recursive = false; }
  26390. var index = this.meshes.indexOf(toRemove);
  26391. if (index !== -1) {
  26392. // Remove from the scene if mesh found
  26393. this.meshes.splice(index, 1);
  26394. }
  26395. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26396. if (recursive) {
  26397. toRemove.getChildMeshes().forEach(function (m) {
  26398. _this.removeMesh(m);
  26399. });
  26400. }
  26401. return index;
  26402. };
  26403. /**
  26404. * Add a transform node to the list of scene's transform nodes
  26405. * @param newTransformNode defines the transform node to add
  26406. */
  26407. Scene.prototype.addTransformNode = function (newTransformNode) {
  26408. this.transformNodes.push(newTransformNode);
  26409. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26410. };
  26411. /**
  26412. * Remove a transform node for the list of scene's transform nodes
  26413. * @param toRemove defines the transform node to remove
  26414. * @returns the index where the transform node was in the transform node list
  26415. */
  26416. Scene.prototype.removeTransformNode = function (toRemove) {
  26417. var index = this.transformNodes.indexOf(toRemove);
  26418. if (index !== -1) {
  26419. // Remove from the scene if found
  26420. this.transformNodes.splice(index, 1);
  26421. }
  26422. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26423. return index;
  26424. };
  26425. /**
  26426. * Remove a skeleton for the list of scene's skeletons
  26427. * @param toRemove defines the skeleton to remove
  26428. * @returns the index where the skeleton was in the skeleton list
  26429. */
  26430. Scene.prototype.removeSkeleton = function (toRemove) {
  26431. var index = this.skeletons.indexOf(toRemove);
  26432. if (index !== -1) {
  26433. // Remove from the scene if found
  26434. this.skeletons.splice(index, 1);
  26435. }
  26436. return index;
  26437. };
  26438. /**
  26439. * Remove a morph target for the list of scene's morph targets
  26440. * @param toRemove defines the morph target to remove
  26441. * @returns the index where the morph target was in the morph target list
  26442. */
  26443. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26444. var index = this.morphTargetManagers.indexOf(toRemove);
  26445. if (index !== -1) {
  26446. // Remove from the scene if found
  26447. this.morphTargetManagers.splice(index, 1);
  26448. }
  26449. return index;
  26450. };
  26451. /**
  26452. * Remove a light for the list of scene's lights
  26453. * @param toRemove defines the light to remove
  26454. * @returns the index where the light was in the light list
  26455. */
  26456. Scene.prototype.removeLight = function (toRemove) {
  26457. var index = this.lights.indexOf(toRemove);
  26458. if (index !== -1) {
  26459. // Remove from meshes
  26460. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26461. var mesh = _a[_i];
  26462. mesh._removeLightSource(toRemove);
  26463. }
  26464. // Remove from the scene if mesh found
  26465. this.lights.splice(index, 1);
  26466. this.sortLightsByPriority();
  26467. }
  26468. this.onLightRemovedObservable.notifyObservers(toRemove);
  26469. return index;
  26470. };
  26471. /**
  26472. * Remove a camera for the list of scene's cameras
  26473. * @param toRemove defines the camera to remove
  26474. * @returns the index where the camera was in the camera list
  26475. */
  26476. Scene.prototype.removeCamera = function (toRemove) {
  26477. var index = this.cameras.indexOf(toRemove);
  26478. if (index !== -1) {
  26479. // Remove from the scene if mesh found
  26480. this.cameras.splice(index, 1);
  26481. }
  26482. // Remove from activeCameras
  26483. var index2 = this.activeCameras.indexOf(toRemove);
  26484. if (index2 !== -1) {
  26485. // Remove from the scene if mesh found
  26486. this.activeCameras.splice(index2, 1);
  26487. }
  26488. // Reset the activeCamera
  26489. if (this.activeCamera === toRemove) {
  26490. if (this.cameras.length > 0) {
  26491. this.activeCamera = this.cameras[0];
  26492. }
  26493. else {
  26494. this.activeCamera = null;
  26495. }
  26496. }
  26497. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26498. return index;
  26499. };
  26500. /**
  26501. * Remove a particle system for the list of scene's particle systems
  26502. * @param toRemove defines the particle system to remove
  26503. * @returns the index where the particle system was in the particle system list
  26504. */
  26505. Scene.prototype.removeParticleSystem = function (toRemove) {
  26506. var index = this.particleSystems.indexOf(toRemove);
  26507. if (index !== -1) {
  26508. this.particleSystems.splice(index, 1);
  26509. }
  26510. return index;
  26511. };
  26512. /**
  26513. * Remove a animation for the list of scene's animations
  26514. * @param toRemove defines the animation to remove
  26515. * @returns the index where the animation was in the animation list
  26516. */
  26517. Scene.prototype.removeAnimation = function (toRemove) {
  26518. var index = this.animations.indexOf(toRemove);
  26519. if (index !== -1) {
  26520. this.animations.splice(index, 1);
  26521. }
  26522. return index;
  26523. };
  26524. /**
  26525. * Removes the given animation group from this scene.
  26526. * @param toRemove The animation group to remove
  26527. * @returns The index of the removed animation group
  26528. */
  26529. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26530. var index = this.animationGroups.indexOf(toRemove);
  26531. if (index !== -1) {
  26532. this.animationGroups.splice(index, 1);
  26533. }
  26534. return index;
  26535. };
  26536. /**
  26537. * Removes the given multi-material from this scene.
  26538. * @param toRemove The multi-material to remove
  26539. * @returns The index of the removed multi-material
  26540. */
  26541. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26542. var index = this.multiMaterials.indexOf(toRemove);
  26543. if (index !== -1) {
  26544. this.multiMaterials.splice(index, 1);
  26545. }
  26546. return index;
  26547. };
  26548. /**
  26549. * Removes the given material from this scene.
  26550. * @param toRemove The material to remove
  26551. * @returns The index of the removed material
  26552. */
  26553. Scene.prototype.removeMaterial = function (toRemove) {
  26554. var index = this.materials.indexOf(toRemove);
  26555. if (index !== -1) {
  26556. this.materials.splice(index, 1);
  26557. }
  26558. return index;
  26559. };
  26560. /**
  26561. * Removes the given action manager from this scene.
  26562. * @param toRemove The action manager to remove
  26563. * @returns The index of the removed action manager
  26564. */
  26565. Scene.prototype.removeActionManager = function (toRemove) {
  26566. var index = this.actionManagers.indexOf(toRemove);
  26567. if (index !== -1) {
  26568. this.actionManagers.splice(index, 1);
  26569. }
  26570. return index;
  26571. };
  26572. /**
  26573. * Removes the given texture from this scene.
  26574. * @param toRemove The texture to remove
  26575. * @returns The index of the removed texture
  26576. */
  26577. Scene.prototype.removeTexture = function (toRemove) {
  26578. var index = this.textures.indexOf(toRemove);
  26579. if (index !== -1) {
  26580. this.textures.splice(index, 1);
  26581. }
  26582. return index;
  26583. };
  26584. /**
  26585. * Adds the given light to this scene
  26586. * @param newLight The light to add
  26587. */
  26588. Scene.prototype.addLight = function (newLight) {
  26589. this.lights.push(newLight);
  26590. this.sortLightsByPriority();
  26591. // Add light to all meshes (To support if the light is removed and then readded)
  26592. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26593. var mesh = _a[_i];
  26594. if (mesh._lightSources.indexOf(newLight) === -1) {
  26595. mesh._lightSources.push(newLight);
  26596. mesh._resyncLightSources();
  26597. }
  26598. }
  26599. this.onNewLightAddedObservable.notifyObservers(newLight);
  26600. };
  26601. /**
  26602. * Sorts the list list based on light priorities
  26603. */
  26604. Scene.prototype.sortLightsByPriority = function () {
  26605. if (this.requireLightSorting) {
  26606. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26607. }
  26608. };
  26609. /**
  26610. * Adds the given camera to this scene
  26611. * @param newCamera The camera to add
  26612. */
  26613. Scene.prototype.addCamera = function (newCamera) {
  26614. this.cameras.push(newCamera);
  26615. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26616. };
  26617. /**
  26618. * Adds the given skeleton to this scene
  26619. * @param newSkeleton The skeleton to add
  26620. */
  26621. Scene.prototype.addSkeleton = function (newSkeleton) {
  26622. this.skeletons.push(newSkeleton);
  26623. };
  26624. /**
  26625. * Adds the given particle system to this scene
  26626. * @param newParticleSystem The particle system to add
  26627. */
  26628. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26629. this.particleSystems.push(newParticleSystem);
  26630. };
  26631. /**
  26632. * Adds the given animation to this scene
  26633. * @param newAnimation The animation to add
  26634. */
  26635. Scene.prototype.addAnimation = function (newAnimation) {
  26636. this.animations.push(newAnimation);
  26637. };
  26638. /**
  26639. * Adds the given animation group to this scene.
  26640. * @param newAnimationGroup The animation group to add
  26641. */
  26642. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26643. this.animationGroups.push(newAnimationGroup);
  26644. };
  26645. /**
  26646. * Adds the given multi-material to this scene
  26647. * @param newMultiMaterial The multi-material to add
  26648. */
  26649. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26650. this.multiMaterials.push(newMultiMaterial);
  26651. };
  26652. /**
  26653. * Adds the given material to this scene
  26654. * @param newMaterial The material to add
  26655. */
  26656. Scene.prototype.addMaterial = function (newMaterial) {
  26657. this.materials.push(newMaterial);
  26658. };
  26659. /**
  26660. * Adds the given morph target to this scene
  26661. * @param newMorphTargetManager The morph target to add
  26662. */
  26663. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26664. this.morphTargetManagers.push(newMorphTargetManager);
  26665. };
  26666. /**
  26667. * Adds the given geometry to this scene
  26668. * @param newGeometry The geometry to add
  26669. */
  26670. Scene.prototype.addGeometry = function (newGeometry) {
  26671. this.geometries.push(newGeometry);
  26672. };
  26673. /**
  26674. * Adds the given action manager to this scene
  26675. * @param newActionManager The action manager to add
  26676. */
  26677. Scene.prototype.addActionManager = function (newActionManager) {
  26678. this.actionManagers.push(newActionManager);
  26679. };
  26680. /**
  26681. * Adds the given texture to this scene.
  26682. * @param newTexture The texture to add
  26683. */
  26684. Scene.prototype.addTexture = function (newTexture) {
  26685. this.textures.push(newTexture);
  26686. };
  26687. /**
  26688. * Switch active camera
  26689. * @param newCamera defines the new active camera
  26690. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26691. */
  26692. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26693. if (attachControl === void 0) { attachControl = true; }
  26694. var canvas = this._engine.getRenderingCanvas();
  26695. if (!canvas) {
  26696. return;
  26697. }
  26698. if (this.activeCamera) {
  26699. this.activeCamera.detachControl(canvas);
  26700. }
  26701. this.activeCamera = newCamera;
  26702. if (attachControl) {
  26703. newCamera.attachControl(canvas);
  26704. }
  26705. };
  26706. /**
  26707. * sets the active camera of the scene using its ID
  26708. * @param id defines the camera's ID
  26709. * @return the new active camera or null if none found.
  26710. */
  26711. Scene.prototype.setActiveCameraByID = function (id) {
  26712. var camera = this.getCameraByID(id);
  26713. if (camera) {
  26714. this.activeCamera = camera;
  26715. return camera;
  26716. }
  26717. return null;
  26718. };
  26719. /**
  26720. * sets the active camera of the scene using its name
  26721. * @param name defines the camera's name
  26722. * @returns the new active camera or null if none found.
  26723. */
  26724. Scene.prototype.setActiveCameraByName = function (name) {
  26725. var camera = this.getCameraByName(name);
  26726. if (camera) {
  26727. this.activeCamera = camera;
  26728. return camera;
  26729. }
  26730. return null;
  26731. };
  26732. /**
  26733. * get an animation group using its name
  26734. * @param name defines the material's name
  26735. * @return the animation group or null if none found.
  26736. */
  26737. Scene.prototype.getAnimationGroupByName = function (name) {
  26738. for (var index = 0; index < this.animationGroups.length; index++) {
  26739. if (this.animationGroups[index].name === name) {
  26740. return this.animationGroups[index];
  26741. }
  26742. }
  26743. return null;
  26744. };
  26745. /**
  26746. * get a material using its id
  26747. * @param id defines the material's ID
  26748. * @return the material or null if none found.
  26749. */
  26750. Scene.prototype.getMaterialByID = function (id) {
  26751. for (var index = 0; index < this.materials.length; index++) {
  26752. if (this.materials[index].id === id) {
  26753. return this.materials[index];
  26754. }
  26755. }
  26756. return null;
  26757. };
  26758. /**
  26759. * Gets a material using its name
  26760. * @param name defines the material's name
  26761. * @return the material or null if none found.
  26762. */
  26763. Scene.prototype.getMaterialByName = function (name) {
  26764. for (var index = 0; index < this.materials.length; index++) {
  26765. if (this.materials[index].name === name) {
  26766. return this.materials[index];
  26767. }
  26768. }
  26769. return null;
  26770. };
  26771. /**
  26772. * Gets a camera using its id
  26773. * @param id defines the id to look for
  26774. * @returns the camera or null if not found
  26775. */
  26776. Scene.prototype.getCameraByID = function (id) {
  26777. for (var index = 0; index < this.cameras.length; index++) {
  26778. if (this.cameras[index].id === id) {
  26779. return this.cameras[index];
  26780. }
  26781. }
  26782. return null;
  26783. };
  26784. /**
  26785. * Gets a camera using its unique id
  26786. * @param uniqueId defines the unique id to look for
  26787. * @returns the camera or null if not found
  26788. */
  26789. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26790. for (var index = 0; index < this.cameras.length; index++) {
  26791. if (this.cameras[index].uniqueId === uniqueId) {
  26792. return this.cameras[index];
  26793. }
  26794. }
  26795. return null;
  26796. };
  26797. /**
  26798. * Gets a camera using its name
  26799. * @param name defines the camera's name
  26800. * @return the camera or null if none found.
  26801. */
  26802. Scene.prototype.getCameraByName = function (name) {
  26803. for (var index = 0; index < this.cameras.length; index++) {
  26804. if (this.cameras[index].name === name) {
  26805. return this.cameras[index];
  26806. }
  26807. }
  26808. return null;
  26809. };
  26810. /**
  26811. * Gets a bone using its id
  26812. * @param id defines the bone's id
  26813. * @return the bone or null if not found
  26814. */
  26815. Scene.prototype.getBoneByID = function (id) {
  26816. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26817. var skeleton = this.skeletons[skeletonIndex];
  26818. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26819. if (skeleton.bones[boneIndex].id === id) {
  26820. return skeleton.bones[boneIndex];
  26821. }
  26822. }
  26823. }
  26824. return null;
  26825. };
  26826. /**
  26827. * Gets a bone using its id
  26828. * @param name defines the bone's name
  26829. * @return the bone or null if not found
  26830. */
  26831. Scene.prototype.getBoneByName = function (name) {
  26832. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26833. var skeleton = this.skeletons[skeletonIndex];
  26834. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26835. if (skeleton.bones[boneIndex].name === name) {
  26836. return skeleton.bones[boneIndex];
  26837. }
  26838. }
  26839. }
  26840. return null;
  26841. };
  26842. /**
  26843. * Gets a light node using its name
  26844. * @param name defines the the light's name
  26845. * @return the light or null if none found.
  26846. */
  26847. Scene.prototype.getLightByName = function (name) {
  26848. for (var index = 0; index < this.lights.length; index++) {
  26849. if (this.lights[index].name === name) {
  26850. return this.lights[index];
  26851. }
  26852. }
  26853. return null;
  26854. };
  26855. /**
  26856. * Gets a light node using its id
  26857. * @param id defines the light's id
  26858. * @return the light or null if none found.
  26859. */
  26860. Scene.prototype.getLightByID = function (id) {
  26861. for (var index = 0; index < this.lights.length; index++) {
  26862. if (this.lights[index].id === id) {
  26863. return this.lights[index];
  26864. }
  26865. }
  26866. return null;
  26867. };
  26868. /**
  26869. * Gets a light node using its scene-generated unique ID
  26870. * @param uniqueId defines the light's unique id
  26871. * @return the light or null if none found.
  26872. */
  26873. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26874. for (var index = 0; index < this.lights.length; index++) {
  26875. if (this.lights[index].uniqueId === uniqueId) {
  26876. return this.lights[index];
  26877. }
  26878. }
  26879. return null;
  26880. };
  26881. /**
  26882. * Gets a particle system by id
  26883. * @param id defines the particle system id
  26884. * @return the corresponding system or null if none found
  26885. */
  26886. Scene.prototype.getParticleSystemByID = function (id) {
  26887. for (var index = 0; index < this.particleSystems.length; index++) {
  26888. if (this.particleSystems[index].id === id) {
  26889. return this.particleSystems[index];
  26890. }
  26891. }
  26892. return null;
  26893. };
  26894. /**
  26895. * Gets a geometry using its ID
  26896. * @param id defines the geometry's id
  26897. * @return the geometry or null if none found.
  26898. */
  26899. Scene.prototype.getGeometryByID = function (id) {
  26900. for (var index = 0; index < this.geometries.length; index++) {
  26901. if (this.geometries[index].id === id) {
  26902. return this.geometries[index];
  26903. }
  26904. }
  26905. return null;
  26906. };
  26907. /**
  26908. * Add a new geometry to this scene
  26909. * @param geometry defines the geometry to be added to the scene.
  26910. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26911. * @return a boolean defining if the geometry was added or not
  26912. */
  26913. Scene.prototype.pushGeometry = function (geometry, force) {
  26914. if (!force && this.getGeometryByID(geometry.id)) {
  26915. return false;
  26916. }
  26917. this.geometries.push(geometry);
  26918. //notify the collision coordinator
  26919. if (this.collisionCoordinator) {
  26920. this.collisionCoordinator.onGeometryAdded(geometry);
  26921. }
  26922. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26923. return true;
  26924. };
  26925. /**
  26926. * Removes an existing geometry
  26927. * @param geometry defines the geometry to be removed from the scene
  26928. * @return a boolean defining if the geometry was removed or not
  26929. */
  26930. Scene.prototype.removeGeometry = function (geometry) {
  26931. var index = this.geometries.indexOf(geometry);
  26932. if (index > -1) {
  26933. this.geometries.splice(index, 1);
  26934. //notify the collision coordinator
  26935. if (this.collisionCoordinator) {
  26936. this.collisionCoordinator.onGeometryDeleted(geometry);
  26937. }
  26938. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26939. return true;
  26940. }
  26941. return false;
  26942. };
  26943. /**
  26944. * Gets the list of geometries attached to the scene
  26945. * @returns an array of Geometry
  26946. */
  26947. Scene.prototype.getGeometries = function () {
  26948. return this.geometries;
  26949. };
  26950. /**
  26951. * Gets the first added mesh found of a given ID
  26952. * @param id defines the id to search for
  26953. * @return the mesh found or null if not found at all
  26954. */
  26955. Scene.prototype.getMeshByID = function (id) {
  26956. for (var index = 0; index < this.meshes.length; index++) {
  26957. if (this.meshes[index].id === id) {
  26958. return this.meshes[index];
  26959. }
  26960. }
  26961. return null;
  26962. };
  26963. /**
  26964. * Gets a list of meshes using their id
  26965. * @param id defines the id to search for
  26966. * @returns a list of meshes
  26967. */
  26968. Scene.prototype.getMeshesByID = function (id) {
  26969. return this.meshes.filter(function (m) {
  26970. return m.id === id;
  26971. });
  26972. };
  26973. /**
  26974. * Gets the first added transform node found of a given ID
  26975. * @param id defines the id to search for
  26976. * @return the found transform node or null if not found at all.
  26977. */
  26978. Scene.prototype.getTransformNodeByID = function (id) {
  26979. for (var index = 0; index < this.transformNodes.length; index++) {
  26980. if (this.transformNodes[index].id === id) {
  26981. return this.transformNodes[index];
  26982. }
  26983. }
  26984. return null;
  26985. };
  26986. /**
  26987. * Gets a list of transform nodes using their id
  26988. * @param id defines the id to search for
  26989. * @returns a list of transform nodes
  26990. */
  26991. Scene.prototype.getTransformNodesByID = function (id) {
  26992. return this.transformNodes.filter(function (m) {
  26993. return m.id === id;
  26994. });
  26995. };
  26996. /**
  26997. * Gets a mesh with its auto-generated unique id
  26998. * @param uniqueId defines the unique id to search for
  26999. * @return the found mesh or null if not found at all.
  27000. */
  27001. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27002. for (var index = 0; index < this.meshes.length; index++) {
  27003. if (this.meshes[index].uniqueId === uniqueId) {
  27004. return this.meshes[index];
  27005. }
  27006. }
  27007. return null;
  27008. };
  27009. /**
  27010. * Gets a the last added mesh using a given id
  27011. * @param id defines the id to search for
  27012. * @return the found mesh or null if not found at all.
  27013. */
  27014. Scene.prototype.getLastMeshByID = function (id) {
  27015. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27016. if (this.meshes[index].id === id) {
  27017. return this.meshes[index];
  27018. }
  27019. }
  27020. return null;
  27021. };
  27022. /**
  27023. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27024. * @param id defines the id to search for
  27025. * @return the found node or null if not found at all
  27026. */
  27027. Scene.prototype.getLastEntryByID = function (id) {
  27028. var index;
  27029. for (index = this.meshes.length - 1; index >= 0; index--) {
  27030. if (this.meshes[index].id === id) {
  27031. return this.meshes[index];
  27032. }
  27033. }
  27034. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27035. if (this.transformNodes[index].id === id) {
  27036. return this.transformNodes[index];
  27037. }
  27038. }
  27039. for (index = this.cameras.length - 1; index >= 0; index--) {
  27040. if (this.cameras[index].id === id) {
  27041. return this.cameras[index];
  27042. }
  27043. }
  27044. for (index = this.lights.length - 1; index >= 0; index--) {
  27045. if (this.lights[index].id === id) {
  27046. return this.lights[index];
  27047. }
  27048. }
  27049. return null;
  27050. };
  27051. /**
  27052. * Gets a node (Mesh, Camera, Light) using a given id
  27053. * @param id defines the id to search for
  27054. * @return the found node or null if not found at all
  27055. */
  27056. Scene.prototype.getNodeByID = function (id) {
  27057. var mesh = this.getMeshByID(id);
  27058. if (mesh) {
  27059. return mesh;
  27060. }
  27061. var light = this.getLightByID(id);
  27062. if (light) {
  27063. return light;
  27064. }
  27065. var camera = this.getCameraByID(id);
  27066. if (camera) {
  27067. return camera;
  27068. }
  27069. var bone = this.getBoneByID(id);
  27070. return bone;
  27071. };
  27072. /**
  27073. * Gets a node (Mesh, Camera, Light) using a given name
  27074. * @param name defines the name to search for
  27075. * @return the found node or null if not found at all.
  27076. */
  27077. Scene.prototype.getNodeByName = function (name) {
  27078. var mesh = this.getMeshByName(name);
  27079. if (mesh) {
  27080. return mesh;
  27081. }
  27082. var light = this.getLightByName(name);
  27083. if (light) {
  27084. return light;
  27085. }
  27086. var camera = this.getCameraByName(name);
  27087. if (camera) {
  27088. return camera;
  27089. }
  27090. var bone = this.getBoneByName(name);
  27091. return bone;
  27092. };
  27093. /**
  27094. * Gets a mesh using a given name
  27095. * @param name defines the name to search for
  27096. * @return the found mesh or null if not found at all.
  27097. */
  27098. Scene.prototype.getMeshByName = function (name) {
  27099. for (var index = 0; index < this.meshes.length; index++) {
  27100. if (this.meshes[index].name === name) {
  27101. return this.meshes[index];
  27102. }
  27103. }
  27104. return null;
  27105. };
  27106. /**
  27107. * Gets a transform node using a given name
  27108. * @param name defines the name to search for
  27109. * @return the found transform node or null if not found at all.
  27110. */
  27111. Scene.prototype.getTransformNodeByName = function (name) {
  27112. for (var index = 0; index < this.transformNodes.length; index++) {
  27113. if (this.transformNodes[index].name === name) {
  27114. return this.transformNodes[index];
  27115. }
  27116. }
  27117. return null;
  27118. };
  27119. /**
  27120. * Gets a sound using a given name
  27121. * @param name defines the name to search for
  27122. * @return the found sound or null if not found at all.
  27123. */
  27124. Scene.prototype.getSoundByName = function (name) {
  27125. var index;
  27126. if (BABYLON.AudioEngine) {
  27127. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27128. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27129. return this.mainSoundTrack.soundCollection[index];
  27130. }
  27131. }
  27132. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27133. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27134. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27135. return this.soundTracks[sdIndex].soundCollection[index];
  27136. }
  27137. }
  27138. }
  27139. }
  27140. return null;
  27141. };
  27142. /**
  27143. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27144. * @param id defines the id to search for
  27145. * @return the found skeleton or null if not found at all.
  27146. */
  27147. Scene.prototype.getLastSkeletonByID = function (id) {
  27148. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27149. if (this.skeletons[index].id === id) {
  27150. return this.skeletons[index];
  27151. }
  27152. }
  27153. return null;
  27154. };
  27155. /**
  27156. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27157. * @param id defines the id to search for
  27158. * @return the found skeleton or null if not found at all.
  27159. */
  27160. Scene.prototype.getSkeletonById = function (id) {
  27161. for (var index = 0; index < this.skeletons.length; index++) {
  27162. if (this.skeletons[index].id === id) {
  27163. return this.skeletons[index];
  27164. }
  27165. }
  27166. return null;
  27167. };
  27168. /**
  27169. * Gets a skeleton using a given name
  27170. * @param name defines the name to search for
  27171. * @return the found skeleton or null if not found at all.
  27172. */
  27173. Scene.prototype.getSkeletonByName = function (name) {
  27174. for (var index = 0; index < this.skeletons.length; index++) {
  27175. if (this.skeletons[index].name === name) {
  27176. return this.skeletons[index];
  27177. }
  27178. }
  27179. return null;
  27180. };
  27181. /**
  27182. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27183. * @param id defines the id to search for
  27184. * @return the found morph target manager or null if not found at all.
  27185. */
  27186. Scene.prototype.getMorphTargetManagerById = function (id) {
  27187. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27188. if (this.morphTargetManagers[index].uniqueId === id) {
  27189. return this.morphTargetManagers[index];
  27190. }
  27191. }
  27192. return null;
  27193. };
  27194. /**
  27195. * Gets a boolean indicating if the given mesh is active
  27196. * @param mesh defines the mesh to look for
  27197. * @returns true if the mesh is in the active list
  27198. */
  27199. Scene.prototype.isActiveMesh = function (mesh) {
  27200. return (this._activeMeshes.indexOf(mesh) !== -1);
  27201. };
  27202. Object.defineProperty(Scene.prototype, "uid", {
  27203. /**
  27204. * Return a unique id as a string which can serve as an identifier for the scene
  27205. */
  27206. get: function () {
  27207. if (!this._uid) {
  27208. this._uid = BABYLON.Tools.RandomId();
  27209. }
  27210. return this._uid;
  27211. },
  27212. enumerable: true,
  27213. configurable: true
  27214. });
  27215. /**
  27216. * Add an externaly attached data from its key.
  27217. * This method call will fail and return false, if such key already exists.
  27218. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27219. * @param key the unique key that identifies the data
  27220. * @param data the data object to associate to the key for this Engine instance
  27221. * @return true if no such key were already present and the data was added successfully, false otherwise
  27222. */
  27223. Scene.prototype.addExternalData = function (key, data) {
  27224. if (!this._externalData) {
  27225. this._externalData = new BABYLON.StringDictionary();
  27226. }
  27227. return this._externalData.add(key, data);
  27228. };
  27229. /**
  27230. * Get an externaly attached data from its key
  27231. * @param key the unique key that identifies the data
  27232. * @return the associated data, if present (can be null), or undefined if not present
  27233. */
  27234. Scene.prototype.getExternalData = function (key) {
  27235. if (!this._externalData) {
  27236. return null;
  27237. }
  27238. return this._externalData.get(key);
  27239. };
  27240. /**
  27241. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27242. * @param key the unique key that identifies the data
  27243. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27244. * @return the associated data, can be null if the factory returned null.
  27245. */
  27246. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27247. if (!this._externalData) {
  27248. this._externalData = new BABYLON.StringDictionary();
  27249. }
  27250. return this._externalData.getOrAddWithFactory(key, factory);
  27251. };
  27252. /**
  27253. * Remove an externaly attached data from the Engine instance
  27254. * @param key the unique key that identifies the data
  27255. * @return true if the data was successfully removed, false if it doesn't exist
  27256. */
  27257. Scene.prototype.removeExternalData = function (key) {
  27258. return this._externalData.remove(key);
  27259. };
  27260. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27261. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27262. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27263. var step = _a[_i];
  27264. step.action(mesh, subMesh);
  27265. }
  27266. var material = subMesh.getMaterial();
  27267. if (material !== null && material !== undefined) {
  27268. // Render targets
  27269. if (material.getRenderTargetTextures !== undefined) {
  27270. if (this._processedMaterials.indexOf(material) === -1) {
  27271. this._processedMaterials.push(material);
  27272. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27273. }
  27274. }
  27275. // Dispatch
  27276. this._activeIndices.addCount(subMesh.indexCount, false);
  27277. this._renderingManager.dispatch(subMesh, mesh, material);
  27278. }
  27279. }
  27280. };
  27281. /**
  27282. * Clear the processed materials smart array preventing retention point in material dispose.
  27283. */
  27284. Scene.prototype.freeProcessedMaterials = function () {
  27285. this._processedMaterials.dispose();
  27286. };
  27287. /**
  27288. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27289. */
  27290. Scene.prototype.freeActiveMeshes = function () {
  27291. this._activeMeshes.dispose();
  27292. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27293. this.activeCamera._activeMeshes.dispose();
  27294. }
  27295. if (this.activeCameras) {
  27296. for (var i = 0; i < this.activeCameras.length; i++) {
  27297. var activeCamera = this.activeCameras[i];
  27298. if (activeCamera && activeCamera._activeMeshes) {
  27299. activeCamera._activeMeshes.dispose();
  27300. }
  27301. }
  27302. }
  27303. };
  27304. /**
  27305. * Clear the info related to rendering groups preventing retention points during dispose.
  27306. */
  27307. Scene.prototype.freeRenderingGroups = function () {
  27308. if (this._renderingManager) {
  27309. this._renderingManager.freeRenderingGroups();
  27310. }
  27311. if (this.textures) {
  27312. for (var i = 0; i < this.textures.length; i++) {
  27313. var texture = this.textures[i];
  27314. if (texture && texture.renderList) {
  27315. texture.freeRenderingGroups();
  27316. }
  27317. }
  27318. }
  27319. };
  27320. /** @hidden */
  27321. Scene.prototype._isInIntermediateRendering = function () {
  27322. return this._intermediateRendering;
  27323. };
  27324. /**
  27325. * Defines the current active mesh candidate provider
  27326. * @param provider defines the provider to use
  27327. */
  27328. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27329. this._activeMeshCandidateProvider = provider;
  27330. };
  27331. /**
  27332. * Gets the current active mesh candidate provider
  27333. * @returns the current active mesh candidate provider
  27334. */
  27335. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27336. return this._activeMeshCandidateProvider;
  27337. };
  27338. /**
  27339. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27340. * @returns the current scene
  27341. */
  27342. Scene.prototype.freezeActiveMeshes = function () {
  27343. if (!this.activeCamera) {
  27344. return this;
  27345. }
  27346. if (!this._frustumPlanes) {
  27347. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27348. }
  27349. this._evaluateActiveMeshes();
  27350. this._activeMeshesFrozen = true;
  27351. return this;
  27352. };
  27353. /**
  27354. * Use this function to restart evaluating active meshes on every frame
  27355. * @returns the current scene
  27356. */
  27357. Scene.prototype.unfreezeActiveMeshes = function () {
  27358. this._activeMeshesFrozen = false;
  27359. return this;
  27360. };
  27361. Scene.prototype._evaluateActiveMeshes = function () {
  27362. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27363. return;
  27364. }
  27365. if (!this.activeCamera) {
  27366. return;
  27367. }
  27368. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27369. this.activeCamera._activeMeshes.reset();
  27370. this._activeMeshes.reset();
  27371. this._renderingManager.reset();
  27372. this._processedMaterials.reset();
  27373. this._activeParticleSystems.reset();
  27374. this._activeSkeletons.reset();
  27375. this._softwareSkinnedMeshes.reset();
  27376. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27377. var step = _a[_i];
  27378. step.action();
  27379. }
  27380. // Meshes
  27381. var meshes;
  27382. var len;
  27383. var checkIsEnabled = true;
  27384. // Determine mesh candidates
  27385. if (this._activeMeshCandidateProvider !== undefined) {
  27386. // Use _activeMeshCandidateProvider
  27387. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27388. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27389. if (meshes !== undefined) {
  27390. len = meshes.length;
  27391. }
  27392. else {
  27393. len = 0;
  27394. }
  27395. }
  27396. else if (this._selectionOctree !== undefined) {
  27397. // Octree
  27398. var selection = this._selectionOctree.select(this._frustumPlanes);
  27399. meshes = selection.data;
  27400. len = selection.length;
  27401. }
  27402. else {
  27403. // Full scene traversal
  27404. len = this.meshes.length;
  27405. meshes = this.meshes;
  27406. }
  27407. // Check each mesh
  27408. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27409. mesh = meshes[meshIndex];
  27410. if (mesh.isBlocked) {
  27411. continue;
  27412. }
  27413. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27414. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27415. continue;
  27416. }
  27417. mesh.computeWorldMatrix();
  27418. // Intersections
  27419. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27420. this._meshesForIntersections.pushNoDuplicate(mesh);
  27421. }
  27422. // Switch to current LOD
  27423. meshLOD = mesh.getLOD(this.activeCamera);
  27424. if (meshLOD === undefined || meshLOD === null) {
  27425. continue;
  27426. }
  27427. mesh._preActivate();
  27428. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27429. this._activeMeshes.push(mesh);
  27430. this.activeCamera._activeMeshes.push(mesh);
  27431. mesh._activate(this._renderId);
  27432. if (meshLOD !== mesh) {
  27433. meshLOD._activate(this._renderId);
  27434. }
  27435. this._activeMesh(mesh, meshLOD);
  27436. }
  27437. }
  27438. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27439. // Particle systems
  27440. if (this.particlesEnabled) {
  27441. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27442. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27443. var particleSystem = this.particleSystems[particleIndex];
  27444. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27445. continue;
  27446. }
  27447. var emitter = particleSystem.emitter;
  27448. if (!emitter.position || emitter.isEnabled()) {
  27449. this._activeParticleSystems.push(particleSystem);
  27450. particleSystem.animate();
  27451. this._renderingManager.dispatchParticles(particleSystem);
  27452. }
  27453. }
  27454. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27455. }
  27456. };
  27457. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27458. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27459. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27460. mesh.skeleton.prepare();
  27461. }
  27462. if (!mesh.computeBonesUsingShaders) {
  27463. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27464. }
  27465. }
  27466. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27467. var step = _a[_i];
  27468. step.action(sourceMesh, mesh);
  27469. }
  27470. if (mesh !== undefined && mesh !== null
  27471. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27472. // Submeshes Octrees
  27473. var len;
  27474. var subMeshes;
  27475. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27476. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27477. len = intersections.length;
  27478. subMeshes = intersections.data;
  27479. }
  27480. else {
  27481. subMeshes = mesh.subMeshes;
  27482. len = subMeshes.length;
  27483. }
  27484. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27485. subMesh = subMeshes[subIndex];
  27486. this._evaluateSubMesh(subMesh, mesh);
  27487. }
  27488. }
  27489. };
  27490. /**
  27491. * Update the transform matrix to update from the current active camera
  27492. * @param force defines a boolean used to force the update even if cache is up to date
  27493. */
  27494. Scene.prototype.updateTransformMatrix = function (force) {
  27495. if (!this.activeCamera) {
  27496. return;
  27497. }
  27498. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27499. };
  27500. /**
  27501. * 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)
  27502. * @param alternateCamera defines the camera to use
  27503. */
  27504. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27505. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27506. };
  27507. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27508. if (camera && camera._skipRendering) {
  27509. return;
  27510. }
  27511. var engine = this._engine;
  27512. this.activeCamera = camera;
  27513. if (!this.activeCamera)
  27514. throw new Error("Active camera not set");
  27515. // Viewport
  27516. engine.setViewport(this.activeCamera.viewport);
  27517. // Camera
  27518. this.resetCachedMaterial();
  27519. this._renderId++;
  27520. this.updateTransformMatrix();
  27521. if (camera._alternateCamera) {
  27522. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27523. this._alternateRendering = true;
  27524. }
  27525. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27526. // Meshes
  27527. this._evaluateActiveMeshes();
  27528. // Software skinning
  27529. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27530. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27531. mesh.applySkeleton(mesh.skeleton);
  27532. }
  27533. // Render targets
  27534. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27535. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27536. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27537. }
  27538. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27539. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27540. }
  27541. if (this.renderTargetsEnabled) {
  27542. this._intermediateRendering = true;
  27543. if (this._renderTargets.length > 0) {
  27544. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27545. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27546. var renderTarget = this._renderTargets.data[renderIndex];
  27547. if (renderTarget._shouldRender()) {
  27548. this._renderId++;
  27549. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27550. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27551. }
  27552. }
  27553. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27554. this._renderId++;
  27555. }
  27556. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27557. var step = _a[_i];
  27558. step.action(this.activeCamera);
  27559. }
  27560. this._intermediateRendering = false;
  27561. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27562. }
  27563. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27564. // Prepare Frame
  27565. if (this.postProcessManager) {
  27566. this.postProcessManager._prepareFrame();
  27567. }
  27568. // Before Camera Draw
  27569. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27570. var step = _c[_b];
  27571. step.action(this.activeCamera);
  27572. }
  27573. // Render
  27574. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27575. this._renderingManager.render(null, null, true, true);
  27576. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27577. // After Camera Draw
  27578. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27579. var step = _e[_d];
  27580. step.action(this.activeCamera);
  27581. }
  27582. // Finalize frame
  27583. if (this.postProcessManager) {
  27584. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27585. }
  27586. // Reset some special arrays
  27587. this._renderTargets.reset();
  27588. this._alternateRendering = false;
  27589. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27590. };
  27591. Scene.prototype._processSubCameras = function (camera) {
  27592. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27593. this._renderForCamera(camera);
  27594. return;
  27595. }
  27596. // rig cameras
  27597. for (var index = 0; index < camera._rigCameras.length; index++) {
  27598. this._renderForCamera(camera._rigCameras[index], camera);
  27599. }
  27600. this.activeCamera = camera;
  27601. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27602. };
  27603. Scene.prototype._checkIntersections = function () {
  27604. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27605. var sourceMesh = this._meshesForIntersections.data[index];
  27606. if (!sourceMesh.actionManager) {
  27607. continue;
  27608. }
  27609. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27610. var action = sourceMesh.actionManager.actions[actionIndex];
  27611. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27612. var parameters = action.getTriggerParameter();
  27613. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27614. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27615. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27616. if (areIntersecting && currentIntersectionInProgress === -1) {
  27617. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27618. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27619. sourceMesh._intersectionsInProgress.push(otherMesh);
  27620. }
  27621. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27622. sourceMesh._intersectionsInProgress.push(otherMesh);
  27623. }
  27624. }
  27625. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27626. //They intersected, and now they don't.
  27627. //is this trigger an exit trigger? execute an event.
  27628. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27629. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27630. }
  27631. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27632. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27633. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27634. return otherMesh === parameterMesh;
  27635. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27636. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27637. }
  27638. }
  27639. }
  27640. }
  27641. }
  27642. };
  27643. /**
  27644. * Render the scene
  27645. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27646. */
  27647. Scene.prototype.render = function (updateCameras) {
  27648. if (updateCameras === void 0) { updateCameras = true; }
  27649. if (this.isDisposed) {
  27650. return;
  27651. }
  27652. // Register components that have been associated lately to the scene.
  27653. this._registerTransientComponents();
  27654. this._activeParticles.fetchNewFrame();
  27655. this._totalVertices.fetchNewFrame();
  27656. this._activeIndices.fetchNewFrame();
  27657. this._activeBones.fetchNewFrame();
  27658. this._meshesForIntersections.reset();
  27659. this.resetCachedMaterial();
  27660. this.onBeforeAnimationsObservable.notifyObservers(this);
  27661. // Actions
  27662. if (this.actionManager) {
  27663. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27664. }
  27665. if (this._engine.isDeterministicLockStep()) {
  27666. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27667. var defaultFPS = (60.0 / 1000.0);
  27668. var defaultFrameTime = 1000 / 60; // frame time in MS
  27669. if (this._physicsEngine) {
  27670. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27671. }
  27672. var stepsTaken = 0;
  27673. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27674. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27675. internalSteps = Math.min(internalSteps, maxSubSteps);
  27676. do {
  27677. this.onBeforeStepObservable.notifyObservers(this);
  27678. // Animations
  27679. this._animationRatio = defaultFrameTime * defaultFPS;
  27680. this._animate();
  27681. this.onAfterAnimationsObservable.notifyObservers(this);
  27682. // Physics
  27683. if (this._physicsEngine) {
  27684. this.onBeforePhysicsObservable.notifyObservers(this);
  27685. this._physicsEngine._step(defaultFrameTime / 1000);
  27686. this.onAfterPhysicsObservable.notifyObservers(this);
  27687. }
  27688. this.onAfterStepObservable.notifyObservers(this);
  27689. this._currentStepId++;
  27690. stepsTaken++;
  27691. deltaTime -= defaultFrameTime;
  27692. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27693. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27694. }
  27695. else {
  27696. // Animations
  27697. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27698. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27699. this._animate();
  27700. this.onAfterAnimationsObservable.notifyObservers(this);
  27701. // Physics
  27702. if (this._physicsEngine) {
  27703. this.onBeforePhysicsObservable.notifyObservers(this);
  27704. this._physicsEngine._step(deltaTime / 1000.0);
  27705. this.onAfterPhysicsObservable.notifyObservers(this);
  27706. }
  27707. }
  27708. // Before camera update steps
  27709. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27710. var step = _a[_i];
  27711. step.action();
  27712. }
  27713. // Update Cameras
  27714. if (updateCameras) {
  27715. if (this.activeCameras.length > 0) {
  27716. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27717. var camera = this.activeCameras[cameraIndex];
  27718. camera.update();
  27719. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27720. // rig cameras
  27721. for (var index = 0; index < camera._rigCameras.length; index++) {
  27722. camera._rigCameras[index].update();
  27723. }
  27724. }
  27725. }
  27726. }
  27727. else if (this.activeCamera) {
  27728. this.activeCamera.update();
  27729. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27730. // rig cameras
  27731. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27732. this.activeCamera._rigCameras[index].update();
  27733. }
  27734. }
  27735. }
  27736. }
  27737. // Before render
  27738. this.onBeforeRenderObservable.notifyObservers(this);
  27739. // Customs render targets
  27740. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27741. var engine = this.getEngine();
  27742. var currentActiveCamera = this.activeCamera;
  27743. if (this.renderTargetsEnabled) {
  27744. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27745. this._intermediateRendering = true;
  27746. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27747. var renderTarget = this.customRenderTargets[customIndex];
  27748. if (renderTarget._shouldRender()) {
  27749. this._renderId++;
  27750. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27751. if (!this.activeCamera)
  27752. throw new Error("Active camera not set");
  27753. // Viewport
  27754. engine.setViewport(this.activeCamera.viewport);
  27755. // Camera
  27756. this.updateTransformMatrix();
  27757. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27758. }
  27759. }
  27760. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27761. this._intermediateRendering = false;
  27762. this._renderId++;
  27763. }
  27764. // Restore back buffer
  27765. if (this.customRenderTargets.length > 0) {
  27766. engine.restoreDefaultFramebuffer();
  27767. }
  27768. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27769. this.activeCamera = currentActiveCamera;
  27770. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  27771. var step = _c[_b];
  27772. step.action();
  27773. }
  27774. // Clear
  27775. if (this.autoClearDepthAndStencil || this.autoClear) {
  27776. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27777. }
  27778. // Collects render targets from external components.
  27779. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  27780. var step = _e[_d];
  27781. step.action(this._renderTargets);
  27782. }
  27783. // Multi-cameras?
  27784. if (this.activeCameras.length > 0) {
  27785. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27786. if (cameraIndex > 0) {
  27787. this._engine.clear(null, false, true, true);
  27788. }
  27789. this._processSubCameras(this.activeCameras[cameraIndex]);
  27790. }
  27791. }
  27792. else {
  27793. if (!this.activeCamera) {
  27794. throw new Error("No camera defined");
  27795. }
  27796. this._processSubCameras(this.activeCamera);
  27797. }
  27798. // Intersection checks
  27799. this._checkIntersections();
  27800. // Update the audio listener attached to the camera
  27801. if (BABYLON.AudioEngine) {
  27802. this._updateAudioParameters();
  27803. }
  27804. // After render
  27805. if (this.afterRender) {
  27806. this.afterRender();
  27807. }
  27808. this.onAfterRenderObservable.notifyObservers(this);
  27809. // Cleaning
  27810. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27811. var data = this._toBeDisposed.data[index];
  27812. if (data) {
  27813. data.dispose();
  27814. }
  27815. this._toBeDisposed[index] = null;
  27816. }
  27817. this._toBeDisposed.reset();
  27818. if (this.dumpNextRenderTargets) {
  27819. this.dumpNextRenderTargets = false;
  27820. }
  27821. this._activeBones.addCount(0, true);
  27822. this._activeIndices.addCount(0, true);
  27823. this._activeParticles.addCount(0, true);
  27824. };
  27825. Scene.prototype._updateAudioParameters = function () {
  27826. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27827. return;
  27828. }
  27829. var listeningCamera;
  27830. var audioEngine = BABYLON.Engine.audioEngine;
  27831. if (this.activeCameras.length > 0) {
  27832. listeningCamera = this.activeCameras[0];
  27833. }
  27834. else {
  27835. listeningCamera = this.activeCamera;
  27836. }
  27837. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27838. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27839. // for VR cameras
  27840. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27841. listeningCamera = listeningCamera.rigCameras[0];
  27842. }
  27843. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27844. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27845. cameraDirection.normalize();
  27846. // To avoid some errors on GearVR
  27847. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27848. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27849. }
  27850. var i;
  27851. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27852. var sound = this.mainSoundTrack.soundCollection[i];
  27853. if (sound.useCustomAttenuation) {
  27854. sound.updateDistanceFromListener();
  27855. }
  27856. }
  27857. for (i = 0; i < this.soundTracks.length; i++) {
  27858. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27859. sound = this.soundTracks[i].soundCollection[j];
  27860. if (sound.useCustomAttenuation) {
  27861. sound.updateDistanceFromListener();
  27862. }
  27863. }
  27864. }
  27865. }
  27866. };
  27867. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27868. // Audio
  27869. /**
  27870. * Gets or sets if audio support is enabled
  27871. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27872. */
  27873. get: function () {
  27874. return this._audioEnabled;
  27875. },
  27876. set: function (value) {
  27877. this._audioEnabled = value;
  27878. if (BABYLON.AudioEngine) {
  27879. if (this._audioEnabled) {
  27880. this._enableAudio();
  27881. }
  27882. else {
  27883. this._disableAudio();
  27884. }
  27885. }
  27886. },
  27887. enumerable: true,
  27888. configurable: true
  27889. });
  27890. Scene.prototype._disableAudio = function () {
  27891. var i;
  27892. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27893. this.mainSoundTrack.soundCollection[i].pause();
  27894. }
  27895. for (i = 0; i < this.soundTracks.length; i++) {
  27896. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27897. this.soundTracks[i].soundCollection[j].pause();
  27898. }
  27899. }
  27900. };
  27901. Scene.prototype._enableAudio = function () {
  27902. var i;
  27903. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27904. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27905. this.mainSoundTrack.soundCollection[i].play();
  27906. }
  27907. }
  27908. for (i = 0; i < this.soundTracks.length; i++) {
  27909. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27910. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27911. this.soundTracks[i].soundCollection[j].play();
  27912. }
  27913. }
  27914. }
  27915. };
  27916. Object.defineProperty(Scene.prototype, "headphone", {
  27917. /**
  27918. * Gets or sets if audio will be output to headphones
  27919. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27920. */
  27921. get: function () {
  27922. return this._headphone;
  27923. },
  27924. set: function (value) {
  27925. this._headphone = value;
  27926. if (BABYLON.AudioEngine) {
  27927. if (this._headphone) {
  27928. this._switchAudioModeForHeadphones();
  27929. }
  27930. else {
  27931. this._switchAudioModeForNormalSpeakers();
  27932. }
  27933. }
  27934. },
  27935. enumerable: true,
  27936. configurable: true
  27937. });
  27938. Scene.prototype._switchAudioModeForHeadphones = function () {
  27939. this.mainSoundTrack.switchPanningModelToHRTF();
  27940. for (var i = 0; i < this.soundTracks.length; i++) {
  27941. this.soundTracks[i].switchPanningModelToHRTF();
  27942. }
  27943. };
  27944. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27945. this.mainSoundTrack.switchPanningModelToEqualPower();
  27946. for (var i = 0; i < this.soundTracks.length; i++) {
  27947. this.soundTracks[i].switchPanningModelToEqualPower();
  27948. }
  27949. };
  27950. /**
  27951. * Freeze all materials
  27952. * A frozen material will not be updatable but should be faster to render
  27953. */
  27954. Scene.prototype.freezeMaterials = function () {
  27955. for (var i = 0; i < this.materials.length; i++) {
  27956. this.materials[i].freeze();
  27957. }
  27958. };
  27959. /**
  27960. * Unfreeze all materials
  27961. * A frozen material will not be updatable but should be faster to render
  27962. */
  27963. Scene.prototype.unfreezeMaterials = function () {
  27964. for (var i = 0; i < this.materials.length; i++) {
  27965. this.materials[i].unfreeze();
  27966. }
  27967. };
  27968. /**
  27969. * Releases all held ressources
  27970. */
  27971. Scene.prototype.dispose = function () {
  27972. this.beforeRender = null;
  27973. this.afterRender = null;
  27974. this.skeletons = [];
  27975. this.morphTargetManagers = [];
  27976. this._transientComponents = [];
  27977. this._isReadyForMeshStage.clear();
  27978. this._beforeEvaluateActiveMeshStage.clear();
  27979. this._evaluateSubMeshStage.clear();
  27980. this._activeMeshStage.clear();
  27981. this._cameraDrawRenderTargetStage.clear();
  27982. this._beforeCameraDrawStage.clear();
  27983. this._beforeRenderingGroupDrawStage.clear();
  27984. this._beforeRenderingMeshStage.clear();
  27985. this._afterRenderingMeshStage.clear();
  27986. this._afterRenderingGroupDrawStage.clear();
  27987. this._afterCameraDrawStage.clear();
  27988. this._beforeCameraUpdateStage.clear();
  27989. this._beforeClearStage.clear();
  27990. this._gatherRenderTargetsStage.clear();
  27991. this._rebuildGeometryStage.clear();
  27992. this._pointerMoveStage.clear();
  27993. this._pointerDownStage.clear();
  27994. this._pointerUpStage.clear();
  27995. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27996. var component = _a[_i];
  27997. component.dispose();
  27998. }
  27999. this.importedMeshesFiles = new Array();
  28000. this.stopAllAnimations();
  28001. this.resetCachedMaterial();
  28002. // Smart arrays
  28003. if (this.activeCamera) {
  28004. this.activeCamera._activeMeshes.dispose();
  28005. this.activeCamera = null;
  28006. }
  28007. this._activeMeshes.dispose();
  28008. this._renderingManager.dispose();
  28009. this._processedMaterials.dispose();
  28010. this._activeParticleSystems.dispose();
  28011. this._activeSkeletons.dispose();
  28012. this._softwareSkinnedMeshes.dispose();
  28013. this._renderTargets.dispose();
  28014. this._registeredForLateAnimationBindings.dispose();
  28015. this._meshesForIntersections.dispose();
  28016. this._toBeDisposed.dispose();
  28017. // Abort active requests
  28018. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28019. var request = _c[_b];
  28020. request.abort();
  28021. }
  28022. // Debug layer
  28023. if (this._debugLayer) {
  28024. this._debugLayer.hide();
  28025. }
  28026. // Events
  28027. this.onDisposeObservable.notifyObservers(this);
  28028. this.onDisposeObservable.clear();
  28029. this.onBeforeRenderObservable.clear();
  28030. this.onAfterRenderObservable.clear();
  28031. this.onBeforeRenderTargetsRenderObservable.clear();
  28032. this.onAfterRenderTargetsRenderObservable.clear();
  28033. this.onAfterStepObservable.clear();
  28034. this.onBeforeStepObservable.clear();
  28035. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28036. this.onAfterActiveMeshesEvaluationObservable.clear();
  28037. this.onBeforeParticlesRenderingObservable.clear();
  28038. this.onAfterParticlesRenderingObservable.clear();
  28039. this.onBeforeDrawPhaseObservable.clear();
  28040. this.onAfterDrawPhaseObservable.clear();
  28041. this.onBeforePhysicsObservable.clear();
  28042. this.onAfterPhysicsObservable.clear();
  28043. this.onBeforeAnimationsObservable.clear();
  28044. this.onAfterAnimationsObservable.clear();
  28045. this.onDataLoadedObservable.clear();
  28046. this.onBeforeRenderingGroupObservable.clear();
  28047. this.onAfterRenderingGroupObservable.clear();
  28048. this.detachControl();
  28049. // Release sounds & sounds tracks
  28050. if (BABYLON.AudioEngine) {
  28051. this.disposeSounds();
  28052. }
  28053. // VR Helper
  28054. if (this.VRHelper) {
  28055. this.VRHelper.dispose();
  28056. }
  28057. // Detach cameras
  28058. var canvas = this._engine.getRenderingCanvas();
  28059. if (canvas) {
  28060. var index;
  28061. for (index = 0; index < this.cameras.length; index++) {
  28062. this.cameras[index].detachControl(canvas);
  28063. }
  28064. }
  28065. // Release animation groups
  28066. while (this.animationGroups.length) {
  28067. this.animationGroups[0].dispose();
  28068. }
  28069. // Release lights
  28070. while (this.lights.length) {
  28071. this.lights[0].dispose();
  28072. }
  28073. // Release meshes
  28074. while (this.meshes.length) {
  28075. this.meshes[0].dispose(true);
  28076. }
  28077. while (this.transformNodes.length) {
  28078. this.removeTransformNode(this.transformNodes[0]);
  28079. }
  28080. // Release cameras
  28081. while (this.cameras.length) {
  28082. this.cameras[0].dispose();
  28083. }
  28084. // Release materials
  28085. if (this.defaultMaterial) {
  28086. this.defaultMaterial.dispose();
  28087. }
  28088. while (this.multiMaterials.length) {
  28089. this.multiMaterials[0].dispose();
  28090. }
  28091. while (this.materials.length) {
  28092. this.materials[0].dispose();
  28093. }
  28094. // Release particles
  28095. while (this.particleSystems.length) {
  28096. this.particleSystems[0].dispose();
  28097. }
  28098. // Release postProcesses
  28099. while (this.postProcesses.length) {
  28100. this.postProcesses[0].dispose();
  28101. }
  28102. // Release textures
  28103. while (this.textures.length) {
  28104. this.textures[0].dispose();
  28105. }
  28106. // Release UBO
  28107. this._sceneUbo.dispose();
  28108. if (this._alternateSceneUbo) {
  28109. this._alternateSceneUbo.dispose();
  28110. }
  28111. // Post-processes
  28112. this.postProcessManager.dispose();
  28113. // Physics
  28114. if (this._physicsEngine) {
  28115. this.disablePhysicsEngine();
  28116. }
  28117. // Remove from engine
  28118. index = this._engine.scenes.indexOf(this);
  28119. if (index > -1) {
  28120. this._engine.scenes.splice(index, 1);
  28121. }
  28122. this._engine.wipeCaches(true);
  28123. this._isDisposed = true;
  28124. };
  28125. Object.defineProperty(Scene.prototype, "isDisposed", {
  28126. /**
  28127. * Gets if the scene is already disposed
  28128. */
  28129. get: function () {
  28130. return this._isDisposed;
  28131. },
  28132. enumerable: true,
  28133. configurable: true
  28134. });
  28135. /**
  28136. * Releases sounds & soundtracks
  28137. */
  28138. Scene.prototype.disposeSounds = function () {
  28139. if (!this._mainSoundTrack) {
  28140. return;
  28141. }
  28142. this.mainSoundTrack.dispose();
  28143. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28144. this.soundTracks[scIndex].dispose();
  28145. }
  28146. };
  28147. /**
  28148. * Call this function to reduce memory footprint of the scene.
  28149. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28150. */
  28151. Scene.prototype.clearCachedVertexData = function () {
  28152. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28153. var mesh = this.meshes[meshIndex];
  28154. var geometry = mesh.geometry;
  28155. if (geometry) {
  28156. geometry._indices = [];
  28157. for (var vbName in geometry._vertexBuffers) {
  28158. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28159. continue;
  28160. }
  28161. geometry._vertexBuffers[vbName]._buffer._data = null;
  28162. }
  28163. }
  28164. }
  28165. };
  28166. /**
  28167. * This function will remove the local cached buffer data from texture.
  28168. * It will save memory but will prevent the texture from being rebuilt
  28169. */
  28170. Scene.prototype.cleanCachedTextureBuffer = function () {
  28171. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28172. var baseTexture = _a[_i];
  28173. var buffer = baseTexture._buffer;
  28174. if (buffer) {
  28175. baseTexture._buffer = null;
  28176. }
  28177. }
  28178. };
  28179. // Octrees
  28180. /**
  28181. * Get the world extend vectors with an optional filter
  28182. *
  28183. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28184. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28185. */
  28186. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28187. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28188. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28189. filterPredicate = filterPredicate || (function () { return true; });
  28190. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28191. mesh.computeWorldMatrix(true);
  28192. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28193. return;
  28194. }
  28195. var boundingInfo = mesh.getBoundingInfo();
  28196. var minBox = boundingInfo.boundingBox.minimumWorld;
  28197. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28198. BABYLON.Tools.CheckExtends(minBox, min, max);
  28199. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28200. });
  28201. return {
  28202. min: min,
  28203. max: max
  28204. };
  28205. };
  28206. /**
  28207. * Creates or updates the octree used to boost selection (picking)
  28208. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28209. * @param maxCapacity defines the maximum capacity per leaf
  28210. * @param maxDepth defines the maximum depth of the octree
  28211. * @returns an octree of AbstractMesh
  28212. */
  28213. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28214. if (maxCapacity === void 0) { maxCapacity = 64; }
  28215. if (maxDepth === void 0) { maxDepth = 2; }
  28216. if (!this._selectionOctree) {
  28217. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28218. }
  28219. var worldExtends = this.getWorldExtends();
  28220. // Update octree
  28221. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28222. return this._selectionOctree;
  28223. };
  28224. // Picking
  28225. /**
  28226. * Creates a ray that can be used to pick in the scene
  28227. * @param x defines the x coordinate of the origin (on-screen)
  28228. * @param y defines the y coordinate of the origin (on-screen)
  28229. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28230. * @param camera defines the camera to use for the picking
  28231. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28232. * @returns a Ray
  28233. */
  28234. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28235. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28236. var result = BABYLON.Ray.Zero();
  28237. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28238. return result;
  28239. };
  28240. /**
  28241. * Creates a ray that can be used to pick in the scene
  28242. * @param x defines the x coordinate of the origin (on-screen)
  28243. * @param y defines the y coordinate of the origin (on-screen)
  28244. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28245. * @param result defines the ray where to store the picking ray
  28246. * @param camera defines the camera to use for the picking
  28247. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28248. * @returns the current scene
  28249. */
  28250. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28251. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28252. var engine = this._engine;
  28253. if (!camera) {
  28254. if (!this.activeCamera)
  28255. throw new Error("Active camera not set");
  28256. camera = this.activeCamera;
  28257. }
  28258. var cameraViewport = camera.viewport;
  28259. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28260. // Moving coordinates to local viewport world
  28261. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28262. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28263. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28264. return this;
  28265. };
  28266. /**
  28267. * Creates a ray that can be used to pick in the scene
  28268. * @param x defines the x coordinate of the origin (on-screen)
  28269. * @param y defines the y coordinate of the origin (on-screen)
  28270. * @param camera defines the camera to use for the picking
  28271. * @returns a Ray
  28272. */
  28273. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28274. var result = BABYLON.Ray.Zero();
  28275. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28276. return result;
  28277. };
  28278. /**
  28279. * Creates a ray that can be used to pick in the scene
  28280. * @param x defines the x coordinate of the origin (on-screen)
  28281. * @param y defines the y coordinate of the origin (on-screen)
  28282. * @param result defines the ray where to store the picking ray
  28283. * @param camera defines the camera to use for the picking
  28284. * @returns the current scene
  28285. */
  28286. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28287. if (!BABYLON.PickingInfo) {
  28288. return this;
  28289. }
  28290. var engine = this._engine;
  28291. if (!camera) {
  28292. if (!this.activeCamera)
  28293. throw new Error("Active camera not set");
  28294. camera = this.activeCamera;
  28295. }
  28296. var cameraViewport = camera.viewport;
  28297. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28298. var identity = BABYLON.Matrix.Identity();
  28299. // Moving coordinates to local viewport world
  28300. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28301. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28302. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28303. return this;
  28304. };
  28305. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28306. if (!BABYLON.PickingInfo) {
  28307. return null;
  28308. }
  28309. var pickingInfo = null;
  28310. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28311. var mesh = this.meshes[meshIndex];
  28312. if (predicate) {
  28313. if (!predicate(mesh)) {
  28314. continue;
  28315. }
  28316. }
  28317. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28318. continue;
  28319. }
  28320. var world = mesh.getWorldMatrix();
  28321. var ray = rayFunction(world);
  28322. var result = mesh.intersects(ray, fastCheck);
  28323. if (!result || !result.hit)
  28324. continue;
  28325. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28326. continue;
  28327. pickingInfo = result;
  28328. if (fastCheck) {
  28329. break;
  28330. }
  28331. }
  28332. return pickingInfo || new BABYLON.PickingInfo();
  28333. };
  28334. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28335. if (!BABYLON.PickingInfo) {
  28336. return null;
  28337. }
  28338. var pickingInfos = new Array();
  28339. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28340. var mesh = this.meshes[meshIndex];
  28341. if (predicate) {
  28342. if (!predicate(mesh)) {
  28343. continue;
  28344. }
  28345. }
  28346. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28347. continue;
  28348. }
  28349. var world = mesh.getWorldMatrix();
  28350. var ray = rayFunction(world);
  28351. var result = mesh.intersects(ray, false);
  28352. if (!result || !result.hit)
  28353. continue;
  28354. pickingInfos.push(result);
  28355. }
  28356. return pickingInfos;
  28357. };
  28358. /** Launch a ray to try to pick a mesh in the scene
  28359. * @param x position on screen
  28360. * @param y position on screen
  28361. * @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
  28362. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28363. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28364. * @returns a PickingInfo
  28365. */
  28366. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28367. var _this = this;
  28368. if (!BABYLON.PickingInfo) {
  28369. return null;
  28370. }
  28371. var result = this._internalPick(function (world) {
  28372. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28373. return _this._tempPickingRay;
  28374. }, predicate, fastCheck);
  28375. if (result) {
  28376. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28377. }
  28378. return result;
  28379. };
  28380. /** Use the given ray to pick a mesh in the scene
  28381. * @param ray The ray to use to pick meshes
  28382. * @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
  28383. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28384. * @returns a PickingInfo
  28385. */
  28386. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28387. var _this = this;
  28388. var result = this._internalPick(function (world) {
  28389. if (!_this._pickWithRayInverseMatrix) {
  28390. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28391. }
  28392. world.invertToRef(_this._pickWithRayInverseMatrix);
  28393. if (!_this._cachedRayForTransform) {
  28394. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28395. }
  28396. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28397. return _this._cachedRayForTransform;
  28398. }, predicate, fastCheck);
  28399. if (result) {
  28400. result.ray = ray;
  28401. }
  28402. return result;
  28403. };
  28404. /**
  28405. * Launch a ray to try to pick a mesh in the scene
  28406. * @param x X position on screen
  28407. * @param y Y position on screen
  28408. * @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
  28409. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28410. * @returns an array of PickingInfo
  28411. */
  28412. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28413. var _this = this;
  28414. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28415. };
  28416. /**
  28417. * Launch a ray to try to pick a mesh in the scene
  28418. * @param ray Ray to use
  28419. * @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
  28420. * @returns an array of PickingInfo
  28421. */
  28422. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28423. var _this = this;
  28424. return this._internalMultiPick(function (world) {
  28425. if (!_this._pickWithRayInverseMatrix) {
  28426. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28427. }
  28428. world.invertToRef(_this._pickWithRayInverseMatrix);
  28429. if (!_this._cachedRayForTransform) {
  28430. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28431. }
  28432. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28433. return _this._cachedRayForTransform;
  28434. }, predicate);
  28435. };
  28436. /**
  28437. * Force the value of meshUnderPointer
  28438. * @param mesh defines the mesh to use
  28439. */
  28440. Scene.prototype.setPointerOverMesh = function (mesh) {
  28441. if (this._pointerOverMesh === mesh) {
  28442. return;
  28443. }
  28444. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28445. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28446. }
  28447. this._pointerOverMesh = mesh;
  28448. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28449. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28450. }
  28451. };
  28452. /**
  28453. * Gets the mesh under the pointer
  28454. * @returns a Mesh or null if no mesh is under the pointer
  28455. */
  28456. Scene.prototype.getPointerOverMesh = function () {
  28457. return this._pointerOverMesh;
  28458. };
  28459. // Physics
  28460. /**
  28461. * Gets the current physics engine
  28462. * @returns a PhysicsEngine or null if none attached
  28463. */
  28464. Scene.prototype.getPhysicsEngine = function () {
  28465. return this._physicsEngine;
  28466. };
  28467. /**
  28468. * Enables physics to the current scene
  28469. * @param gravity defines the scene's gravity for the physics engine
  28470. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28471. * @return a boolean indicating if the physics engine was initialized
  28472. */
  28473. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28474. if (gravity === void 0) { gravity = null; }
  28475. if (this._physicsEngine) {
  28476. return true;
  28477. }
  28478. try {
  28479. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28480. return true;
  28481. }
  28482. catch (e) {
  28483. BABYLON.Tools.Error(e.message);
  28484. return false;
  28485. }
  28486. };
  28487. /**
  28488. * Disables and disposes the physics engine associated with the scene
  28489. */
  28490. Scene.prototype.disablePhysicsEngine = function () {
  28491. if (!this._physicsEngine) {
  28492. return;
  28493. }
  28494. this._physicsEngine.dispose();
  28495. this._physicsEngine = null;
  28496. };
  28497. /**
  28498. * Gets a boolean indicating if there is an active physics engine
  28499. * @returns a boolean indicating if there is an active physics engine
  28500. */
  28501. Scene.prototype.isPhysicsEnabled = function () {
  28502. return this._physicsEngine !== undefined;
  28503. };
  28504. /**
  28505. * Deletes a physics compound impostor
  28506. * @param compound defines the compound to delete
  28507. */
  28508. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28509. var mesh = compound.parts[0].mesh;
  28510. if (mesh.physicsImpostor) {
  28511. mesh.physicsImpostor.dispose( /*true*/);
  28512. mesh.physicsImpostor = null;
  28513. }
  28514. };
  28515. // Misc.
  28516. /** @hidden */
  28517. Scene.prototype._rebuildGeometries = function () {
  28518. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28519. var geometry = _a[_i];
  28520. geometry._rebuild();
  28521. }
  28522. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28523. var mesh = _c[_b];
  28524. mesh._rebuild();
  28525. }
  28526. if (this.postProcessManager) {
  28527. this.postProcessManager._rebuild();
  28528. }
  28529. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28530. var component = _e[_d];
  28531. component.rebuild();
  28532. }
  28533. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28534. var system = _g[_f];
  28535. system.rebuild();
  28536. }
  28537. for (var _h = 0, _j = this._rebuildGeometryStage; _h < _j.length; _h++) {
  28538. var step = _j[_h];
  28539. step.action();
  28540. }
  28541. };
  28542. /** @hidden */
  28543. Scene.prototype._rebuildTextures = function () {
  28544. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28545. var texture = _a[_i];
  28546. texture._rebuild();
  28547. }
  28548. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28549. };
  28550. /**
  28551. * Creates a default light for the scene.
  28552. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28553. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28554. */
  28555. Scene.prototype.createDefaultLight = function (replace) {
  28556. if (replace === void 0) { replace = false; }
  28557. // Dispose existing light in replace mode.
  28558. if (replace) {
  28559. if (this.lights) {
  28560. for (var i = 0; i < this.lights.length; i++) {
  28561. this.lights[i].dispose();
  28562. }
  28563. }
  28564. }
  28565. // Light
  28566. if (this.lights.length === 0) {
  28567. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28568. }
  28569. };
  28570. /**
  28571. * Creates a default camera for the scene.
  28572. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28573. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28574. * @param replace has default false, when true replaces the active camera in the scene
  28575. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28576. */
  28577. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28578. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28579. if (replace === void 0) { replace = false; }
  28580. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28581. // Dispose existing camera in replace mode.
  28582. if (replace) {
  28583. if (this.activeCamera) {
  28584. this.activeCamera.dispose();
  28585. this.activeCamera = null;
  28586. }
  28587. }
  28588. // Camera
  28589. if (!this.activeCamera) {
  28590. var worldExtends = this.getWorldExtends();
  28591. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28592. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28593. var camera;
  28594. var radius = worldSize.length() * 1.5;
  28595. // empty scene scenario!
  28596. if (!isFinite(radius)) {
  28597. radius = 1;
  28598. worldCenter.copyFromFloats(0, 0, 0);
  28599. }
  28600. if (createArcRotateCamera) {
  28601. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28602. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28603. arcRotateCamera.wheelPrecision = 100 / radius;
  28604. camera = arcRotateCamera;
  28605. }
  28606. else {
  28607. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28608. freeCamera.setTarget(worldCenter);
  28609. camera = freeCamera;
  28610. }
  28611. camera.minZ = radius * 0.01;
  28612. camera.maxZ = radius * 1000;
  28613. camera.speed = radius * 0.2;
  28614. this.activeCamera = camera;
  28615. var canvas = this.getEngine().getRenderingCanvas();
  28616. if (attachCameraControls && canvas) {
  28617. camera.attachControl(canvas);
  28618. }
  28619. }
  28620. };
  28621. /**
  28622. * Creates a default camera and a default light.
  28623. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28624. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28625. * @param replace has the default false, when true replaces the active camera/light in the scene
  28626. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28627. */
  28628. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28629. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28630. if (replace === void 0) { replace = false; }
  28631. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28632. this.createDefaultLight(replace);
  28633. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28634. };
  28635. /**
  28636. * Creates a new sky box
  28637. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28638. * @param environmentTexture defines the texture to use as environment texture
  28639. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28640. * @param scale defines the overall scale of the skybox
  28641. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28642. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28643. * @returns a new mesh holding the sky box
  28644. */
  28645. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28646. if (pbr === void 0) { pbr = false; }
  28647. if (scale === void 0) { scale = 1000; }
  28648. if (blur === void 0) { blur = 0; }
  28649. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28650. if (!environmentTexture) {
  28651. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28652. return null;
  28653. }
  28654. if (setGlobalEnvTexture) {
  28655. if (environmentTexture) {
  28656. this.environmentTexture = environmentTexture;
  28657. }
  28658. }
  28659. // Skybox
  28660. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28661. if (pbr) {
  28662. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28663. hdrSkyboxMaterial.backFaceCulling = false;
  28664. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28665. if (hdrSkyboxMaterial.reflectionTexture) {
  28666. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28667. }
  28668. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28669. hdrSkyboxMaterial.disableLighting = true;
  28670. hdrSkyboxMaterial.twoSidedLighting = true;
  28671. hdrSkybox.infiniteDistance = true;
  28672. hdrSkybox.material = hdrSkyboxMaterial;
  28673. }
  28674. else {
  28675. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28676. skyboxMaterial.backFaceCulling = false;
  28677. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28678. if (skyboxMaterial.reflectionTexture) {
  28679. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28680. }
  28681. skyboxMaterial.disableLighting = true;
  28682. hdrSkybox.infiniteDistance = true;
  28683. hdrSkybox.material = skyboxMaterial;
  28684. }
  28685. return hdrSkybox;
  28686. };
  28687. /**
  28688. * Creates a new environment
  28689. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28690. * @param options defines the options you can use to configure the environment
  28691. * @returns the new EnvironmentHelper
  28692. */
  28693. Scene.prototype.createDefaultEnvironment = function (options) {
  28694. if (BABYLON.EnvironmentHelper) {
  28695. return new BABYLON.EnvironmentHelper(options, this);
  28696. }
  28697. return null;
  28698. };
  28699. /**
  28700. * Creates a new VREXperienceHelper
  28701. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28702. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28703. * @returns a new VREXperienceHelper
  28704. */
  28705. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28706. if (webVROptions === void 0) { webVROptions = {}; }
  28707. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28708. };
  28709. // Tags
  28710. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28711. if (tagsQuery === undefined) {
  28712. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28713. return list;
  28714. }
  28715. var listByTags = [];
  28716. forEach = forEach || (function (item) { return; });
  28717. for (var i in list) {
  28718. var item = list[i];
  28719. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28720. listByTags.push(item);
  28721. forEach(item);
  28722. }
  28723. }
  28724. return listByTags;
  28725. };
  28726. /**
  28727. * Get a list of meshes by tags
  28728. * @param tagsQuery defines the tags query to use
  28729. * @param forEach defines a predicate used to filter results
  28730. * @returns an array of Mesh
  28731. */
  28732. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28733. return this._getByTags(this.meshes, tagsQuery, forEach);
  28734. };
  28735. /**
  28736. * Get a list of cameras by tags
  28737. * @param tagsQuery defines the tags query to use
  28738. * @param forEach defines a predicate used to filter results
  28739. * @returns an array of Camera
  28740. */
  28741. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28742. return this._getByTags(this.cameras, tagsQuery, forEach);
  28743. };
  28744. /**
  28745. * Get a list of lights by tags
  28746. * @param tagsQuery defines the tags query to use
  28747. * @param forEach defines a predicate used to filter results
  28748. * @returns an array of Light
  28749. */
  28750. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28751. return this._getByTags(this.lights, tagsQuery, forEach);
  28752. };
  28753. /**
  28754. * Get a list of materials by tags
  28755. * @param tagsQuery defines the tags query to use
  28756. * @param forEach defines a predicate used to filter results
  28757. * @returns an array of Material
  28758. */
  28759. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28760. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28761. };
  28762. /**
  28763. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28764. * This allowed control for front to back rendering or reversly depending of the special needs.
  28765. *
  28766. * @param renderingGroupId The rendering group id corresponding to its index
  28767. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28768. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28769. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28770. */
  28771. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28772. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28773. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28774. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28775. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28776. };
  28777. /**
  28778. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28779. *
  28780. * @param renderingGroupId The rendering group id corresponding to its index
  28781. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28782. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28783. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28784. */
  28785. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28786. if (depth === void 0) { depth = true; }
  28787. if (stencil === void 0) { stencil = true; }
  28788. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28789. };
  28790. /**
  28791. * Gets the current auto clear configuration for one rendering group of the rendering
  28792. * manager.
  28793. * @param index the rendering group index to get the information for
  28794. * @returns The auto clear setup for the requested rendering group
  28795. */
  28796. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28797. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28798. };
  28799. /**
  28800. * Will flag all materials as dirty to trigger new shader compilation
  28801. * @param flag defines the flag used to specify which material part must be marked as dirty
  28802. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28803. */
  28804. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28805. if (this.blockMaterialDirtyMechanism) {
  28806. return;
  28807. }
  28808. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28809. var material = _a[_i];
  28810. if (predicate && !predicate(material)) {
  28811. continue;
  28812. }
  28813. material.markAsDirty(flag);
  28814. }
  28815. };
  28816. /** @hidden */
  28817. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28818. var _this = this;
  28819. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28820. this._activeRequests.push(request);
  28821. request.onCompleteObservable.add(function (request) {
  28822. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28823. });
  28824. return request;
  28825. };
  28826. /** @hidden */
  28827. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28828. var _this = this;
  28829. return new Promise(function (resolve, reject) {
  28830. _this._loadFile(url, function (data) {
  28831. resolve(data);
  28832. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28833. reject(exception);
  28834. });
  28835. });
  28836. };
  28837. // Statics
  28838. Scene._uniqueIdCounter = 0;
  28839. /** The fog is deactivated */
  28840. Scene.FOGMODE_NONE = 0;
  28841. /** The fog density is following an exponential function */
  28842. Scene.FOGMODE_EXP = 1;
  28843. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28844. Scene.FOGMODE_EXP2 = 2;
  28845. /** The fog density is following a linear function. */
  28846. Scene.FOGMODE_LINEAR = 3;
  28847. /**
  28848. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28849. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28850. */
  28851. Scene.MinDeltaTime = 1.0;
  28852. /**
  28853. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28854. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28855. */
  28856. Scene.MaxDeltaTime = 1000.0;
  28857. /** The distance in pixel that you have to move to prevent some events */
  28858. Scene.DragMovementThreshold = 10; // in pixels
  28859. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28860. Scene.LongPressDelay = 500; // in milliseconds
  28861. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28862. Scene.DoubleClickDelay = 300; // in milliseconds
  28863. /** If you need to check double click without raising a single click at first click, enable this flag */
  28864. Scene.ExclusiveDoubleClickMode = false;
  28865. return Scene;
  28866. }(BABYLON.AbstractScene));
  28867. BABYLON.Scene = Scene;
  28868. })(BABYLON || (BABYLON = {}));
  28869. //# sourceMappingURL=babylon.scene.js.map
  28870. var BABYLON;
  28871. (function (BABYLON) {
  28872. /**
  28873. * Set of assets to keep when moving a scene into an asset container.
  28874. */
  28875. var KeepAssets = /** @class */ (function (_super) {
  28876. __extends(KeepAssets, _super);
  28877. function KeepAssets() {
  28878. return _super !== null && _super.apply(this, arguments) || this;
  28879. }
  28880. return KeepAssets;
  28881. }(BABYLON.AbstractScene));
  28882. BABYLON.KeepAssets = KeepAssets;
  28883. /**
  28884. * Container with a set of assets that can be added or removed from a scene.
  28885. */
  28886. var AssetContainer = /** @class */ (function (_super) {
  28887. __extends(AssetContainer, _super);
  28888. /**
  28889. * Instantiates an AssetContainer.
  28890. * @param scene The scene the AssetContainer belongs to.
  28891. */
  28892. function AssetContainer(scene) {
  28893. var _this = _super.call(this) || this;
  28894. _this.scene = scene;
  28895. return _this;
  28896. }
  28897. /**
  28898. * Adds all the assets from the container to the scene.
  28899. */
  28900. AssetContainer.prototype.addAllToScene = function () {
  28901. var _this = this;
  28902. this.cameras.forEach(function (o) {
  28903. _this.scene.addCamera(o);
  28904. });
  28905. this.lights.forEach(function (o) {
  28906. _this.scene.addLight(o);
  28907. });
  28908. this.meshes.forEach(function (o) {
  28909. _this.scene.addMesh(o);
  28910. });
  28911. this.skeletons.forEach(function (o) {
  28912. _this.scene.addSkeleton(o);
  28913. });
  28914. this.animations.forEach(function (o) {
  28915. _this.scene.addAnimation(o);
  28916. });
  28917. this.animationGroups.forEach(function (o) {
  28918. _this.scene.addAnimationGroup(o);
  28919. });
  28920. this.multiMaterials.forEach(function (o) {
  28921. _this.scene.addMultiMaterial(o);
  28922. });
  28923. this.materials.forEach(function (o) {
  28924. _this.scene.addMaterial(o);
  28925. });
  28926. this.morphTargetManagers.forEach(function (o) {
  28927. _this.scene.addMorphTargetManager(o);
  28928. });
  28929. this.geometries.forEach(function (o) {
  28930. _this.scene.addGeometry(o);
  28931. });
  28932. this.transformNodes.forEach(function (o) {
  28933. _this.scene.addTransformNode(o);
  28934. });
  28935. this.actionManagers.forEach(function (o) {
  28936. _this.scene.addActionManager(o);
  28937. });
  28938. this.sounds.forEach(function (o) {
  28939. o.play();
  28940. o.autoplay = true;
  28941. _this.scene.mainSoundTrack.AddSound(o);
  28942. });
  28943. this.textures.forEach(function (o) {
  28944. _this.scene.addTexture(o);
  28945. });
  28946. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28947. var component = _a[_i];
  28948. component.addFromContainer(this.scene);
  28949. }
  28950. };
  28951. /**
  28952. * Removes all the assets in the container from the scene
  28953. */
  28954. AssetContainer.prototype.removeAllFromScene = function () {
  28955. var _this = this;
  28956. this.cameras.forEach(function (o) {
  28957. _this.scene.removeCamera(o);
  28958. });
  28959. this.lights.forEach(function (o) {
  28960. _this.scene.removeLight(o);
  28961. });
  28962. this.meshes.forEach(function (o) {
  28963. _this.scene.removeMesh(o);
  28964. });
  28965. this.skeletons.forEach(function (o) {
  28966. _this.scene.removeSkeleton(o);
  28967. });
  28968. this.animations.forEach(function (o) {
  28969. _this.scene.removeAnimation(o);
  28970. });
  28971. this.animationGroups.forEach(function (o) {
  28972. _this.scene.removeAnimationGroup(o);
  28973. });
  28974. this.multiMaterials.forEach(function (o) {
  28975. _this.scene.removeMultiMaterial(o);
  28976. });
  28977. this.materials.forEach(function (o) {
  28978. _this.scene.removeMaterial(o);
  28979. });
  28980. this.morphTargetManagers.forEach(function (o) {
  28981. _this.scene.removeMorphTargetManager(o);
  28982. });
  28983. this.geometries.forEach(function (o) {
  28984. _this.scene.removeGeometry(o);
  28985. });
  28986. this.transformNodes.forEach(function (o) {
  28987. _this.scene.removeTransformNode(o);
  28988. });
  28989. this.actionManagers.forEach(function (o) {
  28990. _this.scene.removeActionManager(o);
  28991. });
  28992. this.sounds.forEach(function (o) {
  28993. o.stop();
  28994. o.autoplay = false;
  28995. _this.scene.mainSoundTrack.RemoveSound(o);
  28996. });
  28997. this.textures.forEach(function (o) {
  28998. _this.scene.removeTexture(o);
  28999. });
  29000. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29001. var component = _a[_i];
  29002. component.removeFromContainer(this.scene);
  29003. }
  29004. };
  29005. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29006. if (!sourceAssets) {
  29007. return;
  29008. }
  29009. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29010. var asset = sourceAssets_1[_i];
  29011. var move = true;
  29012. if (keepAssets) {
  29013. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29014. var keepAsset = keepAssets_1[_a];
  29015. if (asset === keepAsset) {
  29016. move = false;
  29017. break;
  29018. }
  29019. }
  29020. }
  29021. if (move) {
  29022. targetAssets.push(asset);
  29023. }
  29024. }
  29025. };
  29026. /**
  29027. * Removes all the assets contained in the scene and adds them to the container.
  29028. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29029. */
  29030. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29031. if (keepAssets === undefined) {
  29032. keepAssets = new KeepAssets();
  29033. }
  29034. for (var key in this) {
  29035. if (this.hasOwnProperty(key)) {
  29036. this[key] = this[key] || [];
  29037. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29038. }
  29039. }
  29040. this.removeAllFromScene();
  29041. };
  29042. /**
  29043. * 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.
  29044. * @returns the root mesh
  29045. */
  29046. AssetContainer.prototype.createRootMesh = function () {
  29047. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29048. this.meshes.forEach(function (m) {
  29049. if (!m.parent) {
  29050. rootMesh.addChild(m);
  29051. }
  29052. });
  29053. this.meshes.unshift(rootMesh);
  29054. return rootMesh;
  29055. };
  29056. return AssetContainer;
  29057. }(BABYLON.AbstractScene));
  29058. BABYLON.AssetContainer = AssetContainer;
  29059. })(BABYLON || (BABYLON = {}));
  29060. //# sourceMappingURL=babylon.assetContainer.js.map
  29061. var BABYLON;
  29062. (function (BABYLON) {
  29063. var Buffer = /** @class */ (function () {
  29064. /**
  29065. * Constructor
  29066. * @param engine the engine
  29067. * @param data the data to use for this buffer
  29068. * @param updatable whether the data is updatable
  29069. * @param stride the stride (optional)
  29070. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29071. * @param instanced whether the buffer is instanced (optional)
  29072. * @param useBytes set to true if the stride in in bytes (optional)
  29073. */
  29074. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29075. if (stride === void 0) { stride = 0; }
  29076. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29077. if (instanced === void 0) { instanced = false; }
  29078. if (useBytes === void 0) { useBytes = false; }
  29079. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29080. this._engine = engine.getScene().getEngine();
  29081. }
  29082. else {
  29083. this._engine = engine;
  29084. }
  29085. this._updatable = updatable;
  29086. this._instanced = instanced;
  29087. this._data = data;
  29088. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29089. if (!postponeInternalCreation) { // by default
  29090. this.create();
  29091. }
  29092. }
  29093. /**
  29094. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29095. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29096. * @param offset defines offset in the buffer (0 by default)
  29097. * @param size defines the size in floats of attributes (position is 3 for instance)
  29098. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29099. * @param instanced defines if the vertex buffer contains indexed data
  29100. * @param useBytes defines if the offset and stride are in bytes
  29101. * @returns the new vertex buffer
  29102. */
  29103. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29104. if (useBytes === void 0) { useBytes = false; }
  29105. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29106. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29107. // a lot of these parameters are ignored as they are overriden by the buffer
  29108. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29109. };
  29110. // Properties
  29111. Buffer.prototype.isUpdatable = function () {
  29112. return this._updatable;
  29113. };
  29114. Buffer.prototype.getData = function () {
  29115. return this._data;
  29116. };
  29117. Buffer.prototype.getBuffer = function () {
  29118. return this._buffer;
  29119. };
  29120. /**
  29121. * Gets the stride in float32 units (i.e. byte stride / 4).
  29122. * May not be an integer if the byte stride is not divisible by 4.
  29123. * DEPRECATED. Use byteStride instead.
  29124. * @returns the stride in float32 units
  29125. */
  29126. Buffer.prototype.getStrideSize = function () {
  29127. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29128. };
  29129. // Methods
  29130. Buffer.prototype.create = function (data) {
  29131. if (data === void 0) { data = null; }
  29132. if (!data && this._buffer) {
  29133. return; // nothing to do
  29134. }
  29135. data = data || this._data;
  29136. if (!data) {
  29137. return;
  29138. }
  29139. if (!this._buffer) { // create buffer
  29140. if (this._updatable) {
  29141. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29142. this._data = data;
  29143. }
  29144. else {
  29145. this._buffer = this._engine.createVertexBuffer(data);
  29146. }
  29147. }
  29148. else if (this._updatable) { // update buffer
  29149. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29150. this._data = data;
  29151. }
  29152. };
  29153. /** @hidden */
  29154. Buffer.prototype._rebuild = function () {
  29155. this._buffer = null;
  29156. this.create(this._data);
  29157. };
  29158. Buffer.prototype.update = function (data) {
  29159. this.create(data);
  29160. };
  29161. /**
  29162. * Updates the data directly.
  29163. * @param data the new data
  29164. * @param offset the new offset
  29165. * @param vertexCount the vertex count (optional)
  29166. * @param useBytes set to true if the offset is in bytes
  29167. */
  29168. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29169. if (useBytes === void 0) { useBytes = false; }
  29170. if (!this._buffer) {
  29171. return;
  29172. }
  29173. if (this._updatable) { // update buffer
  29174. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29175. this._data = null;
  29176. }
  29177. };
  29178. Buffer.prototype.dispose = function () {
  29179. if (!this._buffer) {
  29180. return;
  29181. }
  29182. if (this._engine._releaseBuffer(this._buffer)) {
  29183. this._buffer = null;
  29184. }
  29185. };
  29186. return Buffer;
  29187. }());
  29188. BABYLON.Buffer = Buffer;
  29189. })(BABYLON || (BABYLON = {}));
  29190. //# sourceMappingURL=babylon.buffer.js.map
  29191. var BABYLON;
  29192. (function (BABYLON) {
  29193. var VertexBuffer = /** @class */ (function () {
  29194. /**
  29195. * Constructor
  29196. * @param engine the engine
  29197. * @param data the data to use for this vertex buffer
  29198. * @param kind the vertex buffer kind
  29199. * @param updatable whether the data is updatable
  29200. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29201. * @param stride the stride (optional)
  29202. * @param instanced whether the buffer is instanced (optional)
  29203. * @param offset the offset of the data (optional)
  29204. * @param size the number of components (optional)
  29205. * @param type the type of the component (optional)
  29206. * @param normalized whether the data contains normalized data (optional)
  29207. * @param useBytes set to true if stride and offset are in bytes (optional)
  29208. */
  29209. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29210. if (normalized === void 0) { normalized = false; }
  29211. if (useBytes === void 0) { useBytes = false; }
  29212. if (data instanceof BABYLON.Buffer) {
  29213. this._buffer = data;
  29214. this._ownsBuffer = false;
  29215. }
  29216. else {
  29217. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29218. this._ownsBuffer = true;
  29219. }
  29220. this._kind = kind;
  29221. if (type == undefined) {
  29222. var data_1 = this.getData();
  29223. this.type = VertexBuffer.FLOAT;
  29224. if (data_1 instanceof Int8Array)
  29225. this.type = VertexBuffer.BYTE;
  29226. else if (data_1 instanceof Uint8Array)
  29227. this.type = VertexBuffer.UNSIGNED_BYTE;
  29228. else if (data_1 instanceof Int16Array)
  29229. this.type = VertexBuffer.SHORT;
  29230. else if (data_1 instanceof Uint16Array)
  29231. this.type = VertexBuffer.UNSIGNED_SHORT;
  29232. else if (data_1 instanceof Int32Array)
  29233. this.type = VertexBuffer.INT;
  29234. else if (data_1 instanceof Uint32Array)
  29235. this.type = VertexBuffer.UNSIGNED_INT;
  29236. }
  29237. else {
  29238. this.type = type;
  29239. }
  29240. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29241. if (useBytes) {
  29242. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29243. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29244. this.byteOffset = offset || 0;
  29245. }
  29246. else {
  29247. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29248. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29249. this.byteOffset = (offset || 0) * typeByteLength;
  29250. }
  29251. this.normalized = normalized;
  29252. this._instanced = instanced !== undefined ? instanced : false;
  29253. this._instanceDivisor = instanced ? 1 : 0;
  29254. }
  29255. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29256. /**
  29257. * Gets or sets the instance divisor when in instanced mode
  29258. */
  29259. get: function () {
  29260. return this._instanceDivisor;
  29261. },
  29262. set: function (value) {
  29263. this._instanceDivisor = value;
  29264. if (value == 0) {
  29265. this._instanced = false;
  29266. }
  29267. else {
  29268. this._instanced = true;
  29269. }
  29270. },
  29271. enumerable: true,
  29272. configurable: true
  29273. });
  29274. /** @hidden */
  29275. VertexBuffer.prototype._rebuild = function () {
  29276. if (!this._buffer) {
  29277. return;
  29278. }
  29279. this._buffer._rebuild();
  29280. };
  29281. /**
  29282. * Returns the kind of the VertexBuffer (string).
  29283. */
  29284. VertexBuffer.prototype.getKind = function () {
  29285. return this._kind;
  29286. };
  29287. // Properties
  29288. /**
  29289. * Boolean : is the VertexBuffer updatable ?
  29290. */
  29291. VertexBuffer.prototype.isUpdatable = function () {
  29292. return this._buffer.isUpdatable();
  29293. };
  29294. /**
  29295. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29296. */
  29297. VertexBuffer.prototype.getData = function () {
  29298. return this._buffer.getData();
  29299. };
  29300. /**
  29301. * Returns the WebGLBuffer associated to the VertexBuffer.
  29302. */
  29303. VertexBuffer.prototype.getBuffer = function () {
  29304. return this._buffer.getBuffer();
  29305. };
  29306. /**
  29307. * Returns the stride as a multiple of the type byte length.
  29308. * DEPRECATED. Use byteStride instead.
  29309. */
  29310. VertexBuffer.prototype.getStrideSize = function () {
  29311. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29312. };
  29313. /**
  29314. * Returns the offset as a multiple of the type byte length.
  29315. * DEPRECATED. Use byteOffset instead.
  29316. */
  29317. VertexBuffer.prototype.getOffset = function () {
  29318. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29319. };
  29320. /**
  29321. * Returns the number of components per vertex attribute (integer).
  29322. */
  29323. VertexBuffer.prototype.getSize = function () {
  29324. return this._size;
  29325. };
  29326. /**
  29327. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29328. */
  29329. VertexBuffer.prototype.getIsInstanced = function () {
  29330. return this._instanced;
  29331. };
  29332. /**
  29333. * Returns the instancing divisor, zero for non-instanced (integer).
  29334. */
  29335. VertexBuffer.prototype.getInstanceDivisor = function () {
  29336. return this._instanceDivisor;
  29337. };
  29338. // Methods
  29339. /**
  29340. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29341. * Returns the created WebGLBuffer.
  29342. */
  29343. VertexBuffer.prototype.create = function (data) {
  29344. return this._buffer.create(data);
  29345. };
  29346. /**
  29347. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29348. * This function will create a new buffer if the current one is not updatable
  29349. * Returns the updated WebGLBuffer.
  29350. */
  29351. VertexBuffer.prototype.update = function (data) {
  29352. return this._buffer.update(data);
  29353. };
  29354. /**
  29355. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29356. * Returns the directly updated WebGLBuffer.
  29357. * @param data the new data
  29358. * @param offset the new offset
  29359. * @param useBytes set to true if the offset is in bytes
  29360. */
  29361. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29362. if (useBytes === void 0) { useBytes = false; }
  29363. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29364. };
  29365. /**
  29366. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29367. */
  29368. VertexBuffer.prototype.dispose = function () {
  29369. if (this._ownsBuffer) {
  29370. this._buffer.dispose();
  29371. }
  29372. };
  29373. /**
  29374. * Enumerates each value of this vertex buffer as numbers.
  29375. * @param count the number of values to enumerate
  29376. * @param callback the callback function called for each value
  29377. */
  29378. VertexBuffer.prototype.forEach = function (count, callback) {
  29379. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29380. };
  29381. Object.defineProperty(VertexBuffer, "PositionKind", {
  29382. get: function () {
  29383. return VertexBuffer._PositionKind;
  29384. },
  29385. enumerable: true,
  29386. configurable: true
  29387. });
  29388. Object.defineProperty(VertexBuffer, "NormalKind", {
  29389. get: function () {
  29390. return VertexBuffer._NormalKind;
  29391. },
  29392. enumerable: true,
  29393. configurable: true
  29394. });
  29395. Object.defineProperty(VertexBuffer, "TangentKind", {
  29396. get: function () {
  29397. return VertexBuffer._TangentKind;
  29398. },
  29399. enumerable: true,
  29400. configurable: true
  29401. });
  29402. Object.defineProperty(VertexBuffer, "UVKind", {
  29403. get: function () {
  29404. return VertexBuffer._UVKind;
  29405. },
  29406. enumerable: true,
  29407. configurable: true
  29408. });
  29409. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29410. get: function () {
  29411. return VertexBuffer._UV2Kind;
  29412. },
  29413. enumerable: true,
  29414. configurable: true
  29415. });
  29416. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29417. get: function () {
  29418. return VertexBuffer._UV3Kind;
  29419. },
  29420. enumerable: true,
  29421. configurable: true
  29422. });
  29423. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29424. get: function () {
  29425. return VertexBuffer._UV4Kind;
  29426. },
  29427. enumerable: true,
  29428. configurable: true
  29429. });
  29430. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29431. get: function () {
  29432. return VertexBuffer._UV5Kind;
  29433. },
  29434. enumerable: true,
  29435. configurable: true
  29436. });
  29437. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29438. get: function () {
  29439. return VertexBuffer._UV6Kind;
  29440. },
  29441. enumerable: true,
  29442. configurable: true
  29443. });
  29444. Object.defineProperty(VertexBuffer, "ColorKind", {
  29445. get: function () {
  29446. return VertexBuffer._ColorKind;
  29447. },
  29448. enumerable: true,
  29449. configurable: true
  29450. });
  29451. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29452. get: function () {
  29453. return VertexBuffer._MatricesIndicesKind;
  29454. },
  29455. enumerable: true,
  29456. configurable: true
  29457. });
  29458. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29459. get: function () {
  29460. return VertexBuffer._MatricesWeightsKind;
  29461. },
  29462. enumerable: true,
  29463. configurable: true
  29464. });
  29465. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29466. get: function () {
  29467. return VertexBuffer._MatricesIndicesExtraKind;
  29468. },
  29469. enumerable: true,
  29470. configurable: true
  29471. });
  29472. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29473. get: function () {
  29474. return VertexBuffer._MatricesWeightsExtraKind;
  29475. },
  29476. enumerable: true,
  29477. configurable: true
  29478. });
  29479. /**
  29480. * Deduces the stride given a kind.
  29481. * @param kind The kind string to deduce
  29482. * @returns The deduced stride
  29483. */
  29484. VertexBuffer.DeduceStride = function (kind) {
  29485. switch (kind) {
  29486. case VertexBuffer.UVKind:
  29487. case VertexBuffer.UV2Kind:
  29488. case VertexBuffer.UV3Kind:
  29489. case VertexBuffer.UV4Kind:
  29490. case VertexBuffer.UV5Kind:
  29491. case VertexBuffer.UV6Kind:
  29492. return 2;
  29493. case VertexBuffer.NormalKind:
  29494. case VertexBuffer.PositionKind:
  29495. return 3;
  29496. case VertexBuffer.ColorKind:
  29497. case VertexBuffer.MatricesIndicesKind:
  29498. case VertexBuffer.MatricesIndicesExtraKind:
  29499. case VertexBuffer.MatricesWeightsKind:
  29500. case VertexBuffer.MatricesWeightsExtraKind:
  29501. case VertexBuffer.TangentKind:
  29502. return 4;
  29503. default:
  29504. throw new Error("Invalid kind '" + kind + "'");
  29505. }
  29506. };
  29507. /**
  29508. * Gets the byte length of the given type.
  29509. * @param type the type
  29510. * @returns the number of bytes
  29511. */
  29512. VertexBuffer.GetTypeByteLength = function (type) {
  29513. switch (type) {
  29514. case VertexBuffer.BYTE:
  29515. case VertexBuffer.UNSIGNED_BYTE:
  29516. return 1;
  29517. case VertexBuffer.SHORT:
  29518. case VertexBuffer.UNSIGNED_SHORT:
  29519. return 2;
  29520. case VertexBuffer.INT:
  29521. case VertexBuffer.FLOAT:
  29522. return 4;
  29523. default:
  29524. throw new Error("Invalid type '" + type + "'");
  29525. }
  29526. };
  29527. /**
  29528. * Enumerates each value of the given parameters as numbers.
  29529. * @param data the data to enumerate
  29530. * @param byteOffset the byte offset of the data
  29531. * @param byteStride the byte stride of the data
  29532. * @param componentCount the number of components per element
  29533. * @param componentType the type of the component
  29534. * @param count the total number of components
  29535. * @param normalized whether the data is normalized
  29536. * @param callback the callback function called for each value
  29537. */
  29538. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29539. if (data instanceof Array) {
  29540. var offset = byteOffset / 4;
  29541. var stride = byteStride / 4;
  29542. for (var index = 0; index < count; index += componentCount) {
  29543. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29544. callback(data[offset + componentIndex], index + componentIndex);
  29545. }
  29546. offset += stride;
  29547. }
  29548. }
  29549. else {
  29550. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29551. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29552. for (var index = 0; index < count; index += componentCount) {
  29553. var componentByteOffset = byteOffset;
  29554. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29555. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29556. callback(value, index + componentIndex);
  29557. componentByteOffset += componentByteLength;
  29558. }
  29559. byteOffset += byteStride;
  29560. }
  29561. }
  29562. };
  29563. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29564. switch (type) {
  29565. case VertexBuffer.BYTE: {
  29566. var value = dataView.getInt8(byteOffset);
  29567. if (normalized) {
  29568. value = Math.max(value / 127, -1);
  29569. }
  29570. return value;
  29571. }
  29572. case VertexBuffer.UNSIGNED_BYTE: {
  29573. var value = dataView.getUint8(byteOffset);
  29574. if (normalized) {
  29575. value = value / 255;
  29576. }
  29577. return value;
  29578. }
  29579. case VertexBuffer.SHORT: {
  29580. var value = dataView.getInt16(byteOffset, true);
  29581. if (normalized) {
  29582. value = Math.max(value / 16383, -1);
  29583. }
  29584. return value;
  29585. }
  29586. case VertexBuffer.UNSIGNED_SHORT: {
  29587. var value = dataView.getUint16(byteOffset, true);
  29588. if (normalized) {
  29589. value = value / 65535;
  29590. }
  29591. return value;
  29592. }
  29593. case VertexBuffer.FLOAT: {
  29594. return dataView.getFloat32(byteOffset, true);
  29595. }
  29596. default: {
  29597. throw new Error("Invalid component type " + type);
  29598. }
  29599. }
  29600. };
  29601. /**
  29602. * The byte type.
  29603. */
  29604. VertexBuffer.BYTE = 5120;
  29605. /**
  29606. * The unsigned byte type.
  29607. */
  29608. VertexBuffer.UNSIGNED_BYTE = 5121;
  29609. /**
  29610. * The short type.
  29611. */
  29612. VertexBuffer.SHORT = 5122;
  29613. /**
  29614. * The unsigned short type.
  29615. */
  29616. VertexBuffer.UNSIGNED_SHORT = 5123;
  29617. /**
  29618. * The integer type.
  29619. */
  29620. VertexBuffer.INT = 5124;
  29621. /**
  29622. * The unsigned integer type.
  29623. */
  29624. VertexBuffer.UNSIGNED_INT = 5125;
  29625. /**
  29626. * The float type.
  29627. */
  29628. VertexBuffer.FLOAT = 5126;
  29629. // Enums
  29630. VertexBuffer._PositionKind = "position";
  29631. VertexBuffer._NormalKind = "normal";
  29632. VertexBuffer._TangentKind = "tangent";
  29633. VertexBuffer._UVKind = "uv";
  29634. VertexBuffer._UV2Kind = "uv2";
  29635. VertexBuffer._UV3Kind = "uv3";
  29636. VertexBuffer._UV4Kind = "uv4";
  29637. VertexBuffer._UV5Kind = "uv5";
  29638. VertexBuffer._UV6Kind = "uv6";
  29639. VertexBuffer._ColorKind = "color";
  29640. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29641. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29642. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29643. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29644. return VertexBuffer;
  29645. }());
  29646. BABYLON.VertexBuffer = VertexBuffer;
  29647. })(BABYLON || (BABYLON = {}));
  29648. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29649. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29650. var BABYLON;
  29651. (function (BABYLON) {
  29652. /**
  29653. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29654. */
  29655. var DummyInternalTextureTracker = /** @class */ (function () {
  29656. function DummyInternalTextureTracker() {
  29657. /**
  29658. * Gets or set the previous tracker in the list
  29659. */
  29660. this.previous = null;
  29661. /**
  29662. * Gets or set the next tracker in the list
  29663. */
  29664. this.next = null;
  29665. }
  29666. return DummyInternalTextureTracker;
  29667. }());
  29668. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29669. })(BABYLON || (BABYLON = {}));
  29670. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29671. var BABYLON;
  29672. (function (BABYLON) {
  29673. /**
  29674. * Class used to store data associated with WebGL texture data for the engine
  29675. * This class should not be used directly
  29676. */
  29677. var InternalTexture = /** @class */ (function () {
  29678. /**
  29679. * Creates a new InternalTexture
  29680. * @param engine defines the engine to use
  29681. * @param dataSource defines the type of data that will be used
  29682. */
  29683. function InternalTexture(engine, dataSource) {
  29684. /**
  29685. * Observable called when the texture is loaded
  29686. */
  29687. this.onLoadedObservable = new BABYLON.Observable();
  29688. /**
  29689. * Gets or set the previous tracker in the list
  29690. */
  29691. this.previous = null;
  29692. /**
  29693. * Gets or set the next tracker in the list
  29694. */
  29695. this.next = null;
  29696. // Private
  29697. /** @hidden */
  29698. this._initialSlot = -1;
  29699. /** @hidden */
  29700. this._designatedSlot = -1;
  29701. /** @hidden */
  29702. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29703. /** @hidden */
  29704. this._comparisonFunction = 0;
  29705. /** @hidden */
  29706. this._sphericalPolynomial = null;
  29707. /** @hidden */
  29708. this._lodGenerationScale = 0;
  29709. /** @hidden */
  29710. this._lodGenerationOffset = 0;
  29711. /** @hidden */
  29712. this._isRGBD = false;
  29713. /** @hidden */
  29714. this._references = 1;
  29715. this._engine = engine;
  29716. this._dataSource = dataSource;
  29717. this._webGLTexture = engine._createTexture();
  29718. }
  29719. /**
  29720. * Gets the Engine the texture belongs to.
  29721. * @returns The babylon engine
  29722. */
  29723. InternalTexture.prototype.getEngine = function () {
  29724. return this._engine;
  29725. };
  29726. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29727. /**
  29728. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29729. */
  29730. get: function () {
  29731. return this._dataSource;
  29732. },
  29733. enumerable: true,
  29734. configurable: true
  29735. });
  29736. /**
  29737. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29738. */
  29739. InternalTexture.prototype.incrementReferences = function () {
  29740. this._references++;
  29741. };
  29742. /**
  29743. * Change the size of the texture (not the size of the content)
  29744. * @param width defines the new width
  29745. * @param height defines the new height
  29746. * @param depth defines the new depth (1 by default)
  29747. */
  29748. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29749. if (depth === void 0) { depth = 1; }
  29750. this.width = width;
  29751. this.height = height;
  29752. this.depth = depth;
  29753. this.baseWidth = width;
  29754. this.baseHeight = height;
  29755. this.baseDepth = depth;
  29756. this._size = width * height * depth;
  29757. };
  29758. /** @hidden */
  29759. InternalTexture.prototype._rebuild = function () {
  29760. var _this = this;
  29761. var proxy;
  29762. this.isReady = false;
  29763. this._cachedCoordinatesMode = null;
  29764. this._cachedWrapU = null;
  29765. this._cachedWrapV = null;
  29766. this._cachedAnisotropicFilteringLevel = null;
  29767. switch (this._dataSource) {
  29768. case InternalTexture.DATASOURCE_TEMP:
  29769. return;
  29770. case InternalTexture.DATASOURCE_URL:
  29771. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29772. _this.isReady = true;
  29773. }, null, this._buffer, undefined, this.format);
  29774. proxy._swapAndDie(this);
  29775. return;
  29776. case InternalTexture.DATASOURCE_RAW:
  29777. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29778. proxy._swapAndDie(this);
  29779. this.isReady = true;
  29780. return;
  29781. case InternalTexture.DATASOURCE_RAW3D:
  29782. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29783. proxy._swapAndDie(this);
  29784. this.isReady = true;
  29785. return;
  29786. case InternalTexture.DATASOURCE_DYNAMIC:
  29787. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29788. proxy._swapAndDie(this);
  29789. // The engine will make sure to update content so no need to flag it as isReady = true
  29790. return;
  29791. case InternalTexture.DATASOURCE_RENDERTARGET:
  29792. var options = new BABYLON.RenderTargetCreationOptions();
  29793. options.generateDepthBuffer = this._generateDepthBuffer;
  29794. options.generateMipMaps = this.generateMipMaps;
  29795. options.generateStencilBuffer = this._generateStencilBuffer;
  29796. options.samplingMode = this.samplingMode;
  29797. options.type = this.type;
  29798. if (this.isCube) {
  29799. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29800. }
  29801. else {
  29802. var size = {
  29803. width: this.width,
  29804. height: this.height
  29805. };
  29806. proxy = this._engine.createRenderTargetTexture(size, options);
  29807. }
  29808. proxy._swapAndDie(this);
  29809. this.isReady = true;
  29810. return;
  29811. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29812. var depthTextureOptions = {
  29813. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29814. comparisonFunction: this._comparisonFunction,
  29815. generateStencil: this._generateStencilBuffer,
  29816. isCube: this.isCube
  29817. };
  29818. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29819. proxy._swapAndDie(this);
  29820. this.isReady = true;
  29821. return;
  29822. case InternalTexture.DATASOURCE_CUBE:
  29823. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29824. _this.isReady = true;
  29825. }, null, this.format, this._extension);
  29826. proxy._swapAndDie(this);
  29827. return;
  29828. case InternalTexture.DATASOURCE_CUBERAW:
  29829. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29830. proxy._swapAndDie(this);
  29831. this.isReady = true;
  29832. return;
  29833. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29834. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29835. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29836. _this.isReady = true;
  29837. });
  29838. proxy._swapAndDie(this);
  29839. return;
  29840. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29841. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29842. if (proxy) {
  29843. proxy._swapAndDie(_this);
  29844. }
  29845. _this.isReady = true;
  29846. }, null, this.format, this._extension);
  29847. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29848. return;
  29849. }
  29850. };
  29851. /** @hidden */
  29852. InternalTexture.prototype._swapAndDie = function (target) {
  29853. target._webGLTexture = this._webGLTexture;
  29854. if (this._framebuffer) {
  29855. target._framebuffer = this._framebuffer;
  29856. }
  29857. if (this._depthStencilBuffer) {
  29858. target._depthStencilBuffer = this._depthStencilBuffer;
  29859. }
  29860. if (this._lodTextureHigh) {
  29861. if (target._lodTextureHigh) {
  29862. target._lodTextureHigh.dispose();
  29863. }
  29864. target._lodTextureHigh = this._lodTextureHigh;
  29865. }
  29866. if (this._lodTextureMid) {
  29867. if (target._lodTextureMid) {
  29868. target._lodTextureMid.dispose();
  29869. }
  29870. target._lodTextureMid = this._lodTextureMid;
  29871. }
  29872. if (this._lodTextureLow) {
  29873. if (target._lodTextureLow) {
  29874. target._lodTextureLow.dispose();
  29875. }
  29876. target._lodTextureLow = this._lodTextureLow;
  29877. }
  29878. var cache = this._engine.getLoadedTexturesCache();
  29879. var index = cache.indexOf(this);
  29880. if (index !== -1) {
  29881. cache.splice(index, 1);
  29882. }
  29883. };
  29884. /**
  29885. * Dispose the current allocated resources
  29886. */
  29887. InternalTexture.prototype.dispose = function () {
  29888. if (!this._webGLTexture) {
  29889. return;
  29890. }
  29891. this._references--;
  29892. if (this._references === 0) {
  29893. this._engine._releaseTexture(this);
  29894. this._webGLTexture = null;
  29895. this.previous = null;
  29896. this.next = null;
  29897. }
  29898. };
  29899. /**
  29900. * The source of the texture data is unknown
  29901. */
  29902. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29903. /**
  29904. * Texture data comes from an URL
  29905. */
  29906. InternalTexture.DATASOURCE_URL = 1;
  29907. /**
  29908. * Texture data is only used for temporary storage
  29909. */
  29910. InternalTexture.DATASOURCE_TEMP = 2;
  29911. /**
  29912. * Texture data comes from raw data (ArrayBuffer)
  29913. */
  29914. InternalTexture.DATASOURCE_RAW = 3;
  29915. /**
  29916. * Texture content is dynamic (video or dynamic texture)
  29917. */
  29918. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29919. /**
  29920. * Texture content is generated by rendering to it
  29921. */
  29922. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29923. /**
  29924. * Texture content is part of a multi render target process
  29925. */
  29926. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29927. /**
  29928. * Texture data comes from a cube data file
  29929. */
  29930. InternalTexture.DATASOURCE_CUBE = 7;
  29931. /**
  29932. * Texture data comes from a raw cube data
  29933. */
  29934. InternalTexture.DATASOURCE_CUBERAW = 8;
  29935. /**
  29936. * Texture data come from a prefiltered cube data file
  29937. */
  29938. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29939. /**
  29940. * Texture content is raw 3D data
  29941. */
  29942. InternalTexture.DATASOURCE_RAW3D = 10;
  29943. /**
  29944. * Texture content is a depth texture
  29945. */
  29946. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29947. /**
  29948. * Texture data comes from a raw cube data encoded with RGBD
  29949. */
  29950. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29951. return InternalTexture;
  29952. }());
  29953. BABYLON.InternalTexture = InternalTexture;
  29954. })(BABYLON || (BABYLON = {}));
  29955. //# sourceMappingURL=babylon.internalTexture.js.map
  29956. var BABYLON;
  29957. (function (BABYLON) {
  29958. var BaseTexture = /** @class */ (function () {
  29959. function BaseTexture(scene) {
  29960. this._hasAlpha = false;
  29961. this.getAlphaFromRGB = false;
  29962. this.level = 1;
  29963. this.coordinatesIndex = 0;
  29964. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29965. /**
  29966. * | Value | Type | Description |
  29967. * | ----- | ------------------ | ----------- |
  29968. * | 0 | CLAMP_ADDRESSMODE | |
  29969. * | 1 | WRAP_ADDRESSMODE | |
  29970. * | 2 | MIRROR_ADDRESSMODE | |
  29971. */
  29972. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29973. /**
  29974. * | Value | Type | Description |
  29975. * | ----- | ------------------ | ----------- |
  29976. * | 0 | CLAMP_ADDRESSMODE | |
  29977. * | 1 | WRAP_ADDRESSMODE | |
  29978. * | 2 | MIRROR_ADDRESSMODE | |
  29979. */
  29980. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29981. /**
  29982. * | Value | Type | Description |
  29983. * | ----- | ------------------ | ----------- |
  29984. * | 0 | CLAMP_ADDRESSMODE | |
  29985. * | 1 | WRAP_ADDRESSMODE | |
  29986. * | 2 | MIRROR_ADDRESSMODE | |
  29987. */
  29988. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29989. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29990. this.isCube = false;
  29991. this.is3D = false;
  29992. this.gammaSpace = true;
  29993. this.invertZ = false;
  29994. this.lodLevelInAlpha = false;
  29995. this.isRenderTarget = false;
  29996. this.animations = new Array();
  29997. /**
  29998. * An event triggered when the texture is disposed.
  29999. */
  30000. this.onDisposeObservable = new BABYLON.Observable();
  30001. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30002. this._cachedSize = BABYLON.Size.Zero();
  30003. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30004. if (this._scene) {
  30005. this._scene.textures.push(this);
  30006. }
  30007. this._uid = null;
  30008. }
  30009. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30010. get: function () {
  30011. return this._hasAlpha;
  30012. },
  30013. set: function (value) {
  30014. if (this._hasAlpha === value) {
  30015. return;
  30016. }
  30017. this._hasAlpha = value;
  30018. if (this._scene) {
  30019. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30020. }
  30021. },
  30022. enumerable: true,
  30023. configurable: true
  30024. });
  30025. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30026. get: function () {
  30027. return this._coordinatesMode;
  30028. },
  30029. /**
  30030. * How a texture is mapped.
  30031. *
  30032. * | Value | Type | Description |
  30033. * | ----- | ----------------------------------- | ----------- |
  30034. * | 0 | EXPLICIT_MODE | |
  30035. * | 1 | SPHERICAL_MODE | |
  30036. * | 2 | PLANAR_MODE | |
  30037. * | 3 | CUBIC_MODE | |
  30038. * | 4 | PROJECTION_MODE | |
  30039. * | 5 | SKYBOX_MODE | |
  30040. * | 6 | INVCUBIC_MODE | |
  30041. * | 7 | EQUIRECTANGULAR_MODE | |
  30042. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30043. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30044. */
  30045. set: function (value) {
  30046. if (this._coordinatesMode === value) {
  30047. return;
  30048. }
  30049. this._coordinatesMode = value;
  30050. if (this._scene) {
  30051. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30052. }
  30053. },
  30054. enumerable: true,
  30055. configurable: true
  30056. });
  30057. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30058. /**
  30059. * Gets whether or not the texture contains RGBD data.
  30060. */
  30061. get: function () {
  30062. return this._texture != null && this._texture._isRGBD;
  30063. },
  30064. enumerable: true,
  30065. configurable: true
  30066. });
  30067. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30068. get: function () {
  30069. if (this._texture)
  30070. return this._texture._lodGenerationOffset;
  30071. return 0.0;
  30072. },
  30073. set: function (value) {
  30074. if (this._texture)
  30075. this._texture._lodGenerationOffset = value;
  30076. },
  30077. enumerable: true,
  30078. configurable: true
  30079. });
  30080. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30081. get: function () {
  30082. if (this._texture)
  30083. return this._texture._lodGenerationScale;
  30084. return 0.0;
  30085. },
  30086. set: function (value) {
  30087. if (this._texture)
  30088. this._texture._lodGenerationScale = value;
  30089. },
  30090. enumerable: true,
  30091. configurable: true
  30092. });
  30093. Object.defineProperty(BaseTexture.prototype, "uid", {
  30094. get: function () {
  30095. if (!this._uid) {
  30096. this._uid = BABYLON.Tools.RandomId();
  30097. }
  30098. return this._uid;
  30099. },
  30100. enumerable: true,
  30101. configurable: true
  30102. });
  30103. BaseTexture.prototype.toString = function () {
  30104. return this.name;
  30105. };
  30106. BaseTexture.prototype.getClassName = function () {
  30107. return "BaseTexture";
  30108. };
  30109. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30110. set: function (callback) {
  30111. if (this._onDisposeObserver) {
  30112. this.onDisposeObservable.remove(this._onDisposeObserver);
  30113. }
  30114. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30115. },
  30116. enumerable: true,
  30117. configurable: true
  30118. });
  30119. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30120. get: function () {
  30121. return true;
  30122. },
  30123. enumerable: true,
  30124. configurable: true
  30125. });
  30126. BaseTexture.prototype.getScene = function () {
  30127. return this._scene;
  30128. };
  30129. BaseTexture.prototype.getTextureMatrix = function () {
  30130. return BABYLON.Matrix.IdentityReadOnly;
  30131. };
  30132. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30133. return BABYLON.Matrix.IdentityReadOnly;
  30134. };
  30135. BaseTexture.prototype.getInternalTexture = function () {
  30136. return this._texture;
  30137. };
  30138. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30139. return !this.isBlocking || this.isReady();
  30140. };
  30141. BaseTexture.prototype.isReady = function () {
  30142. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30143. this.delayLoad();
  30144. return false;
  30145. }
  30146. if (this._texture) {
  30147. return this._texture.isReady;
  30148. }
  30149. return false;
  30150. };
  30151. BaseTexture.prototype.getSize = function () {
  30152. if (this._texture) {
  30153. if (this._texture.width) {
  30154. this._cachedSize.width = this._texture.width;
  30155. this._cachedSize.height = this._texture.height;
  30156. return this._cachedSize;
  30157. }
  30158. if (this._texture._size) {
  30159. this._cachedSize.width = this._texture._size;
  30160. this._cachedSize.height = this._texture._size;
  30161. return this._cachedSize;
  30162. }
  30163. }
  30164. return this._cachedSize;
  30165. };
  30166. BaseTexture.prototype.getBaseSize = function () {
  30167. if (!this.isReady() || !this._texture)
  30168. return BABYLON.Size.Zero();
  30169. if (this._texture._size) {
  30170. return new BABYLON.Size(this._texture._size, this._texture._size);
  30171. }
  30172. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30173. };
  30174. BaseTexture.prototype.scale = function (ratio) {
  30175. };
  30176. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30177. get: function () {
  30178. return false;
  30179. },
  30180. enumerable: true,
  30181. configurable: true
  30182. });
  30183. /** @hidden */
  30184. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30185. if (!this._scene) {
  30186. return null;
  30187. }
  30188. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30189. for (var index = 0; index < texturesCache.length; index++) {
  30190. var texturesCacheEntry = texturesCache[index];
  30191. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30192. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30193. texturesCacheEntry.incrementReferences();
  30194. return texturesCacheEntry;
  30195. }
  30196. }
  30197. }
  30198. return null;
  30199. };
  30200. /** @hidden */
  30201. BaseTexture.prototype._rebuild = function () {
  30202. };
  30203. BaseTexture.prototype.delayLoad = function () {
  30204. };
  30205. BaseTexture.prototype.clone = function () {
  30206. return null;
  30207. };
  30208. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30209. get: function () {
  30210. if (!this._texture) {
  30211. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30212. }
  30213. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30214. },
  30215. enumerable: true,
  30216. configurable: true
  30217. });
  30218. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30219. get: function () {
  30220. if (!this._texture) {
  30221. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30222. }
  30223. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30224. },
  30225. enumerable: true,
  30226. configurable: true
  30227. });
  30228. /**
  30229. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30230. * This will returns an RGBA array buffer containing either in values (0-255) or
  30231. * float values (0-1) depending of the underlying buffer type.
  30232. * @param faceIndex The face of the texture to read (in case of cube texture)
  30233. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30234. * @returns The Array buffer containing the pixels data.
  30235. */
  30236. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30237. if (faceIndex === void 0) { faceIndex = 0; }
  30238. if (level === void 0) { level = 0; }
  30239. if (!this._texture) {
  30240. return null;
  30241. }
  30242. var size = this.getSize();
  30243. var width = size.width;
  30244. var height = size.height;
  30245. var scene = this.getScene();
  30246. if (!scene) {
  30247. return null;
  30248. }
  30249. var engine = scene.getEngine();
  30250. if (level != 0) {
  30251. width = width / Math.pow(2, level);
  30252. height = height / Math.pow(2, level);
  30253. width = Math.round(width);
  30254. height = Math.round(height);
  30255. }
  30256. if (this._texture.isCube) {
  30257. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30258. }
  30259. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30260. };
  30261. BaseTexture.prototype.releaseInternalTexture = function () {
  30262. if (this._texture) {
  30263. this._texture.dispose();
  30264. this._texture = null;
  30265. }
  30266. };
  30267. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30268. get: function () {
  30269. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30270. return null;
  30271. }
  30272. if (!this._texture._sphericalPolynomial) {
  30273. this._texture._sphericalPolynomial =
  30274. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30275. }
  30276. return this._texture._sphericalPolynomial;
  30277. },
  30278. set: function (value) {
  30279. if (this._texture) {
  30280. this._texture._sphericalPolynomial = value;
  30281. }
  30282. },
  30283. enumerable: true,
  30284. configurable: true
  30285. });
  30286. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30287. get: function () {
  30288. if (this._texture) {
  30289. return this._texture._lodTextureHigh;
  30290. }
  30291. return null;
  30292. },
  30293. enumerable: true,
  30294. configurable: true
  30295. });
  30296. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30297. get: function () {
  30298. if (this._texture) {
  30299. return this._texture._lodTextureMid;
  30300. }
  30301. return null;
  30302. },
  30303. enumerable: true,
  30304. configurable: true
  30305. });
  30306. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30307. get: function () {
  30308. if (this._texture) {
  30309. return this._texture._lodTextureLow;
  30310. }
  30311. return null;
  30312. },
  30313. enumerable: true,
  30314. configurable: true
  30315. });
  30316. BaseTexture.prototype.dispose = function () {
  30317. if (!this._scene) {
  30318. return;
  30319. }
  30320. // Animations
  30321. this._scene.stopAnimation(this);
  30322. // Remove from scene
  30323. this._scene._removePendingData(this);
  30324. var index = this._scene.textures.indexOf(this);
  30325. if (index >= 0) {
  30326. this._scene.textures.splice(index, 1);
  30327. }
  30328. if (this._texture === undefined) {
  30329. return;
  30330. }
  30331. // Release
  30332. this.releaseInternalTexture();
  30333. // Callback
  30334. this.onDisposeObservable.notifyObservers(this);
  30335. this.onDisposeObservable.clear();
  30336. };
  30337. BaseTexture.prototype.serialize = function () {
  30338. if (!this.name) {
  30339. return null;
  30340. }
  30341. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30342. // Animations
  30343. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30344. return serializationObject;
  30345. };
  30346. BaseTexture.WhenAllReady = function (textures, callback) {
  30347. var numRemaining = textures.length;
  30348. if (numRemaining === 0) {
  30349. callback();
  30350. return;
  30351. }
  30352. var _loop_1 = function () {
  30353. texture = textures[i];
  30354. if (texture.isReady()) {
  30355. if (--numRemaining === 0) {
  30356. callback();
  30357. }
  30358. }
  30359. else {
  30360. onLoadObservable = texture.onLoadObservable;
  30361. var onLoadCallback_1 = function () {
  30362. onLoadObservable.removeCallback(onLoadCallback_1);
  30363. if (--numRemaining === 0) {
  30364. callback();
  30365. }
  30366. };
  30367. onLoadObservable.add(onLoadCallback_1);
  30368. }
  30369. };
  30370. var texture, onLoadObservable;
  30371. for (var i = 0; i < textures.length; i++) {
  30372. _loop_1();
  30373. }
  30374. };
  30375. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30376. __decorate([
  30377. BABYLON.serialize()
  30378. ], BaseTexture.prototype, "name", void 0);
  30379. __decorate([
  30380. BABYLON.serialize("hasAlpha")
  30381. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30382. __decorate([
  30383. BABYLON.serialize()
  30384. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30385. __decorate([
  30386. BABYLON.serialize()
  30387. ], BaseTexture.prototype, "level", void 0);
  30388. __decorate([
  30389. BABYLON.serialize()
  30390. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30391. __decorate([
  30392. BABYLON.serialize("coordinatesMode")
  30393. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30394. __decorate([
  30395. BABYLON.serialize()
  30396. ], BaseTexture.prototype, "wrapU", void 0);
  30397. __decorate([
  30398. BABYLON.serialize()
  30399. ], BaseTexture.prototype, "wrapV", void 0);
  30400. __decorate([
  30401. BABYLON.serialize()
  30402. ], BaseTexture.prototype, "wrapR", void 0);
  30403. __decorate([
  30404. BABYLON.serialize()
  30405. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30406. __decorate([
  30407. BABYLON.serialize()
  30408. ], BaseTexture.prototype, "isCube", void 0);
  30409. __decorate([
  30410. BABYLON.serialize()
  30411. ], BaseTexture.prototype, "is3D", void 0);
  30412. __decorate([
  30413. BABYLON.serialize()
  30414. ], BaseTexture.prototype, "gammaSpace", void 0);
  30415. __decorate([
  30416. BABYLON.serialize()
  30417. ], BaseTexture.prototype, "invertZ", void 0);
  30418. __decorate([
  30419. BABYLON.serialize()
  30420. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30421. __decorate([
  30422. BABYLON.serialize()
  30423. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30424. __decorate([
  30425. BABYLON.serialize()
  30426. ], BaseTexture.prototype, "lodGenerationScale", null);
  30427. __decorate([
  30428. BABYLON.serialize()
  30429. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30430. return BaseTexture;
  30431. }());
  30432. BABYLON.BaseTexture = BaseTexture;
  30433. })(BABYLON || (BABYLON = {}));
  30434. //# sourceMappingURL=babylon.baseTexture.js.map
  30435. var BABYLON;
  30436. (function (BABYLON) {
  30437. var Texture = /** @class */ (function (_super) {
  30438. __extends(Texture, _super);
  30439. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30440. if (noMipmap === void 0) { noMipmap = false; }
  30441. if (invertY === void 0) { invertY = true; }
  30442. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30443. if (onLoad === void 0) { onLoad = null; }
  30444. if (onError === void 0) { onError = null; }
  30445. if (buffer === void 0) { buffer = null; }
  30446. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30447. var _this = _super.call(this, scene) || this;
  30448. _this.uOffset = 0;
  30449. _this.vOffset = 0;
  30450. _this.uScale = 1.0;
  30451. _this.vScale = 1.0;
  30452. _this.uAng = 0;
  30453. _this.vAng = 0;
  30454. _this.wAng = 0;
  30455. /**
  30456. * Defines the center of rotation (U)
  30457. */
  30458. _this.uRotationCenter = 0.5;
  30459. /**
  30460. * Defines the center of rotation (V)
  30461. */
  30462. _this.vRotationCenter = 0.5;
  30463. /**
  30464. * Defines the center of rotation (W)
  30465. */
  30466. _this.wRotationCenter = 0.5;
  30467. _this._isBlocking = true;
  30468. _this.name = url || "";
  30469. _this.url = url;
  30470. _this._noMipmap = noMipmap;
  30471. _this._invertY = invertY;
  30472. _this._samplingMode = samplingMode;
  30473. _this._buffer = buffer;
  30474. _this._deleteBuffer = deleteBuffer;
  30475. if (format) {
  30476. _this._format = format;
  30477. }
  30478. scene = _this.getScene();
  30479. if (!scene) {
  30480. return _this;
  30481. }
  30482. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30483. var load = function () {
  30484. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30485. _this.onLoadObservable.notifyObservers(_this);
  30486. }
  30487. if (onLoad) {
  30488. onLoad();
  30489. }
  30490. if (!_this.isBlocking && scene) {
  30491. scene.resetCachedMaterial();
  30492. }
  30493. };
  30494. if (!_this.url) {
  30495. _this._delayedOnLoad = load;
  30496. _this._delayedOnError = onError;
  30497. return _this;
  30498. }
  30499. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30500. if (!_this._texture) {
  30501. if (!scene.useDelayedTextureLoading) {
  30502. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30503. if (deleteBuffer) {
  30504. delete _this._buffer;
  30505. }
  30506. }
  30507. else {
  30508. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30509. _this._delayedOnLoad = load;
  30510. _this._delayedOnError = onError;
  30511. }
  30512. }
  30513. else {
  30514. if (_this._texture.isReady) {
  30515. BABYLON.Tools.SetImmediate(function () { return load(); });
  30516. }
  30517. else {
  30518. _this._texture.onLoadedObservable.add(load);
  30519. }
  30520. }
  30521. return _this;
  30522. }
  30523. Object.defineProperty(Texture.prototype, "noMipmap", {
  30524. get: function () {
  30525. return this._noMipmap;
  30526. },
  30527. enumerable: true,
  30528. configurable: true
  30529. });
  30530. Object.defineProperty(Texture.prototype, "isBlocking", {
  30531. get: function () {
  30532. return this._isBlocking;
  30533. },
  30534. set: function (value) {
  30535. this._isBlocking = value;
  30536. },
  30537. enumerable: true,
  30538. configurable: true
  30539. });
  30540. Object.defineProperty(Texture.prototype, "samplingMode", {
  30541. get: function () {
  30542. return this._samplingMode;
  30543. },
  30544. enumerable: true,
  30545. configurable: true
  30546. });
  30547. /**
  30548. * Update the url (and optional buffer) of this texture if url was null during construction.
  30549. * @param url the url of the texture
  30550. * @param buffer the buffer of the texture (defaults to null)
  30551. */
  30552. Texture.prototype.updateURL = function (url, buffer) {
  30553. if (buffer === void 0) { buffer = null; }
  30554. if (this.url) {
  30555. throw new Error("URL is already set");
  30556. }
  30557. this.url = url;
  30558. this._buffer = buffer;
  30559. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30560. this.delayLoad();
  30561. };
  30562. Texture.prototype.delayLoad = function () {
  30563. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30564. return;
  30565. }
  30566. var scene = this.getScene();
  30567. if (!scene) {
  30568. return;
  30569. }
  30570. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30571. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30572. if (!this._texture) {
  30573. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30574. if (this._deleteBuffer) {
  30575. delete this._buffer;
  30576. }
  30577. }
  30578. else {
  30579. if (this._delayedOnLoad) {
  30580. if (this._texture.isReady) {
  30581. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30582. }
  30583. else {
  30584. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30585. }
  30586. }
  30587. }
  30588. this._delayedOnLoad = null;
  30589. this._delayedOnError = null;
  30590. };
  30591. /**
  30592. * Default is Trilinear mode.
  30593. *
  30594. * | Value | Type | Description |
  30595. * | ----- | ------------------ | ----------- |
  30596. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30597. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30598. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30599. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30600. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30601. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30602. * | 7 | NEAREST_LINEAR | |
  30603. * | 8 | NEAREST_NEAREST | |
  30604. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30605. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30606. * | 11 | LINEAR_LINEAR | |
  30607. * | 12 | LINEAR_NEAREST | |
  30608. *
  30609. * > _mag_: magnification filter (close to the viewer)
  30610. * > _min_: minification filter (far from the viewer)
  30611. * > _mip_: filter used between mip map levels
  30612. *
  30613. */
  30614. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30615. if (!this._texture) {
  30616. return;
  30617. }
  30618. var scene = this.getScene();
  30619. if (!scene) {
  30620. return;
  30621. }
  30622. this._samplingMode = samplingMode;
  30623. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30624. };
  30625. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30626. x *= this.uScale;
  30627. y *= this.vScale;
  30628. x -= this.uRotationCenter * this.uScale;
  30629. y -= this.vRotationCenter * this.vScale;
  30630. z -= this.wRotationCenter;
  30631. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30632. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30633. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30634. t.z += this.wRotationCenter;
  30635. };
  30636. Texture.prototype.getTextureMatrix = function () {
  30637. var _this = this;
  30638. if (this.uOffset === this._cachedUOffset &&
  30639. this.vOffset === this._cachedVOffset &&
  30640. this.uScale === this._cachedUScale &&
  30641. this.vScale === this._cachedVScale &&
  30642. this.uAng === this._cachedUAng &&
  30643. this.vAng === this._cachedVAng &&
  30644. this.wAng === this._cachedWAng) {
  30645. return this._cachedTextureMatrix;
  30646. }
  30647. this._cachedUOffset = this.uOffset;
  30648. this._cachedVOffset = this.vOffset;
  30649. this._cachedUScale = this.uScale;
  30650. this._cachedVScale = this.vScale;
  30651. this._cachedUAng = this.uAng;
  30652. this._cachedVAng = this.vAng;
  30653. this._cachedWAng = this.wAng;
  30654. if (!this._cachedTextureMatrix) {
  30655. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30656. this._rowGenerationMatrix = new BABYLON.Matrix();
  30657. this._t0 = BABYLON.Vector3.Zero();
  30658. this._t1 = BABYLON.Vector3.Zero();
  30659. this._t2 = BABYLON.Vector3.Zero();
  30660. }
  30661. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30662. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30663. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30664. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30665. this._t1.subtractInPlace(this._t0);
  30666. this._t2.subtractInPlace(this._t0);
  30667. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30668. this._cachedTextureMatrix.m[0] = this._t1.x;
  30669. this._cachedTextureMatrix.m[1] = this._t1.y;
  30670. this._cachedTextureMatrix.m[2] = this._t1.z;
  30671. this._cachedTextureMatrix.m[4] = this._t2.x;
  30672. this._cachedTextureMatrix.m[5] = this._t2.y;
  30673. this._cachedTextureMatrix.m[6] = this._t2.z;
  30674. this._cachedTextureMatrix.m[8] = this._t0.x;
  30675. this._cachedTextureMatrix.m[9] = this._t0.y;
  30676. this._cachedTextureMatrix.m[10] = this._t0.z;
  30677. var scene = this.getScene();
  30678. if (!scene) {
  30679. return this._cachedTextureMatrix;
  30680. }
  30681. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30682. return mat.hasTexture(_this);
  30683. });
  30684. return this._cachedTextureMatrix;
  30685. };
  30686. Texture.prototype.getReflectionTextureMatrix = function () {
  30687. var _this = this;
  30688. var scene = this.getScene();
  30689. if (!scene) {
  30690. return this._cachedTextureMatrix;
  30691. }
  30692. if (this.uOffset === this._cachedUOffset &&
  30693. this.vOffset === this._cachedVOffset &&
  30694. this.uScale === this._cachedUScale &&
  30695. this.vScale === this._cachedVScale &&
  30696. this.coordinatesMode === this._cachedCoordinatesMode) {
  30697. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30698. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30699. return this._cachedTextureMatrix;
  30700. }
  30701. }
  30702. else {
  30703. return this._cachedTextureMatrix;
  30704. }
  30705. }
  30706. if (!this._cachedTextureMatrix) {
  30707. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30708. }
  30709. if (!this._projectionModeMatrix) {
  30710. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30711. }
  30712. this._cachedUOffset = this.uOffset;
  30713. this._cachedVOffset = this.vOffset;
  30714. this._cachedUScale = this.uScale;
  30715. this._cachedVScale = this.vScale;
  30716. this._cachedCoordinatesMode = this.coordinatesMode;
  30717. switch (this.coordinatesMode) {
  30718. case Texture.PLANAR_MODE:
  30719. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30720. this._cachedTextureMatrix[0] = this.uScale;
  30721. this._cachedTextureMatrix[5] = this.vScale;
  30722. this._cachedTextureMatrix[12] = this.uOffset;
  30723. this._cachedTextureMatrix[13] = this.vOffset;
  30724. break;
  30725. case Texture.PROJECTION_MODE:
  30726. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30727. this._projectionModeMatrix.m[0] = 0.5;
  30728. this._projectionModeMatrix.m[5] = -0.5;
  30729. this._projectionModeMatrix.m[10] = 0.0;
  30730. this._projectionModeMatrix.m[12] = 0.5;
  30731. this._projectionModeMatrix.m[13] = 0.5;
  30732. this._projectionModeMatrix.m[14] = 1.0;
  30733. this._projectionModeMatrix.m[15] = 1.0;
  30734. var projectionMatrix = scene.getProjectionMatrix();
  30735. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30736. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30737. break;
  30738. default:
  30739. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30740. break;
  30741. }
  30742. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30743. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30744. });
  30745. return this._cachedTextureMatrix;
  30746. };
  30747. Texture.prototype.clone = function () {
  30748. var _this = this;
  30749. return BABYLON.SerializationHelper.Clone(function () {
  30750. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30751. }, this);
  30752. };
  30753. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30754. get: function () {
  30755. if (!this._onLoadObservable) {
  30756. this._onLoadObservable = new BABYLON.Observable();
  30757. }
  30758. return this._onLoadObservable;
  30759. },
  30760. enumerable: true,
  30761. configurable: true
  30762. });
  30763. Texture.prototype.serialize = function () {
  30764. var serializationObject = _super.prototype.serialize.call(this);
  30765. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30766. serializationObject.base64String = this._buffer;
  30767. serializationObject.name = serializationObject.name.replace("data:", "");
  30768. }
  30769. serializationObject.invertY = this._invertY;
  30770. serializationObject.samplingMode = this.samplingMode;
  30771. return serializationObject;
  30772. };
  30773. Texture.prototype.getClassName = function () {
  30774. return "Texture";
  30775. };
  30776. Texture.prototype.dispose = function () {
  30777. _super.prototype.dispose.call(this);
  30778. if (this._onLoadObservable) {
  30779. this._onLoadObservable.clear();
  30780. this._onLoadObservable = null;
  30781. }
  30782. this._delayedOnLoad = null;
  30783. this._delayedOnError = null;
  30784. };
  30785. // Statics
  30786. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30787. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30788. if (onLoad === void 0) { onLoad = null; }
  30789. if (onError === void 0) { onError = null; }
  30790. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30791. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30792. };
  30793. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30794. if (parsedTexture.customType) {
  30795. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30796. // Update Sampling Mode
  30797. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30798. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30799. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30800. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30801. }
  30802. }
  30803. return parsedCustomTexture;
  30804. }
  30805. if (parsedTexture.isCube) {
  30806. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30807. }
  30808. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30809. return null;
  30810. }
  30811. var texture = BABYLON.SerializationHelper.Parse(function () {
  30812. var generateMipMaps = true;
  30813. if (parsedTexture.noMipmap) {
  30814. generateMipMaps = false;
  30815. }
  30816. if (parsedTexture.mirrorPlane) {
  30817. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30818. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30819. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30820. return mirrorTexture;
  30821. }
  30822. else if (parsedTexture.isRenderTarget) {
  30823. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30824. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30825. return renderTargetTexture;
  30826. }
  30827. else {
  30828. var texture;
  30829. if (parsedTexture.base64String) {
  30830. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30831. }
  30832. else {
  30833. var url = rootUrl + parsedTexture.name;
  30834. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30835. url = parsedTexture.url;
  30836. }
  30837. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30838. }
  30839. return texture;
  30840. }
  30841. }, parsedTexture, scene);
  30842. // Update Sampling Mode
  30843. if (parsedTexture.samplingMode) {
  30844. var sampling = parsedTexture.samplingMode;
  30845. if (texture._samplingMode !== sampling) {
  30846. texture.updateSamplingMode(sampling);
  30847. }
  30848. }
  30849. // Animations
  30850. if (parsedTexture.animations) {
  30851. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30852. var parsedAnimation = parsedTexture.animations[animationIndex];
  30853. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30854. }
  30855. }
  30856. return texture;
  30857. };
  30858. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30859. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30860. if (noMipmap === void 0) { noMipmap = false; }
  30861. if (invertY === void 0) { invertY = true; }
  30862. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30863. if (onLoad === void 0) { onLoad = null; }
  30864. if (onError === void 0) { onError = null; }
  30865. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30866. if (name.substr(0, 5) !== "data:") {
  30867. name = "data:" + name;
  30868. }
  30869. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30870. };
  30871. // Constants
  30872. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30873. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30874. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30875. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30876. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30877. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30878. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30879. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30880. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30881. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30882. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30883. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30884. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30885. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30886. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30887. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30888. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30889. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30890. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30891. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30892. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30893. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30894. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30895. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30896. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30897. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30898. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30899. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30900. /**
  30901. * 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
  30902. */
  30903. Texture.UseSerializedUrlIfAny = false;
  30904. __decorate([
  30905. BABYLON.serialize()
  30906. ], Texture.prototype, "url", void 0);
  30907. __decorate([
  30908. BABYLON.serialize()
  30909. ], Texture.prototype, "uOffset", void 0);
  30910. __decorate([
  30911. BABYLON.serialize()
  30912. ], Texture.prototype, "vOffset", void 0);
  30913. __decorate([
  30914. BABYLON.serialize()
  30915. ], Texture.prototype, "uScale", void 0);
  30916. __decorate([
  30917. BABYLON.serialize()
  30918. ], Texture.prototype, "vScale", void 0);
  30919. __decorate([
  30920. BABYLON.serialize()
  30921. ], Texture.prototype, "uAng", void 0);
  30922. __decorate([
  30923. BABYLON.serialize()
  30924. ], Texture.prototype, "vAng", void 0);
  30925. __decorate([
  30926. BABYLON.serialize()
  30927. ], Texture.prototype, "wAng", void 0);
  30928. __decorate([
  30929. BABYLON.serialize()
  30930. ], Texture.prototype, "uRotationCenter", void 0);
  30931. __decorate([
  30932. BABYLON.serialize()
  30933. ], Texture.prototype, "vRotationCenter", void 0);
  30934. __decorate([
  30935. BABYLON.serialize()
  30936. ], Texture.prototype, "wRotationCenter", void 0);
  30937. __decorate([
  30938. BABYLON.serialize()
  30939. ], Texture.prototype, "isBlocking", null);
  30940. return Texture;
  30941. }(BABYLON.BaseTexture));
  30942. BABYLON.Texture = Texture;
  30943. })(BABYLON || (BABYLON = {}));
  30944. //# sourceMappingURL=babylon.texture.js.map
  30945. var BABYLON;
  30946. (function (BABYLON) {
  30947. /**
  30948. * @hidden
  30949. **/
  30950. var _InstancesBatch = /** @class */ (function () {
  30951. function _InstancesBatch() {
  30952. this.mustReturn = false;
  30953. this.visibleInstances = new Array();
  30954. this.renderSelf = new Array();
  30955. }
  30956. return _InstancesBatch;
  30957. }());
  30958. BABYLON._InstancesBatch = _InstancesBatch;
  30959. var Mesh = /** @class */ (function (_super) {
  30960. __extends(Mesh, _super);
  30961. /**
  30962. * @constructor
  30963. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30964. * @param {Scene} scene The scene to add this mesh to.
  30965. * @param {Node} parent The parent of this mesh, if it has one
  30966. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30967. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30968. * When false, achieved by calling a clone(), also passing False.
  30969. * This will make creation of children, recursive.
  30970. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30971. */
  30972. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30973. if (scene === void 0) { scene = null; }
  30974. if (parent === void 0) { parent = null; }
  30975. if (source === void 0) { source = null; }
  30976. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30977. var _this = _super.call(this, name, scene) || this;
  30978. // Members
  30979. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30980. _this.instances = new Array();
  30981. _this._LODLevels = new Array();
  30982. /** @hidden */
  30983. _this._visibleInstances = {};
  30984. _this._renderIdForInstances = new Array();
  30985. _this._batchCache = new _InstancesBatch();
  30986. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30987. // Use by builder only to know what orientation were the mesh build in.
  30988. /** @hidden */
  30989. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30990. _this.overrideMaterialSideOrientation = null;
  30991. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30992. // Will be used to save a source mesh reference, If any
  30993. _this._source = null;
  30994. scene = _this.getScene();
  30995. if (source) {
  30996. // Geometry
  30997. if (source._geometry) {
  30998. source._geometry.applyToMesh(_this);
  30999. }
  31000. // Deep copy
  31001. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31002. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31003. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31004. ], ["_poseMatrix"]);
  31005. // Source mesh
  31006. _this._source = source;
  31007. // Construction Params
  31008. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31009. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31010. var myAnyThis = _this;
  31011. var myAnySource = source;
  31012. myAnyThis._closePath = myAnySource._closePath;
  31013. myAnyThis._idx = myAnySource._idx;
  31014. myAnyThis.dashSize = myAnySource.dashSize;
  31015. myAnyThis.gapSize = myAnySource.gapSize;
  31016. myAnyThis.path3D = myAnySource.path3D;
  31017. myAnyThis.pathArray = myAnySource.pathArray;
  31018. myAnyThis.arc = myAnySource.arc;
  31019. myAnyThis.radius = myAnySource.radius;
  31020. // Animation ranges
  31021. if (_this._source._ranges) {
  31022. var ranges = _this._source._ranges;
  31023. for (var name in ranges) {
  31024. if (!ranges.hasOwnProperty(name)) {
  31025. continue;
  31026. }
  31027. if (!ranges[name]) {
  31028. continue;
  31029. }
  31030. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31031. }
  31032. }
  31033. // Metadata
  31034. if (source.metadata && source.metadata.clone) {
  31035. _this.metadata = source.metadata.clone();
  31036. }
  31037. else {
  31038. _this.metadata = source.metadata;
  31039. }
  31040. // Tags
  31041. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31042. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31043. }
  31044. // Parent
  31045. _this.parent = source.parent;
  31046. // Pivot
  31047. _this.setPivotMatrix(source.getPivotMatrix());
  31048. _this.id = name + "." + source.id;
  31049. // Material
  31050. _this.material = source.material;
  31051. var index;
  31052. if (!doNotCloneChildren) {
  31053. // Children
  31054. var directDescendants = source.getDescendants(true);
  31055. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31056. var child = directDescendants[index_1];
  31057. if (child.clone) {
  31058. child.clone(name + "." + child.name, _this);
  31059. }
  31060. }
  31061. }
  31062. // Physics clone
  31063. var physicsEngine = _this.getScene().getPhysicsEngine();
  31064. if (clonePhysicsImpostor && physicsEngine) {
  31065. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31066. if (impostor) {
  31067. _this.physicsImpostor = impostor.clone(_this);
  31068. }
  31069. }
  31070. // Particles
  31071. for (index = 0; index < scene.particleSystems.length; index++) {
  31072. var system = scene.particleSystems[index];
  31073. if (system.emitter === source) {
  31074. system.clone(system.name, _this);
  31075. }
  31076. }
  31077. _this.refreshBoundingInfo();
  31078. _this.computeWorldMatrix(true);
  31079. }
  31080. // Parent
  31081. if (parent !== null) {
  31082. _this.parent = parent;
  31083. }
  31084. return _this;
  31085. }
  31086. Object.defineProperty(Mesh, "FRONTSIDE", {
  31087. /**
  31088. * Mesh side orientation : usually the external or front surface
  31089. */
  31090. get: function () {
  31091. return Mesh._FRONTSIDE;
  31092. },
  31093. enumerable: true,
  31094. configurable: true
  31095. });
  31096. Object.defineProperty(Mesh, "BACKSIDE", {
  31097. /**
  31098. * Mesh side orientation : usually the internal or back surface
  31099. */
  31100. get: function () {
  31101. return Mesh._BACKSIDE;
  31102. },
  31103. enumerable: true,
  31104. configurable: true
  31105. });
  31106. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31107. /**
  31108. * Mesh side orientation : both internal and external or front and back surfaces
  31109. */
  31110. get: function () {
  31111. return Mesh._DOUBLESIDE;
  31112. },
  31113. enumerable: true,
  31114. configurable: true
  31115. });
  31116. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31117. /**
  31118. * Mesh side orientation : by default, `FRONTSIDE`
  31119. */
  31120. get: function () {
  31121. return Mesh._DEFAULTSIDE;
  31122. },
  31123. enumerable: true,
  31124. configurable: true
  31125. });
  31126. Object.defineProperty(Mesh, "NO_CAP", {
  31127. /**
  31128. * Mesh cap setting : no cap
  31129. */
  31130. get: function () {
  31131. return Mesh._NO_CAP;
  31132. },
  31133. enumerable: true,
  31134. configurable: true
  31135. });
  31136. Object.defineProperty(Mesh, "CAP_START", {
  31137. /**
  31138. * Mesh cap setting : one cap at the beginning of the mesh
  31139. */
  31140. get: function () {
  31141. return Mesh._CAP_START;
  31142. },
  31143. enumerable: true,
  31144. configurable: true
  31145. });
  31146. Object.defineProperty(Mesh, "CAP_END", {
  31147. /**
  31148. * Mesh cap setting : one cap at the end of the mesh
  31149. */
  31150. get: function () {
  31151. return Mesh._CAP_END;
  31152. },
  31153. enumerable: true,
  31154. configurable: true
  31155. });
  31156. Object.defineProperty(Mesh, "CAP_ALL", {
  31157. /**
  31158. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31159. */
  31160. get: function () {
  31161. return Mesh._CAP_ALL;
  31162. },
  31163. enumerable: true,
  31164. configurable: true
  31165. });
  31166. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31167. /**
  31168. * An event triggered before rendering the mesh
  31169. */
  31170. get: function () {
  31171. if (!this._onBeforeRenderObservable) {
  31172. this._onBeforeRenderObservable = new BABYLON.Observable();
  31173. }
  31174. return this._onBeforeRenderObservable;
  31175. },
  31176. enumerable: true,
  31177. configurable: true
  31178. });
  31179. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31180. /**
  31181. * An event triggered after rendering the mesh
  31182. */
  31183. get: function () {
  31184. if (!this._onAfterRenderObservable) {
  31185. this._onAfterRenderObservable = new BABYLON.Observable();
  31186. }
  31187. return this._onAfterRenderObservable;
  31188. },
  31189. enumerable: true,
  31190. configurable: true
  31191. });
  31192. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31193. /**
  31194. * An event triggered before drawing the mesh
  31195. */
  31196. get: function () {
  31197. if (!this._onBeforeDrawObservable) {
  31198. this._onBeforeDrawObservable = new BABYLON.Observable();
  31199. }
  31200. return this._onBeforeDrawObservable;
  31201. },
  31202. enumerable: true,
  31203. configurable: true
  31204. });
  31205. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31206. set: function (callback) {
  31207. if (this._onBeforeDrawObserver) {
  31208. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31209. }
  31210. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31211. },
  31212. enumerable: true,
  31213. configurable: true
  31214. });
  31215. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31216. get: function () {
  31217. return this._morphTargetManager;
  31218. },
  31219. set: function (value) {
  31220. if (this._morphTargetManager === value) {
  31221. return;
  31222. }
  31223. this._morphTargetManager = value;
  31224. this._syncGeometryWithMorphTargetManager();
  31225. },
  31226. enumerable: true,
  31227. configurable: true
  31228. });
  31229. Object.defineProperty(Mesh.prototype, "source", {
  31230. get: function () {
  31231. return this._source;
  31232. },
  31233. enumerable: true,
  31234. configurable: true
  31235. });
  31236. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31237. get: function () {
  31238. return this._unIndexed;
  31239. },
  31240. set: function (value) {
  31241. if (this._unIndexed !== value) {
  31242. this._unIndexed = value;
  31243. this._markSubMeshesAsAttributesDirty();
  31244. }
  31245. },
  31246. enumerable: true,
  31247. configurable: true
  31248. });
  31249. // Methods
  31250. /**
  31251. * Returns the string "Mesh".
  31252. */
  31253. Mesh.prototype.getClassName = function () {
  31254. return "Mesh";
  31255. };
  31256. /**
  31257. * Returns a string.
  31258. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31259. */
  31260. Mesh.prototype.toString = function (fullDetails) {
  31261. var ret = _super.prototype.toString.call(this, fullDetails);
  31262. ret += ", n vertices: " + this.getTotalVertices();
  31263. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31264. if (this.animations) {
  31265. for (var i = 0; i < this.animations.length; i++) {
  31266. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31267. }
  31268. }
  31269. if (fullDetails) {
  31270. if (this._geometry) {
  31271. var ib = this.getIndices();
  31272. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31273. if (vb && ib) {
  31274. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31275. }
  31276. }
  31277. else {
  31278. ret += ", flat shading: UNKNOWN";
  31279. }
  31280. }
  31281. return ret;
  31282. };
  31283. /** @hidden */
  31284. Mesh.prototype._unBindEffect = function () {
  31285. _super.prototype._unBindEffect.call(this);
  31286. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31287. var instance = _a[_i];
  31288. instance._unBindEffect();
  31289. }
  31290. };
  31291. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31292. /**
  31293. * True if the mesh has some Levels Of Details (LOD).
  31294. * Returns a boolean.
  31295. */
  31296. get: function () {
  31297. return this._LODLevels.length > 0;
  31298. },
  31299. enumerable: true,
  31300. configurable: true
  31301. });
  31302. /**
  31303. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31304. * @returns an array of {BABYLON.MeshLODLevel}
  31305. */
  31306. Mesh.prototype.getLODLevels = function () {
  31307. return this._LODLevels;
  31308. };
  31309. Mesh.prototype._sortLODLevels = function () {
  31310. this._LODLevels.sort(function (a, b) {
  31311. if (a.distance < b.distance) {
  31312. return 1;
  31313. }
  31314. if (a.distance > b.distance) {
  31315. return -1;
  31316. }
  31317. return 0;
  31318. });
  31319. };
  31320. /**
  31321. * Add a mesh as LOD level triggered at the given distance.
  31322. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31323. * @param distance The distance from the center of the object to show this level
  31324. * @param mesh The mesh to be added as LOD level (can be null)
  31325. * @return This mesh (for chaining)
  31326. */
  31327. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31328. if (mesh && mesh._masterMesh) {
  31329. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31330. return this;
  31331. }
  31332. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31333. this._LODLevels.push(level);
  31334. if (mesh) {
  31335. mesh._masterMesh = this;
  31336. }
  31337. this._sortLODLevels();
  31338. return this;
  31339. };
  31340. /**
  31341. * Returns the LOD level mesh at the passed distance or null if not found.
  31342. * It is related to the method `addLODLevel(distance, mesh)`.
  31343. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31344. * Returns an object Mesh or `null`.
  31345. */
  31346. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31347. for (var index = 0; index < this._LODLevels.length; index++) {
  31348. var level = this._LODLevels[index];
  31349. if (level.distance === distance) {
  31350. return level.mesh;
  31351. }
  31352. }
  31353. return null;
  31354. };
  31355. /**
  31356. * Remove a mesh from the LOD array
  31357. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31358. * @param {Mesh} mesh The mesh to be removed.
  31359. * @return {Mesh} This mesh (for chaining)
  31360. */
  31361. Mesh.prototype.removeLODLevel = function (mesh) {
  31362. for (var index = 0; index < this._LODLevels.length; index++) {
  31363. if (this._LODLevels[index].mesh === mesh) {
  31364. this._LODLevels.splice(index, 1);
  31365. if (mesh) {
  31366. mesh._masterMesh = null;
  31367. }
  31368. }
  31369. }
  31370. this._sortLODLevels();
  31371. return this;
  31372. };
  31373. /**
  31374. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31375. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31376. */
  31377. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31378. if (!this._LODLevels || this._LODLevels.length === 0) {
  31379. return this;
  31380. }
  31381. var bSphere;
  31382. if (boundingSphere) {
  31383. bSphere = boundingSphere;
  31384. }
  31385. else {
  31386. var boundingInfo = this.getBoundingInfo();
  31387. bSphere = boundingInfo.boundingSphere;
  31388. }
  31389. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31390. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31391. if (this.onLODLevelSelection) {
  31392. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31393. }
  31394. return this;
  31395. }
  31396. for (var index = 0; index < this._LODLevels.length; index++) {
  31397. var level = this._LODLevels[index];
  31398. if (level.distance < distanceToCamera) {
  31399. if (level.mesh) {
  31400. level.mesh._preActivate();
  31401. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31402. }
  31403. if (this.onLODLevelSelection) {
  31404. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31405. }
  31406. return level.mesh;
  31407. }
  31408. }
  31409. if (this.onLODLevelSelection) {
  31410. this.onLODLevelSelection(distanceToCamera, this, this);
  31411. }
  31412. return this;
  31413. };
  31414. Object.defineProperty(Mesh.prototype, "geometry", {
  31415. /**
  31416. * Returns the mesh internal Geometry object.
  31417. */
  31418. get: function () {
  31419. return this._geometry;
  31420. },
  31421. enumerable: true,
  31422. configurable: true
  31423. });
  31424. /**
  31425. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31426. */
  31427. Mesh.prototype.getTotalVertices = function () {
  31428. if (this._geometry === null || this._geometry === undefined) {
  31429. return 0;
  31430. }
  31431. return this._geometry.getTotalVertices();
  31432. };
  31433. /**
  31434. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31435. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31436. * You can force the copy with forceCopy === true
  31437. * Returns null if the mesh has no geometry or no vertex buffer.
  31438. * Possible `kind` values :
  31439. * - BABYLON.VertexBuffer.PositionKind
  31440. * - BABYLON.VertexBuffer.UVKind
  31441. * - BABYLON.VertexBuffer.UV2Kind
  31442. * - BABYLON.VertexBuffer.UV3Kind
  31443. * - BABYLON.VertexBuffer.UV4Kind
  31444. * - BABYLON.VertexBuffer.UV5Kind
  31445. * - BABYLON.VertexBuffer.UV6Kind
  31446. * - BABYLON.VertexBuffer.ColorKind
  31447. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31448. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31449. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31450. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31451. */
  31452. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31453. if (!this._geometry) {
  31454. return null;
  31455. }
  31456. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31457. };
  31458. /**
  31459. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31460. * Returns `null` if the mesh has no geometry.
  31461. * Possible `kind` values :
  31462. * - BABYLON.VertexBuffer.PositionKind
  31463. * - BABYLON.VertexBuffer.UVKind
  31464. * - BABYLON.VertexBuffer.UV2Kind
  31465. * - BABYLON.VertexBuffer.UV3Kind
  31466. * - BABYLON.VertexBuffer.UV4Kind
  31467. * - BABYLON.VertexBuffer.UV5Kind
  31468. * - BABYLON.VertexBuffer.UV6Kind
  31469. * - BABYLON.VertexBuffer.ColorKind
  31470. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31471. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31472. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31473. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31474. */
  31475. Mesh.prototype.getVertexBuffer = function (kind) {
  31476. if (!this._geometry) {
  31477. return null;
  31478. }
  31479. return this._geometry.getVertexBuffer(kind);
  31480. };
  31481. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31482. if (!this._geometry) {
  31483. if (this._delayInfo) {
  31484. return this._delayInfo.indexOf(kind) !== -1;
  31485. }
  31486. return false;
  31487. }
  31488. return this._geometry.isVerticesDataPresent(kind);
  31489. };
  31490. /**
  31491. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31492. * Possible `kind` values :
  31493. * - BABYLON.VertexBuffer.PositionKind
  31494. * - BABYLON.VertexBuffer.UVKind
  31495. * - BABYLON.VertexBuffer.UV2Kind
  31496. * - BABYLON.VertexBuffer.UV3Kind
  31497. * - BABYLON.VertexBuffer.UV4Kind
  31498. * - BABYLON.VertexBuffer.UV5Kind
  31499. * - BABYLON.VertexBuffer.UV6Kind
  31500. * - BABYLON.VertexBuffer.ColorKind
  31501. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31502. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31503. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31504. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31505. */
  31506. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31507. if (!this._geometry) {
  31508. if (this._delayInfo) {
  31509. return this._delayInfo.indexOf(kind) !== -1;
  31510. }
  31511. return false;
  31512. }
  31513. return this._geometry.isVertexBufferUpdatable(kind);
  31514. };
  31515. /**
  31516. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31517. * Possible `kind` values :
  31518. * - BABYLON.VertexBuffer.PositionKind
  31519. * - BABYLON.VertexBuffer.UVKind
  31520. * - BABYLON.VertexBuffer.UV2Kind
  31521. * - BABYLON.VertexBuffer.UV3Kind
  31522. * - BABYLON.VertexBuffer.UV4Kind
  31523. * - BABYLON.VertexBuffer.UV5Kind
  31524. * - BABYLON.VertexBuffer.UV6Kind
  31525. * - BABYLON.VertexBuffer.ColorKind
  31526. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31527. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31528. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31529. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31530. */
  31531. Mesh.prototype.getVerticesDataKinds = function () {
  31532. if (!this._geometry) {
  31533. var result = new Array();
  31534. if (this._delayInfo) {
  31535. this._delayInfo.forEach(function (kind, index, array) {
  31536. result.push(kind);
  31537. });
  31538. }
  31539. return result;
  31540. }
  31541. return this._geometry.getVerticesDataKinds();
  31542. };
  31543. /**
  31544. * Returns a positive integer : the total number of indices in this mesh geometry.
  31545. * Returns zero if the mesh has no geometry.
  31546. */
  31547. Mesh.prototype.getTotalIndices = function () {
  31548. if (!this._geometry) {
  31549. return 0;
  31550. }
  31551. return this._geometry.getTotalIndices();
  31552. };
  31553. /**
  31554. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31555. * @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.
  31556. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31557. * @returns the indices array or an empty array if the mesh has no geometry
  31558. */
  31559. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31560. if (!this._geometry) {
  31561. return [];
  31562. }
  31563. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31564. };
  31565. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31566. get: function () {
  31567. return this._masterMesh !== null && this._masterMesh !== undefined;
  31568. },
  31569. enumerable: true,
  31570. configurable: true
  31571. });
  31572. /**
  31573. * Determine if the current mesh is ready to be rendered
  31574. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31575. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31576. * @returns true if all associated assets are ready (material, textures, shaders)
  31577. */
  31578. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31579. if (completeCheck === void 0) { completeCheck = false; }
  31580. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31581. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31582. return false;
  31583. }
  31584. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31585. return false;
  31586. }
  31587. if (!this.subMeshes || this.subMeshes.length === 0) {
  31588. return true;
  31589. }
  31590. if (!completeCheck) {
  31591. return true;
  31592. }
  31593. var engine = this.getEngine();
  31594. var scene = this.getScene();
  31595. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31596. this.computeWorldMatrix();
  31597. var mat = this.material || scene.defaultMaterial;
  31598. if (mat) {
  31599. if (mat.storeEffectOnSubMeshes) {
  31600. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31601. var subMesh = _a[_i];
  31602. var effectiveMaterial = subMesh.getMaterial();
  31603. if (effectiveMaterial) {
  31604. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31605. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31606. return false;
  31607. }
  31608. }
  31609. else {
  31610. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31611. return false;
  31612. }
  31613. }
  31614. }
  31615. }
  31616. }
  31617. else {
  31618. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31619. return false;
  31620. }
  31621. }
  31622. }
  31623. // Shadows
  31624. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31625. var light = _c[_b];
  31626. var generator = light.getShadowGenerator();
  31627. if (generator) {
  31628. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31629. var subMesh = _e[_d];
  31630. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31631. return false;
  31632. }
  31633. }
  31634. }
  31635. }
  31636. // LOD
  31637. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31638. var lod = _g[_f];
  31639. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31640. return false;
  31641. }
  31642. }
  31643. return true;
  31644. };
  31645. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31646. /**
  31647. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31648. * This property is pertinent only for updatable parametric shapes.
  31649. */
  31650. get: function () {
  31651. return this._areNormalsFrozen;
  31652. },
  31653. enumerable: true,
  31654. configurable: true
  31655. });
  31656. /**
  31657. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31658. * It has no effect at all on other shapes.
  31659. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31660. * Returns the Mesh.
  31661. */
  31662. Mesh.prototype.freezeNormals = function () {
  31663. this._areNormalsFrozen = true;
  31664. return this;
  31665. };
  31666. /**
  31667. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31668. * It has no effect at all on other shapes.
  31669. * It reactivates the mesh normals computation if it was previously frozen.
  31670. * Returns the Mesh.
  31671. */
  31672. Mesh.prototype.unfreezeNormals = function () {
  31673. this._areNormalsFrozen = false;
  31674. return this;
  31675. };
  31676. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31677. /**
  31678. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31679. */
  31680. set: function (count) {
  31681. this._overridenInstanceCount = count;
  31682. },
  31683. enumerable: true,
  31684. configurable: true
  31685. });
  31686. // Methods
  31687. /** @hidden */
  31688. Mesh.prototype._preActivate = function () {
  31689. var sceneRenderId = this.getScene().getRenderId();
  31690. if (this._preActivateId === sceneRenderId) {
  31691. return this;
  31692. }
  31693. this._preActivateId = sceneRenderId;
  31694. this._visibleInstances = null;
  31695. return this;
  31696. };
  31697. /** @hidden */
  31698. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31699. if (this._visibleInstances) {
  31700. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31701. }
  31702. return this;
  31703. };
  31704. /** @hidden */
  31705. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31706. if (!this._visibleInstances) {
  31707. this._visibleInstances = {};
  31708. this._visibleInstances.defaultRenderId = renderId;
  31709. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31710. }
  31711. if (!this._visibleInstances[renderId]) {
  31712. this._visibleInstances[renderId] = new Array();
  31713. }
  31714. this._visibleInstances[renderId].push(instance);
  31715. return this;
  31716. };
  31717. /**
  31718. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31719. * This means the mesh underlying bounding box and sphere are recomputed.
  31720. * Returns the Mesh.
  31721. */
  31722. Mesh.prototype.refreshBoundingInfo = function () {
  31723. return this._refreshBoundingInfo(false);
  31724. };
  31725. /** @hidden */
  31726. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31727. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31728. return this;
  31729. }
  31730. var data = this._getPositionData(applySkeleton);
  31731. if (data) {
  31732. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31733. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31734. }
  31735. if (this.subMeshes) {
  31736. for (var index = 0; index < this.subMeshes.length; index++) {
  31737. this.subMeshes[index].refreshBoundingInfo();
  31738. }
  31739. }
  31740. this._updateBoundingInfo();
  31741. return this;
  31742. };
  31743. Mesh.prototype._getPositionData = function (applySkeleton) {
  31744. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31745. if (data && applySkeleton && this.skeleton) {
  31746. data = BABYLON.Tools.Slice(data);
  31747. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31748. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31749. if (matricesWeightsData && matricesIndicesData) {
  31750. var needExtras = this.numBoneInfluencers > 4;
  31751. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31752. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31753. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31754. var tempVector = BABYLON.Tmp.Vector3[0];
  31755. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31756. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31757. var matWeightIdx = 0;
  31758. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31759. finalMatrix.reset();
  31760. var inf;
  31761. var weight;
  31762. for (inf = 0; inf < 4; inf++) {
  31763. weight = matricesWeightsData[matWeightIdx + inf];
  31764. if (weight > 0) {
  31765. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31766. finalMatrix.addToSelf(tempMatrix);
  31767. }
  31768. }
  31769. if (needExtras) {
  31770. for (inf = 0; inf < 4; inf++) {
  31771. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31772. if (weight > 0) {
  31773. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31774. finalMatrix.addToSelf(tempMatrix);
  31775. }
  31776. }
  31777. }
  31778. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31779. tempVector.toArray(data, index);
  31780. }
  31781. }
  31782. }
  31783. return data;
  31784. };
  31785. /** @hidden */
  31786. Mesh.prototype._createGlobalSubMesh = function (force) {
  31787. var totalVertices = this.getTotalVertices();
  31788. if (!totalVertices || !this.getIndices()) {
  31789. return null;
  31790. }
  31791. // Check if we need to recreate the submeshes
  31792. if (this.subMeshes && this.subMeshes.length > 0) {
  31793. var ib = this.getIndices();
  31794. if (!ib) {
  31795. return null;
  31796. }
  31797. var totalIndices = ib.length;
  31798. var needToRecreate = false;
  31799. if (force) {
  31800. needToRecreate = true;
  31801. }
  31802. else {
  31803. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31804. var submesh = _a[_i];
  31805. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31806. needToRecreate = true;
  31807. break;
  31808. }
  31809. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31810. needToRecreate = true;
  31811. break;
  31812. }
  31813. }
  31814. }
  31815. if (!needToRecreate) {
  31816. return this.subMeshes[0];
  31817. }
  31818. }
  31819. this.releaseSubMeshes();
  31820. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31821. };
  31822. Mesh.prototype.subdivide = function (count) {
  31823. if (count < 1) {
  31824. return;
  31825. }
  31826. var totalIndices = this.getTotalIndices();
  31827. var subdivisionSize = (totalIndices / count) | 0;
  31828. var offset = 0;
  31829. // Ensure that subdivisionSize is a multiple of 3
  31830. while (subdivisionSize % 3 !== 0) {
  31831. subdivisionSize++;
  31832. }
  31833. this.releaseSubMeshes();
  31834. for (var index = 0; index < count; index++) {
  31835. if (offset >= totalIndices) {
  31836. break;
  31837. }
  31838. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31839. offset += subdivisionSize;
  31840. }
  31841. this.synchronizeInstances();
  31842. };
  31843. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31844. if (updatable === void 0) { updatable = false; }
  31845. if (!this._geometry) {
  31846. var vertexData = new BABYLON.VertexData();
  31847. vertexData.set(data, kind);
  31848. var scene = this.getScene();
  31849. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31850. }
  31851. else {
  31852. this._geometry.setVerticesData(kind, data, updatable, stride);
  31853. }
  31854. return this;
  31855. };
  31856. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31857. if (updatable === void 0) { updatable = true; }
  31858. var vb = this.getVertexBuffer(kind);
  31859. if (!vb || vb.isUpdatable() === updatable) {
  31860. return;
  31861. }
  31862. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31863. };
  31864. /**
  31865. * Sets the mesh VertexBuffer.
  31866. * Returns the Mesh.
  31867. */
  31868. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31869. if (!this._geometry) {
  31870. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31871. }
  31872. this._geometry.setVerticesBuffer(buffer);
  31873. return this;
  31874. };
  31875. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31876. if (!this._geometry) {
  31877. return this;
  31878. }
  31879. if (!makeItUnique) {
  31880. this._geometry.updateVerticesData(kind, data, updateExtends);
  31881. }
  31882. else {
  31883. this.makeGeometryUnique();
  31884. this.updateVerticesData(kind, data, updateExtends, false);
  31885. }
  31886. return this;
  31887. };
  31888. /**
  31889. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31890. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31891. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31892. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31893. * Returns the Mesh.
  31894. */
  31895. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31896. if (computeNormals === void 0) { computeNormals = true; }
  31897. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31898. if (!positions) {
  31899. return this;
  31900. }
  31901. positionFunction(positions);
  31902. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31903. if (computeNormals) {
  31904. var indices = this.getIndices();
  31905. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31906. if (!normals) {
  31907. return this;
  31908. }
  31909. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31910. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31911. }
  31912. return this;
  31913. };
  31914. /**
  31915. * Creates a un-shared specific occurence of the geometry for the mesh.
  31916. * Returns the Mesh.
  31917. */
  31918. Mesh.prototype.makeGeometryUnique = function () {
  31919. if (!this._geometry) {
  31920. return this;
  31921. }
  31922. var oldGeometry = this._geometry;
  31923. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31924. oldGeometry.releaseForMesh(this, true);
  31925. geometry.applyToMesh(this);
  31926. return this;
  31927. };
  31928. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31929. if (totalVertices === void 0) { totalVertices = null; }
  31930. if (updatable === void 0) { updatable = false; }
  31931. if (!this._geometry) {
  31932. var vertexData = new BABYLON.VertexData();
  31933. vertexData.indices = indices;
  31934. var scene = this.getScene();
  31935. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31936. }
  31937. else {
  31938. this._geometry.setIndices(indices, totalVertices, updatable);
  31939. }
  31940. return this;
  31941. };
  31942. /**
  31943. * Update the current index buffer
  31944. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31945. * Returns the Mesh.
  31946. */
  31947. Mesh.prototype.updateIndices = function (indices, offset) {
  31948. if (!this._geometry) {
  31949. return this;
  31950. }
  31951. this._geometry.updateIndices(indices, offset);
  31952. return this;
  31953. };
  31954. /**
  31955. * Invert the geometry to move from a right handed system to a left handed one.
  31956. * Returns the Mesh.
  31957. */
  31958. Mesh.prototype.toLeftHanded = function () {
  31959. if (!this._geometry) {
  31960. return this;
  31961. }
  31962. this._geometry.toLeftHanded();
  31963. return this;
  31964. };
  31965. /** @hidden */
  31966. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31967. if (!this._geometry) {
  31968. return this;
  31969. }
  31970. var engine = this.getScene().getEngine();
  31971. // Wireframe
  31972. var indexToBind;
  31973. if (this._unIndexed) {
  31974. indexToBind = null;
  31975. }
  31976. else {
  31977. switch (fillMode) {
  31978. case BABYLON.Material.PointFillMode:
  31979. indexToBind = null;
  31980. break;
  31981. case BABYLON.Material.WireFrameFillMode:
  31982. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31983. break;
  31984. default:
  31985. case BABYLON.Material.TriangleFillMode:
  31986. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31987. break;
  31988. }
  31989. }
  31990. // VBOs
  31991. this._geometry._bind(effect, indexToBind);
  31992. return this;
  31993. };
  31994. /** @hidden */
  31995. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31996. if (alternate === void 0) { alternate = false; }
  31997. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31998. return this;
  31999. }
  32000. if (this._onBeforeDrawObservable) {
  32001. this._onBeforeDrawObservable.notifyObservers(this);
  32002. }
  32003. var scene = this.getScene();
  32004. var engine = scene.getEngine();
  32005. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32006. // or triangles as points
  32007. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32008. }
  32009. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32010. // Triangles as wireframe
  32011. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32012. }
  32013. else {
  32014. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32015. }
  32016. if (scene._isAlternateRenderingEnabled && !alternate) {
  32017. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32018. if (!effect || !scene.activeCamera) {
  32019. return this;
  32020. }
  32021. scene._switchToAlternateCameraConfiguration(true);
  32022. this._effectiveMaterial.bindView(effect);
  32023. this._effectiveMaterial.bindViewProjection(effect);
  32024. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32025. this._draw(subMesh, fillMode, instancesCount, true);
  32026. engine.setViewport(scene.activeCamera.viewport);
  32027. scene._switchToAlternateCameraConfiguration(false);
  32028. this._effectiveMaterial.bindView(effect);
  32029. this._effectiveMaterial.bindViewProjection(effect);
  32030. }
  32031. return this;
  32032. };
  32033. /**
  32034. * Registers for this mesh a javascript function called just before the rendering process.
  32035. * This function is passed the current mesh.
  32036. * Return the Mesh.
  32037. */
  32038. Mesh.prototype.registerBeforeRender = function (func) {
  32039. this.onBeforeRenderObservable.add(func);
  32040. return this;
  32041. };
  32042. /**
  32043. * Disposes a previously registered javascript function called before the rendering.
  32044. * This function is passed the current mesh.
  32045. * Returns the Mesh.
  32046. */
  32047. Mesh.prototype.unregisterBeforeRender = function (func) {
  32048. this.onBeforeRenderObservable.removeCallback(func);
  32049. return this;
  32050. };
  32051. /**
  32052. * Registers for this mesh a javascript function called just after the rendering is complete.
  32053. * This function is passed the current mesh.
  32054. * Returns the Mesh.
  32055. */
  32056. Mesh.prototype.registerAfterRender = function (func) {
  32057. this.onAfterRenderObservable.add(func);
  32058. return this;
  32059. };
  32060. /**
  32061. * Disposes a previously registered javascript function called after the rendering.
  32062. * This function is passed the current mesh.
  32063. * Return the Mesh.
  32064. */
  32065. Mesh.prototype.unregisterAfterRender = function (func) {
  32066. this.onAfterRenderObservable.removeCallback(func);
  32067. return this;
  32068. };
  32069. /** @hidden */
  32070. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32071. var scene = this.getScene();
  32072. this._batchCache.mustReturn = false;
  32073. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32074. this._batchCache.visibleInstances[subMeshId] = null;
  32075. if (this._visibleInstances) {
  32076. var currentRenderId = scene.getRenderId();
  32077. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32078. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32079. var selfRenderId = this._renderId;
  32080. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32081. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32082. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32083. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32084. }
  32085. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32086. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32087. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32088. this._batchCache.mustReturn = true;
  32089. return this._batchCache;
  32090. }
  32091. if (currentRenderId !== selfRenderId) {
  32092. this._batchCache.renderSelf[subMeshId] = false;
  32093. }
  32094. }
  32095. this._renderIdForInstances[subMeshId] = currentRenderId;
  32096. }
  32097. return this._batchCache;
  32098. };
  32099. /** @hidden */
  32100. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32101. var visibleInstances = batch.visibleInstances[subMesh._id];
  32102. if (!visibleInstances) {
  32103. return this;
  32104. }
  32105. var matricesCount = visibleInstances.length + 1;
  32106. var bufferSize = matricesCount * 16 * 4;
  32107. var currentInstancesBufferSize = this._instancesBufferSize;
  32108. var instancesBuffer = this._instancesBuffer;
  32109. while (this._instancesBufferSize < bufferSize) {
  32110. this._instancesBufferSize *= 2;
  32111. }
  32112. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32113. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32114. }
  32115. var offset = 0;
  32116. var instancesCount = 0;
  32117. var world = this.getWorldMatrix();
  32118. if (batch.renderSelf[subMesh._id]) {
  32119. world.copyToArray(this._instancesData, offset);
  32120. offset += 16;
  32121. instancesCount++;
  32122. }
  32123. if (visibleInstances) {
  32124. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32125. var instance = visibleInstances[instanceIndex];
  32126. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32127. offset += 16;
  32128. instancesCount++;
  32129. }
  32130. }
  32131. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32132. if (instancesBuffer) {
  32133. instancesBuffer.dispose();
  32134. }
  32135. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32136. this._instancesBuffer = instancesBuffer;
  32137. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32138. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32139. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32140. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32141. }
  32142. else {
  32143. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32144. }
  32145. this._bind(subMesh, effect, fillMode);
  32146. this._draw(subMesh, fillMode, instancesCount);
  32147. engine.unbindInstanceAttributes();
  32148. return this;
  32149. };
  32150. /** @hidden */
  32151. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32152. var scene = this.getScene();
  32153. var engine = scene.getEngine();
  32154. if (hardwareInstancedRendering) {
  32155. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32156. }
  32157. else {
  32158. if (batch.renderSelf[subMesh._id]) {
  32159. // Draw
  32160. if (onBeforeDraw) {
  32161. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32162. }
  32163. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32164. }
  32165. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32166. if (visibleInstancesForSubMesh) {
  32167. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32168. var instance = visibleInstancesForSubMesh[instanceIndex];
  32169. // World
  32170. var world = instance.getWorldMatrix();
  32171. if (onBeforeDraw) {
  32172. onBeforeDraw(true, world, effectiveMaterial);
  32173. }
  32174. // Draw
  32175. this._draw(subMesh, fillMode);
  32176. }
  32177. }
  32178. }
  32179. return this;
  32180. };
  32181. /**
  32182. * 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
  32183. * @param subMesh defines the subMesh to render
  32184. * @param enableAlphaMode defines if alpha mode can be changed
  32185. * @returns the current mesh
  32186. */
  32187. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32188. this._checkOcclusionQuery();
  32189. if (this._isOccluded) {
  32190. return this;
  32191. }
  32192. var scene = this.getScene();
  32193. // Managing instances
  32194. var batch = this._getInstancesRenderList(subMesh._id);
  32195. if (batch.mustReturn) {
  32196. return this;
  32197. }
  32198. // Checking geometry state
  32199. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32200. return this;
  32201. }
  32202. if (this._onBeforeRenderObservable) {
  32203. this._onBeforeRenderObservable.notifyObservers(this);
  32204. }
  32205. var engine = scene.getEngine();
  32206. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32207. // Material
  32208. var material = subMesh.getMaterial();
  32209. if (!material) {
  32210. return this;
  32211. }
  32212. this._effectiveMaterial = material;
  32213. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32214. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32215. return this;
  32216. }
  32217. }
  32218. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32219. return this;
  32220. }
  32221. // Alpha mode
  32222. if (enableAlphaMode) {
  32223. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32224. }
  32225. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32226. var step = _a[_i];
  32227. step.action(this, subMesh, batch);
  32228. }
  32229. var effect;
  32230. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32231. effect = subMesh.effect;
  32232. }
  32233. else {
  32234. effect = this._effectiveMaterial.getEffect();
  32235. }
  32236. if (!effect) {
  32237. return this;
  32238. }
  32239. var sideOrientation = this.overrideMaterialSideOrientation;
  32240. if (sideOrientation == null) {
  32241. sideOrientation = this._effectiveMaterial.sideOrientation;
  32242. if (this._getWorldMatrixDeterminant() < 0) {
  32243. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32244. }
  32245. }
  32246. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32247. if (this._effectiveMaterial.forceDepthWrite) {
  32248. engine.setDepthWrite(true);
  32249. }
  32250. // Bind
  32251. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32252. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32253. this._bind(subMesh, effect, fillMode);
  32254. }
  32255. var world = this.getWorldMatrix();
  32256. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32257. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32258. }
  32259. else {
  32260. this._effectiveMaterial.bind(world, this);
  32261. }
  32262. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32263. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32264. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32265. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32266. }
  32267. // Draw
  32268. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32269. // Unbind
  32270. this._effectiveMaterial.unbind();
  32271. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32272. var step = _c[_b];
  32273. step.action(this, subMesh, batch);
  32274. }
  32275. if (this._onAfterRenderObservable) {
  32276. this._onAfterRenderObservable.notifyObservers(this);
  32277. }
  32278. return this;
  32279. };
  32280. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32281. if (isInstance && effectiveMaterial) {
  32282. effectiveMaterial.bindOnlyWorldMatrix(world);
  32283. }
  32284. };
  32285. /**
  32286. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32287. */
  32288. Mesh.prototype.getEmittedParticleSystems = function () {
  32289. var results = new Array();
  32290. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32291. var particleSystem = this.getScene().particleSystems[index];
  32292. if (particleSystem.emitter === this) {
  32293. results.push(particleSystem);
  32294. }
  32295. }
  32296. return results;
  32297. };
  32298. /**
  32299. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32300. */
  32301. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32302. var results = new Array();
  32303. var descendants = this.getDescendants();
  32304. descendants.push(this);
  32305. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32306. var particleSystem = this.getScene().particleSystems[index];
  32307. var emitter = particleSystem.emitter;
  32308. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32309. results.push(particleSystem);
  32310. }
  32311. }
  32312. return results;
  32313. };
  32314. /**
  32315. * Normalize matrix weights so that all vertices have a total weight set to 1
  32316. */
  32317. Mesh.prototype.cleanMatrixWeights = function () {
  32318. var epsilon = 1e-3;
  32319. var noInfluenceBoneIndex = 0.0;
  32320. if (this.skeleton) {
  32321. noInfluenceBoneIndex = this.skeleton.bones.length;
  32322. }
  32323. else {
  32324. return;
  32325. }
  32326. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32327. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32328. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32329. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32330. var influencers = this.numBoneInfluencers;
  32331. var size = matricesWeights.length;
  32332. for (var i = 0; i < size; i += 4) {
  32333. var weight = 0.0;
  32334. var firstZeroWeight = -1;
  32335. for (var j = 0; j < 4; j++) {
  32336. var w = matricesWeights[i + j];
  32337. weight += w;
  32338. if (w < epsilon && firstZeroWeight < 0) {
  32339. firstZeroWeight = j;
  32340. }
  32341. }
  32342. if (matricesWeightsExtra) {
  32343. for (var j = 0; j < 4; j++) {
  32344. var w = matricesWeightsExtra[i + j];
  32345. weight += w;
  32346. if (w < epsilon && firstZeroWeight < 0) {
  32347. firstZeroWeight = j + 4;
  32348. }
  32349. }
  32350. }
  32351. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32352. firstZeroWeight = influencers - 1;
  32353. }
  32354. if (weight > epsilon) {
  32355. var mweight = 1.0 / weight;
  32356. for (var j = 0; j < 4; j++) {
  32357. matricesWeights[i + j] *= mweight;
  32358. }
  32359. if (matricesWeightsExtra) {
  32360. for (var j = 0; j < 4; j++) {
  32361. matricesWeightsExtra[i + j] *= mweight;
  32362. }
  32363. }
  32364. }
  32365. else {
  32366. if (firstZeroWeight >= 4) {
  32367. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32368. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32369. }
  32370. else {
  32371. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32372. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32373. }
  32374. }
  32375. }
  32376. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32377. if (matricesIndicesExtra) {
  32378. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32379. }
  32380. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32381. if (matricesWeightsExtra) {
  32382. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32383. }
  32384. };
  32385. /** @hidden */
  32386. Mesh.prototype._checkDelayState = function () {
  32387. var scene = this.getScene();
  32388. if (this._geometry) {
  32389. this._geometry.load(scene);
  32390. }
  32391. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32392. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32393. this._queueLoad(scene);
  32394. }
  32395. return this;
  32396. };
  32397. Mesh.prototype._queueLoad = function (scene) {
  32398. var _this = this;
  32399. scene._addPendingData(this);
  32400. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32401. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32402. if (data instanceof ArrayBuffer) {
  32403. _this._delayLoadingFunction(data, _this);
  32404. }
  32405. else {
  32406. _this._delayLoadingFunction(JSON.parse(data), _this);
  32407. }
  32408. _this.instances.forEach(function (instance) {
  32409. instance._syncSubMeshes();
  32410. });
  32411. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32412. scene._removePendingData(_this);
  32413. }, function () { }, scene.database, getBinaryData);
  32414. return this;
  32415. };
  32416. /**
  32417. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32418. * A mesh is in the frustum if its bounding box intersects the frustum
  32419. * @param frustumPlanes defines the frustum to test
  32420. * @returns true if the mesh is in the frustum planes
  32421. */
  32422. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32423. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32424. return false;
  32425. }
  32426. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32427. return false;
  32428. }
  32429. this._checkDelayState();
  32430. return true;
  32431. };
  32432. /**
  32433. * Sets the mesh material by the material or multiMaterial `id` property.
  32434. * The material `id` is a string identifying the material or the multiMaterial.
  32435. * This method returns the Mesh.
  32436. */
  32437. Mesh.prototype.setMaterialByID = function (id) {
  32438. var materials = this.getScene().materials;
  32439. var index;
  32440. for (index = materials.length - 1; index > -1; index--) {
  32441. if (materials[index].id === id) {
  32442. this.material = materials[index];
  32443. return this;
  32444. }
  32445. }
  32446. // Multi
  32447. var multiMaterials = this.getScene().multiMaterials;
  32448. for (index = multiMaterials.length - 1; index > -1; index--) {
  32449. if (multiMaterials[index].id === id) {
  32450. this.material = multiMaterials[index];
  32451. return this;
  32452. }
  32453. }
  32454. return this;
  32455. };
  32456. /**
  32457. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32458. */
  32459. Mesh.prototype.getAnimatables = function () {
  32460. var results = new Array();
  32461. if (this.material) {
  32462. results.push(this.material);
  32463. }
  32464. if (this.skeleton) {
  32465. results.push(this.skeleton);
  32466. }
  32467. return results;
  32468. };
  32469. /**
  32470. * Modifies the mesh geometry according to the passed transformation matrix.
  32471. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32472. * The mesh normals are modified using the same transformation.
  32473. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32474. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32475. * Returns the Mesh.
  32476. */
  32477. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32478. // Position
  32479. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32480. return this;
  32481. }
  32482. var submeshes = this.subMeshes.splice(0);
  32483. this._resetPointsArrayCache();
  32484. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32485. var temp = new Array();
  32486. var index;
  32487. for (index = 0; index < data.length; index += 3) {
  32488. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32489. }
  32490. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32491. // Normals
  32492. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32493. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32494. temp = [];
  32495. for (index = 0; index < data.length; index += 3) {
  32496. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32497. }
  32498. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32499. }
  32500. // flip faces?
  32501. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32502. this.flipFaces();
  32503. }
  32504. // Restore submeshes
  32505. this.releaseSubMeshes();
  32506. this.subMeshes = submeshes;
  32507. return this;
  32508. };
  32509. /**
  32510. * Modifies the mesh geometry according to its own current World Matrix.
  32511. * The mesh World Matrix is then reset.
  32512. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32513. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32514. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32515. * Returns the Mesh.
  32516. */
  32517. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32518. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32519. this.scaling.copyFromFloats(1, 1, 1);
  32520. this.position.copyFromFloats(0, 0, 0);
  32521. this.rotation.copyFromFloats(0, 0, 0);
  32522. //only if quaternion is already set
  32523. if (this.rotationQuaternion) {
  32524. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32525. }
  32526. this._worldMatrix = BABYLON.Matrix.Identity();
  32527. return this;
  32528. };
  32529. Object.defineProperty(Mesh.prototype, "_positions", {
  32530. // Cache
  32531. get: function () {
  32532. if (this._geometry) {
  32533. return this._geometry._positions;
  32534. }
  32535. return null;
  32536. },
  32537. enumerable: true,
  32538. configurable: true
  32539. });
  32540. /** @hidden */
  32541. Mesh.prototype._resetPointsArrayCache = function () {
  32542. if (this._geometry) {
  32543. this._geometry._resetPointsArrayCache();
  32544. }
  32545. return this;
  32546. };
  32547. /** @hidden */
  32548. Mesh.prototype._generatePointsArray = function () {
  32549. if (this._geometry) {
  32550. return this._geometry._generatePointsArray();
  32551. }
  32552. return false;
  32553. };
  32554. /**
  32555. * Returns a new Mesh object generated from the current mesh properties.
  32556. * This method must not get confused with createInstance().
  32557. * The parameter `name` is a string, the name given to the new mesh.
  32558. * The optional parameter `newParent` can be any Node object (default `null`).
  32559. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32560. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  32561. */
  32562. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32563. if (name === void 0) { name = ""; }
  32564. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32565. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32566. };
  32567. /**
  32568. * Releases resources associated with this mesh.
  32569. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32570. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32571. */
  32572. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32573. var _this = this;
  32574. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32575. this.morphTargetManager = null;
  32576. if (this._geometry) {
  32577. this._geometry.releaseForMesh(this, true);
  32578. }
  32579. if (this._onBeforeDrawObservable) {
  32580. this._onBeforeDrawObservable.clear();
  32581. }
  32582. if (this._onBeforeRenderObservable) {
  32583. this._onBeforeRenderObservable.clear();
  32584. }
  32585. if (this._onAfterRenderObservable) {
  32586. this._onAfterRenderObservable.clear();
  32587. }
  32588. // Sources
  32589. var meshes = this.getScene().meshes;
  32590. meshes.forEach(function (abstractMesh) {
  32591. var mesh = abstractMesh;
  32592. if (mesh._source && mesh._source === _this) {
  32593. mesh._source = null;
  32594. }
  32595. });
  32596. this._source = null;
  32597. // Instances
  32598. if (this._instancesBuffer) {
  32599. this._instancesBuffer.dispose();
  32600. this._instancesBuffer = null;
  32601. }
  32602. while (this.instances.length) {
  32603. this.instances[0].dispose();
  32604. }
  32605. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32606. };
  32607. /**
  32608. * Modifies the mesh geometry according to a displacement map.
  32609. * 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.
  32610. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32611. * This method returns nothing.
  32612. * @param url is a string, the URL from the image file is to be downloaded.
  32613. * @param minHeight is the lower limit of the displacement.
  32614. * @param maxHeight is the upper limit of the displacement.
  32615. * @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.
  32616. * @param uvOffset is an optional vector2 used to offset UV.
  32617. * @param uvScale is an optional vector2 used to scale UV.
  32618. * @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.
  32619. * @returns the Mesh.
  32620. */
  32621. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32622. var _this = this;
  32623. if (forceUpdate === void 0) { forceUpdate = false; }
  32624. var scene = this.getScene();
  32625. var onload = function (img) {
  32626. // Getting height map data
  32627. var canvas = document.createElement("canvas");
  32628. var context = canvas.getContext("2d");
  32629. var heightMapWidth = img.width;
  32630. var heightMapHeight = img.height;
  32631. canvas.width = heightMapWidth;
  32632. canvas.height = heightMapHeight;
  32633. context.drawImage(img, 0, 0);
  32634. // Create VertexData from map data
  32635. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32636. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32637. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32638. //execute success callback, if set
  32639. if (onSuccess) {
  32640. onSuccess(_this);
  32641. }
  32642. };
  32643. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32644. return this;
  32645. };
  32646. /**
  32647. * Modifies the mesh geometry according to a displacementMap buffer.
  32648. * 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.
  32649. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32650. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32651. * @param heightMapWidth is the width of the buffer image.
  32652. * @param heightMapHeight is the height of the buffer image.
  32653. * @param minHeight is the lower limit of the displacement.
  32654. * @param maxHeight is the upper limit of the displacement.
  32655. * @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.
  32656. * @param uvOffset is an optional vector2 used to offset UV.
  32657. * @param uvScale is an optional vector2 used to scale UV.
  32658. * @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.
  32659. * @returns the Mesh.
  32660. */
  32661. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32662. if (forceUpdate === void 0) { forceUpdate = false; }
  32663. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32664. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32665. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32666. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32667. return this;
  32668. }
  32669. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32670. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32671. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32672. var position = BABYLON.Vector3.Zero();
  32673. var normal = BABYLON.Vector3.Zero();
  32674. var uv = BABYLON.Vector2.Zero();
  32675. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32676. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32677. for (var index = 0; index < positions.length; index += 3) {
  32678. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32679. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32680. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32681. // Compute height
  32682. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32683. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32684. var pos = (u + v * heightMapWidth) * 4;
  32685. var r = buffer[pos] / 255.0;
  32686. var g = buffer[pos + 1] / 255.0;
  32687. var b = buffer[pos + 2] / 255.0;
  32688. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32689. normal.normalize();
  32690. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32691. position = position.add(normal);
  32692. position.toArray(positions, index);
  32693. }
  32694. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32695. if (forceUpdate) {
  32696. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32697. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32698. }
  32699. else {
  32700. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32701. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32702. }
  32703. return this;
  32704. };
  32705. /**
  32706. * Modify the mesh to get a flat shading rendering.
  32707. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32708. * This method returns the Mesh.
  32709. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32710. */
  32711. Mesh.prototype.convertToFlatShadedMesh = function () {
  32712. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32713. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32714. var kinds = this.getVerticesDataKinds();
  32715. var vbs = {};
  32716. var data = {};
  32717. var newdata = {};
  32718. var updatableNormals = false;
  32719. var kindIndex;
  32720. var kind;
  32721. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32722. kind = kinds[kindIndex];
  32723. var vertexBuffer = this.getVertexBuffer(kind);
  32724. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32725. updatableNormals = vertexBuffer.isUpdatable();
  32726. kinds.splice(kindIndex, 1);
  32727. kindIndex--;
  32728. continue;
  32729. }
  32730. vbs[kind] = vertexBuffer;
  32731. data[kind] = vbs[kind].getData();
  32732. newdata[kind] = [];
  32733. }
  32734. // Save previous submeshes
  32735. var previousSubmeshes = this.subMeshes.slice(0);
  32736. var indices = this.getIndices();
  32737. var totalIndices = this.getTotalIndices();
  32738. // Generating unique vertices per face
  32739. var index;
  32740. for (index = 0; index < totalIndices; index++) {
  32741. var vertexIndex = indices[index];
  32742. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32743. kind = kinds[kindIndex];
  32744. var stride = vbs[kind].getStrideSize();
  32745. for (var offset = 0; offset < stride; offset++) {
  32746. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32747. }
  32748. }
  32749. }
  32750. // Updating faces & normal
  32751. var normals = [];
  32752. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32753. for (index = 0; index < totalIndices; index += 3) {
  32754. indices[index] = index;
  32755. indices[index + 1] = index + 1;
  32756. indices[index + 2] = index + 2;
  32757. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32758. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32759. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32760. var p1p2 = p1.subtract(p2);
  32761. var p3p2 = p3.subtract(p2);
  32762. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32763. // Store same normals for every vertex
  32764. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32765. normals.push(normal.x);
  32766. normals.push(normal.y);
  32767. normals.push(normal.z);
  32768. }
  32769. }
  32770. this.setIndices(indices);
  32771. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32772. // Updating vertex buffers
  32773. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32774. kind = kinds[kindIndex];
  32775. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32776. }
  32777. // Updating submeshes
  32778. this.releaseSubMeshes();
  32779. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32780. var previousOne = previousSubmeshes[submeshIndex];
  32781. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32782. }
  32783. this.synchronizeInstances();
  32784. return this;
  32785. };
  32786. /**
  32787. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32788. * In other words, more vertices, no more indices and a single bigger VBO.
  32789. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32790. * Returns the Mesh.
  32791. */
  32792. Mesh.prototype.convertToUnIndexedMesh = function () {
  32793. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32794. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32795. var kinds = this.getVerticesDataKinds();
  32796. var vbs = {};
  32797. var data = {};
  32798. var newdata = {};
  32799. var kindIndex;
  32800. var kind;
  32801. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32802. kind = kinds[kindIndex];
  32803. var vertexBuffer = this.getVertexBuffer(kind);
  32804. vbs[kind] = vertexBuffer;
  32805. data[kind] = vbs[kind].getData();
  32806. newdata[kind] = [];
  32807. }
  32808. // Save previous submeshes
  32809. var previousSubmeshes = this.subMeshes.slice(0);
  32810. var indices = this.getIndices();
  32811. var totalIndices = this.getTotalIndices();
  32812. // Generating unique vertices per face
  32813. var index;
  32814. for (index = 0; index < totalIndices; index++) {
  32815. var vertexIndex = indices[index];
  32816. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32817. kind = kinds[kindIndex];
  32818. var stride = vbs[kind].getStrideSize();
  32819. for (var offset = 0; offset < stride; offset++) {
  32820. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32821. }
  32822. }
  32823. }
  32824. // Updating indices
  32825. for (index = 0; index < totalIndices; index += 3) {
  32826. indices[index] = index;
  32827. indices[index + 1] = index + 1;
  32828. indices[index + 2] = index + 2;
  32829. }
  32830. this.setIndices(indices);
  32831. // Updating vertex buffers
  32832. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32833. kind = kinds[kindIndex];
  32834. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32835. }
  32836. // Updating submeshes
  32837. this.releaseSubMeshes();
  32838. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32839. var previousOne = previousSubmeshes[submeshIndex];
  32840. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32841. }
  32842. this._unIndexed = true;
  32843. this.synchronizeInstances();
  32844. return this;
  32845. };
  32846. /**
  32847. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32848. * This method returns the Mesh.
  32849. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32850. */
  32851. Mesh.prototype.flipFaces = function (flipNormals) {
  32852. if (flipNormals === void 0) { flipNormals = false; }
  32853. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32854. var i;
  32855. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32856. for (i = 0; i < vertex_data.normals.length; i++) {
  32857. vertex_data.normals[i] *= -1;
  32858. }
  32859. }
  32860. if (vertex_data.indices) {
  32861. var temp;
  32862. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32863. // reassign indices
  32864. temp = vertex_data.indices[i + 1];
  32865. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32866. vertex_data.indices[i + 2] = temp;
  32867. }
  32868. }
  32869. vertex_data.applyToMesh(this);
  32870. return this;
  32871. };
  32872. // Instances
  32873. /**
  32874. * Creates a new InstancedMesh object from the mesh model.
  32875. * An instance shares the same properties and the same material than its model.
  32876. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  32877. * Only these properties of each instance can then be set individually :
  32878. * - position
  32879. * - rotation
  32880. * - rotationQuaternion
  32881. * - setPivotMatrix
  32882. * - scaling
  32883. *
  32884. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32885. * Warning : this method is not supported for Line mesh and LineSystem
  32886. */
  32887. Mesh.prototype.createInstance = function (name) {
  32888. return new BABYLON.InstancedMesh(name, this);
  32889. };
  32890. /**
  32891. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32892. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32893. * This method returns the Mesh.
  32894. */
  32895. Mesh.prototype.synchronizeInstances = function () {
  32896. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32897. var instance = this.instances[instanceIndex];
  32898. instance._syncSubMeshes();
  32899. }
  32900. return this;
  32901. };
  32902. /**
  32903. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32904. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32905. * This should be used together with the simplification to avoid disappearing triangles.
  32906. * Returns the Mesh.
  32907. * @param successCallback an optional success callback to be called after the optimization finished.
  32908. */
  32909. Mesh.prototype.optimizeIndices = function (successCallback) {
  32910. var _this = this;
  32911. var indices = this.getIndices();
  32912. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32913. if (!positions || !indices) {
  32914. return this;
  32915. }
  32916. var vectorPositions = new Array();
  32917. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32918. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32919. }
  32920. var dupes = new Array();
  32921. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32922. var realPos = vectorPositions.length - 1 - iteration;
  32923. var testedPosition = vectorPositions[realPos];
  32924. for (var j = 0; j < realPos; ++j) {
  32925. var againstPosition = vectorPositions[j];
  32926. if (testedPosition.equals(againstPosition)) {
  32927. dupes[realPos] = j;
  32928. break;
  32929. }
  32930. }
  32931. }, function () {
  32932. for (var i = 0; i < indices.length; ++i) {
  32933. indices[i] = dupes[indices[i]] || indices[i];
  32934. }
  32935. //indices are now reordered
  32936. var originalSubMeshes = _this.subMeshes.slice(0);
  32937. _this.setIndices(indices);
  32938. _this.subMeshes = originalSubMeshes;
  32939. if (successCallback) {
  32940. successCallback(_this);
  32941. }
  32942. });
  32943. return this;
  32944. };
  32945. Mesh.prototype.serialize = function (serializationObject) {
  32946. serializationObject.name = this.name;
  32947. serializationObject.id = this.id;
  32948. serializationObject.type = this.getClassName();
  32949. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32950. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32951. }
  32952. serializationObject.position = this.position.asArray();
  32953. if (this.rotationQuaternion) {
  32954. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32955. }
  32956. else if (this.rotation) {
  32957. serializationObject.rotation = this.rotation.asArray();
  32958. }
  32959. serializationObject.scaling = this.scaling.asArray();
  32960. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32961. serializationObject.isEnabled = this.isEnabled(false);
  32962. serializationObject.isVisible = this.isVisible;
  32963. serializationObject.infiniteDistance = this.infiniteDistance;
  32964. serializationObject.pickable = this.isPickable;
  32965. serializationObject.receiveShadows = this.receiveShadows;
  32966. serializationObject.billboardMode = this.billboardMode;
  32967. serializationObject.visibility = this.visibility;
  32968. serializationObject.checkCollisions = this.checkCollisions;
  32969. serializationObject.isBlocker = this.isBlocker;
  32970. // Parent
  32971. if (this.parent) {
  32972. serializationObject.parentId = this.parent.id;
  32973. }
  32974. // Geometry
  32975. serializationObject.isUnIndexed = this.isUnIndexed;
  32976. var geometry = this._geometry;
  32977. if (geometry) {
  32978. var geometryId = geometry.id;
  32979. serializationObject.geometryId = geometryId;
  32980. // SubMeshes
  32981. serializationObject.subMeshes = [];
  32982. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32983. var subMesh = this.subMeshes[subIndex];
  32984. serializationObject.subMeshes.push({
  32985. materialIndex: subMesh.materialIndex,
  32986. verticesStart: subMesh.verticesStart,
  32987. verticesCount: subMesh.verticesCount,
  32988. indexStart: subMesh.indexStart,
  32989. indexCount: subMesh.indexCount
  32990. });
  32991. }
  32992. }
  32993. // Material
  32994. if (this.material) {
  32995. serializationObject.materialId = this.material.id;
  32996. }
  32997. else {
  32998. this.material = null;
  32999. }
  33000. // Morph targets
  33001. if (this.morphTargetManager) {
  33002. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33003. }
  33004. // Skeleton
  33005. if (this.skeleton) {
  33006. serializationObject.skeletonId = this.skeleton.id;
  33007. }
  33008. // Physics
  33009. //TODO implement correct serialization for physics impostors.
  33010. var impostor = this.getPhysicsImpostor();
  33011. if (impostor) {
  33012. serializationObject.physicsMass = impostor.getParam("mass");
  33013. serializationObject.physicsFriction = impostor.getParam("friction");
  33014. serializationObject.physicsRestitution = impostor.getParam("mass");
  33015. serializationObject.physicsImpostor = impostor.type;
  33016. }
  33017. // Metadata
  33018. if (this.metadata) {
  33019. serializationObject.metadata = this.metadata;
  33020. }
  33021. // Instances
  33022. serializationObject.instances = [];
  33023. for (var index = 0; index < this.instances.length; index++) {
  33024. var instance = this.instances[index];
  33025. if (instance.doNotSerialize) {
  33026. continue;
  33027. }
  33028. var serializationInstance = {
  33029. name: instance.name,
  33030. id: instance.id,
  33031. position: instance.position.asArray(),
  33032. scaling: instance.scaling.asArray()
  33033. };
  33034. if (instance.parent) {
  33035. serializationInstance.parentId = instance.parent.id;
  33036. }
  33037. if (instance.rotationQuaternion) {
  33038. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33039. }
  33040. else if (instance.rotation) {
  33041. serializationInstance.rotation = instance.rotation.asArray();
  33042. }
  33043. serializationObject.instances.push(serializationInstance);
  33044. // Animations
  33045. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33046. serializationInstance.ranges = instance.serializeAnimationRanges();
  33047. }
  33048. //
  33049. // Animations
  33050. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33051. serializationObject.ranges = this.serializeAnimationRanges();
  33052. // Layer mask
  33053. serializationObject.layerMask = this.layerMask;
  33054. // Alpha
  33055. serializationObject.alphaIndex = this.alphaIndex;
  33056. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33057. // Overlay
  33058. serializationObject.overlayAlpha = this.overlayAlpha;
  33059. serializationObject.overlayColor = this.overlayColor.asArray();
  33060. serializationObject.renderOverlay = this.renderOverlay;
  33061. // Fog
  33062. serializationObject.applyFog = this.applyFog;
  33063. // Action Manager
  33064. if (this.actionManager) {
  33065. serializationObject.actions = this.actionManager.serialize(this.name);
  33066. }
  33067. };
  33068. /** @hidden */
  33069. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33070. if (!this.geometry) {
  33071. return;
  33072. }
  33073. this._markSubMeshesAsAttributesDirty();
  33074. var morphTargetManager = this._morphTargetManager;
  33075. if (morphTargetManager && morphTargetManager.vertexCount) {
  33076. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33077. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33078. this.morphTargetManager = null;
  33079. return;
  33080. }
  33081. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33082. var morphTarget = morphTargetManager.getActiveTarget(index);
  33083. var positions = morphTarget.getPositions();
  33084. if (!positions) {
  33085. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33086. return;
  33087. }
  33088. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33089. var normals = morphTarget.getNormals();
  33090. if (normals) {
  33091. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33092. }
  33093. var tangents = morphTarget.getTangents();
  33094. if (tangents) {
  33095. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33096. }
  33097. }
  33098. }
  33099. else {
  33100. var index = 0;
  33101. // Positions
  33102. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33103. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33104. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33105. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33106. }
  33107. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33108. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33109. }
  33110. index++;
  33111. }
  33112. }
  33113. };
  33114. // Statics
  33115. /**
  33116. * Returns a new Mesh object parsed from the source provided.
  33117. * The parameter `parsedMesh` is the source.
  33118. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33119. */
  33120. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33121. var mesh;
  33122. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33123. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33124. }
  33125. else {
  33126. mesh = new Mesh(parsedMesh.name, scene);
  33127. }
  33128. mesh.id = parsedMesh.id;
  33129. if (BABYLON.Tags) {
  33130. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33131. }
  33132. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33133. if (parsedMesh.metadata !== undefined) {
  33134. mesh.metadata = parsedMesh.metadata;
  33135. }
  33136. if (parsedMesh.rotationQuaternion) {
  33137. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33138. }
  33139. else if (parsedMesh.rotation) {
  33140. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33141. }
  33142. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33143. if (parsedMesh.localMatrix) {
  33144. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33145. }
  33146. else if (parsedMesh.pivotMatrix) {
  33147. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33148. }
  33149. mesh.setEnabled(parsedMesh.isEnabled);
  33150. mesh.isVisible = parsedMesh.isVisible;
  33151. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33152. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33153. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33154. if (parsedMesh.applyFog !== undefined) {
  33155. mesh.applyFog = parsedMesh.applyFog;
  33156. }
  33157. if (parsedMesh.pickable !== undefined) {
  33158. mesh.isPickable = parsedMesh.pickable;
  33159. }
  33160. if (parsedMesh.alphaIndex !== undefined) {
  33161. mesh.alphaIndex = parsedMesh.alphaIndex;
  33162. }
  33163. mesh.receiveShadows = parsedMesh.receiveShadows;
  33164. mesh.billboardMode = parsedMesh.billboardMode;
  33165. if (parsedMesh.visibility !== undefined) {
  33166. mesh.visibility = parsedMesh.visibility;
  33167. }
  33168. mesh.checkCollisions = parsedMesh.checkCollisions;
  33169. if (parsedMesh.isBlocker !== undefined) {
  33170. mesh.isBlocker = parsedMesh.isBlocker;
  33171. }
  33172. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33173. // freezeWorldMatrix
  33174. if (parsedMesh.freezeWorldMatrix) {
  33175. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33176. }
  33177. // Parent
  33178. if (parsedMesh.parentId) {
  33179. mesh._waitingParentId = parsedMesh.parentId;
  33180. }
  33181. // Actions
  33182. if (parsedMesh.actions !== undefined) {
  33183. mesh._waitingActions = parsedMesh.actions;
  33184. }
  33185. // Overlay
  33186. if (parsedMesh.overlayAlpha !== undefined) {
  33187. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33188. }
  33189. if (parsedMesh.overlayColor !== undefined) {
  33190. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33191. }
  33192. if (parsedMesh.renderOverlay !== undefined) {
  33193. mesh.renderOverlay = parsedMesh.renderOverlay;
  33194. }
  33195. // Geometry
  33196. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33197. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33198. if (parsedMesh.delayLoadingFile) {
  33199. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33200. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33201. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33202. if (parsedMesh._binaryInfo) {
  33203. mesh._binaryInfo = parsedMesh._binaryInfo;
  33204. }
  33205. mesh._delayInfo = [];
  33206. if (parsedMesh.hasUVs) {
  33207. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33208. }
  33209. if (parsedMesh.hasUVs2) {
  33210. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33211. }
  33212. if (parsedMesh.hasUVs3) {
  33213. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33214. }
  33215. if (parsedMesh.hasUVs4) {
  33216. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33217. }
  33218. if (parsedMesh.hasUVs5) {
  33219. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33220. }
  33221. if (parsedMesh.hasUVs6) {
  33222. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33223. }
  33224. if (parsedMesh.hasColors) {
  33225. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33226. }
  33227. if (parsedMesh.hasMatricesIndices) {
  33228. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33229. }
  33230. if (parsedMesh.hasMatricesWeights) {
  33231. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33232. }
  33233. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33234. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33235. mesh._checkDelayState();
  33236. }
  33237. }
  33238. else {
  33239. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33240. }
  33241. // Material
  33242. if (parsedMesh.materialId) {
  33243. mesh.setMaterialByID(parsedMesh.materialId);
  33244. }
  33245. else {
  33246. mesh.material = null;
  33247. }
  33248. // Morph targets
  33249. if (parsedMesh.morphTargetManagerId > -1) {
  33250. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33251. }
  33252. // Skeleton
  33253. if (parsedMesh.skeletonId > -1) {
  33254. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33255. if (parsedMesh.numBoneInfluencers) {
  33256. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33257. }
  33258. }
  33259. // Animations
  33260. if (parsedMesh.animations) {
  33261. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33262. var parsedAnimation = parsedMesh.animations[animationIndex];
  33263. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33264. }
  33265. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33266. }
  33267. if (parsedMesh.autoAnimate) {
  33268. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33269. }
  33270. // Layer Mask
  33271. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33272. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33273. }
  33274. else {
  33275. mesh.layerMask = 0x0FFFFFFF;
  33276. }
  33277. // Physics
  33278. if (parsedMesh.physicsImpostor) {
  33279. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33280. mass: parsedMesh.physicsMass,
  33281. friction: parsedMesh.physicsFriction,
  33282. restitution: parsedMesh.physicsRestitution
  33283. }, scene);
  33284. }
  33285. // Instances
  33286. if (parsedMesh.instances) {
  33287. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33288. var parsedInstance = parsedMesh.instances[index];
  33289. var instance = mesh.createInstance(parsedInstance.name);
  33290. if (parsedInstance.id) {
  33291. instance.id = parsedInstance.id;
  33292. }
  33293. if (BABYLON.Tags) {
  33294. if (parsedInstance.tags) {
  33295. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33296. }
  33297. else {
  33298. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33299. }
  33300. }
  33301. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33302. if (parsedInstance.parentId) {
  33303. instance._waitingParentId = parsedInstance.parentId;
  33304. }
  33305. if (parsedInstance.rotationQuaternion) {
  33306. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33307. }
  33308. else if (parsedInstance.rotation) {
  33309. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33310. }
  33311. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33312. instance.checkCollisions = mesh.checkCollisions;
  33313. if (parsedMesh.animations) {
  33314. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33315. parsedAnimation = parsedMesh.animations[animationIndex];
  33316. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33317. }
  33318. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33319. if (parsedMesh.autoAnimate) {
  33320. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33321. }
  33322. }
  33323. }
  33324. }
  33325. return mesh;
  33326. };
  33327. /**
  33328. * Creates a ribbon mesh.
  33329. * Please consider using the same method from the MeshBuilder class instead.
  33330. * The ribbon is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33331. *
  33332. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33333. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33334. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33335. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33336. * 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.
  33337. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  33338. * 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
  33339. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33340. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33341. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33342. */
  33343. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33344. if (closeArray === void 0) { closeArray = false; }
  33345. if (updatable === void 0) { updatable = false; }
  33346. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33347. pathArray: pathArray,
  33348. closeArray: closeArray,
  33349. closePath: closePath,
  33350. offset: offset,
  33351. updatable: updatable,
  33352. sideOrientation: sideOrientation,
  33353. instance: instance
  33354. }, scene);
  33355. };
  33356. /**
  33357. * Creates a plane polygonal mesh. By default, this is a disc.
  33358. * Please consider using the same method from the MeshBuilder class instead.
  33359. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33360. * 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.
  33361. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33362. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33363. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33364. */
  33365. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33366. if (scene === void 0) { scene = null; }
  33367. var options = {
  33368. radius: radius,
  33369. tessellation: tessellation,
  33370. sideOrientation: sideOrientation,
  33371. updatable: updatable
  33372. };
  33373. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33374. };
  33375. /**
  33376. * Creates a box mesh.
  33377. * Please consider using the same method from the MeshBuilder class instead.
  33378. * The parameter `size` sets the size (float) of each box side (default 1).
  33379. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33380. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33381. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33382. */
  33383. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33384. if (scene === void 0) { scene = null; }
  33385. var options = {
  33386. size: size,
  33387. sideOrientation: sideOrientation,
  33388. updatable: updatable
  33389. };
  33390. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33391. };
  33392. /**
  33393. * Creates a sphere mesh.
  33394. * Please consider using the same method from the MeshBuilder class instead.
  33395. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33396. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33397. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33398. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33399. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33400. */
  33401. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33402. var options = {
  33403. segments: segments,
  33404. diameterX: diameter,
  33405. diameterY: diameter,
  33406. diameterZ: diameter,
  33407. sideOrientation: sideOrientation,
  33408. updatable: updatable
  33409. };
  33410. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33411. };
  33412. /**
  33413. * Creates a cylinder or a cone mesh.
  33414. * Please consider using the same method from the MeshBuilder class instead.
  33415. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33416. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33417. * 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.
  33418. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33419. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33420. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33421. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33422. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33423. */
  33424. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33425. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33426. if (scene !== undefined) {
  33427. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33428. updatable = scene;
  33429. }
  33430. scene = subdivisions;
  33431. subdivisions = 1;
  33432. }
  33433. var options = {
  33434. height: height,
  33435. diameterTop: diameterTop,
  33436. diameterBottom: diameterBottom,
  33437. tessellation: tessellation,
  33438. subdivisions: subdivisions,
  33439. sideOrientation: sideOrientation,
  33440. updatable: updatable
  33441. };
  33442. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33443. };
  33444. // Torus (Code from SharpDX.org)
  33445. /**
  33446. * Creates a torus mesh.
  33447. * Please consider using the same method from the MeshBuilder class instead.
  33448. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33449. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33450. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33451. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33452. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33453. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33454. */
  33455. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33456. var options = {
  33457. diameter: diameter,
  33458. thickness: thickness,
  33459. tessellation: tessellation,
  33460. sideOrientation: sideOrientation,
  33461. updatable: updatable
  33462. };
  33463. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33464. };
  33465. /**
  33466. * Creates a torus knot mesh.
  33467. * Please consider using the same method from the MeshBuilder class instead.
  33468. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33469. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33470. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33471. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33472. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33473. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33474. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33475. */
  33476. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33477. var options = {
  33478. radius: radius,
  33479. tube: tube,
  33480. radialSegments: radialSegments,
  33481. tubularSegments: tubularSegments,
  33482. p: p,
  33483. q: q,
  33484. sideOrientation: sideOrientation,
  33485. updatable: updatable
  33486. };
  33487. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33488. };
  33489. /**
  33490. * Creates a line mesh.
  33491. * Please consider using the same method from the MeshBuilder class instead.
  33492. * 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.
  33493. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33494. * The parameter `points` is an array successive Vector3.
  33495. * 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
  33496. * When updating an instance, remember that only point positions can change, not the number of points.
  33497. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33498. */
  33499. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33500. if (scene === void 0) { scene = null; }
  33501. if (updatable === void 0) { updatable = false; }
  33502. if (instance === void 0) { instance = null; }
  33503. var options = {
  33504. points: points,
  33505. updatable: updatable,
  33506. instance: instance
  33507. };
  33508. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33509. };
  33510. /**
  33511. * Creates a dashed line mesh.
  33512. * Please consider using the same method from the MeshBuilder class instead.
  33513. * 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.
  33514. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33515. * The parameter `points` is an array successive Vector3.
  33516. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33517. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33518. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33519. * 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
  33520. * When updating an instance, remember that only point positions can change, not the number of points.
  33521. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33522. */
  33523. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33524. if (scene === void 0) { scene = null; }
  33525. var options = {
  33526. points: points,
  33527. dashSize: dashSize,
  33528. gapSize: gapSize,
  33529. dashNb: dashNb,
  33530. updatable: updatable,
  33531. instance: instance
  33532. };
  33533. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33534. };
  33535. /**
  33536. * Creates a polygon mesh.
  33537. * Please consider using the same method from the MeshBuilder class instead.
  33538. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33539. * 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.
  33540. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33541. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33542. * Remember you can only change the shape positions, not their number when updating a polygon.
  33543. */
  33544. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33545. var options = {
  33546. shape: shape,
  33547. holes: holes,
  33548. updatable: updatable,
  33549. sideOrientation: sideOrientation
  33550. };
  33551. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33552. };
  33553. /**
  33554. * Creates an extruded polygon mesh, with depth in the Y direction.
  33555. * Please consider using the same method from the MeshBuilder class instead.
  33556. */
  33557. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33558. var options = {
  33559. shape: shape,
  33560. holes: holes,
  33561. depth: depth,
  33562. updatable: updatable,
  33563. sideOrientation: sideOrientation
  33564. };
  33565. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33566. };
  33567. /**
  33568. * Creates an extruded shape mesh.
  33569. * The extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33570. * Please consider using the same method from the MeshBuilder class instead.
  33571. *
  33572. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33573. * 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
  33574. * extruded along the Z axis.
  33575. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33576. * 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.
  33577. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33578. * 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
  33579. * 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
  33580. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33581. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33582. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33583. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33584. */
  33585. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33586. if (scene === void 0) { scene = null; }
  33587. var options = {
  33588. shape: shape,
  33589. path: path,
  33590. scale: scale,
  33591. rotation: rotation,
  33592. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33593. sideOrientation: sideOrientation,
  33594. instance: instance,
  33595. updatable: updatable
  33596. };
  33597. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33598. };
  33599. /**
  33600. * Creates an custom extruded shape mesh.
  33601. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33602. * Please consider using the same method from the MeshBuilder class instead.
  33603. *
  33604. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33605. * 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
  33606. * extruded along the Z axis.
  33607. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33608. * 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
  33609. * and the distance of this point from the begining of the path :
  33610. * ```javascript
  33611. * var rotationFunction = function(i, distance) {
  33612. * // do things
  33613. * return rotationValue; }
  33614. * ```
  33615. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33616. * 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
  33617. * and the distance of this point from the begining of the path :
  33618. * ```javascript
  33619. * var scaleFunction = function(i, distance) {
  33620. * // do things
  33621. * return scaleValue;}
  33622. * ```
  33623. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33624. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33625. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33626. * 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
  33627. * 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
  33628. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33629. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33630. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33631. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33632. */
  33633. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33634. var options = {
  33635. shape: shape,
  33636. path: path,
  33637. scaleFunction: scaleFunction,
  33638. rotationFunction: rotationFunction,
  33639. ribbonCloseArray: ribbonCloseArray,
  33640. ribbonClosePath: ribbonClosePath,
  33641. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33642. sideOrientation: sideOrientation,
  33643. instance: instance,
  33644. updatable: updatable
  33645. };
  33646. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33647. };
  33648. /**
  33649. * Creates lathe mesh.
  33650. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33651. * Please consider using the same method from the MeshBuilder class instead.
  33652. * 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
  33653. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33654. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33655. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33656. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33657. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33658. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33659. */
  33660. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33661. var options = {
  33662. shape: shape,
  33663. radius: radius,
  33664. tessellation: tessellation,
  33665. sideOrientation: sideOrientation,
  33666. updatable: updatable
  33667. };
  33668. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33669. };
  33670. /**
  33671. * Creates a plane mesh.
  33672. * Please consider using the same method from the MeshBuilder class instead.
  33673. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33674. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33675. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33676. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33677. */
  33678. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33679. var options = {
  33680. size: size,
  33681. width: size,
  33682. height: size,
  33683. sideOrientation: sideOrientation,
  33684. updatable: updatable
  33685. };
  33686. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33687. };
  33688. /**
  33689. * Creates a ground mesh.
  33690. * Please consider using the same method from the MeshBuilder class instead.
  33691. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33692. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33693. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33694. */
  33695. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33696. var options = {
  33697. width: width,
  33698. height: height,
  33699. subdivisions: subdivisions,
  33700. updatable: updatable
  33701. };
  33702. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33703. };
  33704. /**
  33705. * Creates a tiled ground mesh.
  33706. * Please consider using the same method from the MeshBuilder class instead.
  33707. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33708. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33709. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33710. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33711. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33712. * numbers of subdivisions on the ground width and height of each tile.
  33713. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33714. */
  33715. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33716. var options = {
  33717. xmin: xmin,
  33718. zmin: zmin,
  33719. xmax: xmax,
  33720. zmax: zmax,
  33721. subdivisions: subdivisions,
  33722. precision: precision,
  33723. updatable: updatable
  33724. };
  33725. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33726. };
  33727. /**
  33728. * Creates a ground mesh from a height map.
  33729. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33730. * Please consider using the same method from the MeshBuilder class instead.
  33731. * The parameter `url` sets the URL of the height map image resource.
  33732. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33733. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33734. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33735. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33736. * 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).
  33737. * This function is passed the newly built mesh :
  33738. * ```javascript
  33739. * function(mesh) { // do things
  33740. * return; }
  33741. * ```
  33742. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33743. */
  33744. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33745. var options = {
  33746. width: width,
  33747. height: height,
  33748. subdivisions: subdivisions,
  33749. minHeight: minHeight,
  33750. maxHeight: maxHeight,
  33751. updatable: updatable,
  33752. onReady: onReady
  33753. };
  33754. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33755. };
  33756. /**
  33757. * Creates a tube mesh.
  33758. * The tube is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33759. * Please consider using the same method from the MeshBuilder class instead.
  33760. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33761. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33762. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33763. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33764. * 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.
  33765. * It must return a radius value (positive float) :
  33766. * ```javascript
  33767. * var radiusFunction = function(i, distance) {
  33768. * // do things
  33769. * return radius; }
  33770. * ```
  33771. * 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
  33772. * 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
  33773. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33774. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33775. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33776. */
  33777. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33778. var options = {
  33779. path: path,
  33780. radius: radius,
  33781. tessellation: tessellation,
  33782. radiusFunction: radiusFunction,
  33783. arc: 1,
  33784. cap: cap,
  33785. updatable: updatable,
  33786. sideOrientation: sideOrientation,
  33787. instance: instance
  33788. };
  33789. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33790. };
  33791. /**
  33792. * Creates a polyhedron mesh.
  33793. * Please consider using the same method from the MeshBuilder class instead.
  33794. * 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
  33795. * to choose the wanted type.
  33796. * The parameter `size` (positive float, default 1) sets the polygon size.
  33797. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33798. * 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`.
  33799. * 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
  33800. * 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)`).
  33801. * 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
  33802. * 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.
  33803. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33804. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33805. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33806. */
  33807. Mesh.CreatePolyhedron = function (name, options, scene) {
  33808. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33809. };
  33810. /**
  33811. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33812. * Please consider using the same method from the MeshBuilder class instead.
  33813. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33814. * 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`).
  33815. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33816. * 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.
  33817. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33818. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33819. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33820. */
  33821. Mesh.CreateIcoSphere = function (name, options, scene) {
  33822. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33823. };
  33824. /**
  33825. * Creates a decal mesh.
  33826. * Please consider using the same method from the MeshBuilder class instead.
  33827. * 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.
  33828. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33829. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33830. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33831. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33832. */
  33833. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33834. var options = {
  33835. position: position,
  33836. normal: normal,
  33837. size: size,
  33838. angle: angle
  33839. };
  33840. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33841. };
  33842. // Skeletons
  33843. /**
  33844. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33845. */
  33846. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33847. if (!this._sourcePositions) {
  33848. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33849. if (!source) {
  33850. return this._sourcePositions;
  33851. }
  33852. this._sourcePositions = new Float32Array(source);
  33853. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33854. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33855. }
  33856. }
  33857. return this._sourcePositions;
  33858. };
  33859. /**
  33860. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33861. */
  33862. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33863. if (!this._sourceNormals) {
  33864. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33865. if (!source) {
  33866. return this._sourceNormals;
  33867. }
  33868. this._sourceNormals = new Float32Array(source);
  33869. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33870. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33871. }
  33872. }
  33873. return this._sourceNormals;
  33874. };
  33875. /**
  33876. * Updates the vertex buffer by applying transformation from the bones.
  33877. * Returns the Mesh.
  33878. *
  33879. * @param {skeleton} skeleton to apply
  33880. */
  33881. Mesh.prototype.applySkeleton = function (skeleton) {
  33882. if (!this.geometry) {
  33883. return this;
  33884. }
  33885. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33886. return this;
  33887. }
  33888. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33889. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33890. return this;
  33891. }
  33892. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33893. return this;
  33894. }
  33895. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33896. return this;
  33897. }
  33898. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33899. return this;
  33900. }
  33901. if (!this._sourcePositions) {
  33902. var submeshes = this.subMeshes.slice();
  33903. this.setPositionsForCPUSkinning();
  33904. this.subMeshes = submeshes;
  33905. }
  33906. if (!this._sourceNormals) {
  33907. this.setNormalsForCPUSkinning();
  33908. }
  33909. // positionsData checks for not being Float32Array will only pass at most once
  33910. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33911. if (!positionsData) {
  33912. return this;
  33913. }
  33914. if (!(positionsData instanceof Float32Array)) {
  33915. positionsData = new Float32Array(positionsData);
  33916. }
  33917. // normalsData checks for not being Float32Array will only pass at most once
  33918. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33919. if (!normalsData) {
  33920. return this;
  33921. }
  33922. if (!(normalsData instanceof Float32Array)) {
  33923. normalsData = new Float32Array(normalsData);
  33924. }
  33925. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33926. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33927. if (!matricesWeightsData || !matricesIndicesData) {
  33928. return this;
  33929. }
  33930. var needExtras = this.numBoneInfluencers > 4;
  33931. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33932. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33933. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33934. var tempVector3 = BABYLON.Vector3.Zero();
  33935. var finalMatrix = new BABYLON.Matrix();
  33936. var tempMatrix = new BABYLON.Matrix();
  33937. var matWeightIdx = 0;
  33938. var inf;
  33939. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33940. var weight;
  33941. for (inf = 0; inf < 4; inf++) {
  33942. weight = matricesWeightsData[matWeightIdx + inf];
  33943. if (weight > 0) {
  33944. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33945. finalMatrix.addToSelf(tempMatrix);
  33946. }
  33947. }
  33948. if (needExtras) {
  33949. for (inf = 0; inf < 4; inf++) {
  33950. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33951. if (weight > 0) {
  33952. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33953. finalMatrix.addToSelf(tempMatrix);
  33954. }
  33955. }
  33956. }
  33957. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33958. tempVector3.toArray(positionsData, index);
  33959. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33960. tempVector3.toArray(normalsData, index);
  33961. finalMatrix.reset();
  33962. }
  33963. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33964. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33965. return this;
  33966. };
  33967. // Tools
  33968. /**
  33969. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33970. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33971. */
  33972. Mesh.MinMax = function (meshes) {
  33973. var minVector = null;
  33974. var maxVector = null;
  33975. meshes.forEach(function (mesh, index, array) {
  33976. var boundingInfo = mesh.getBoundingInfo();
  33977. var boundingBox = boundingInfo.boundingBox;
  33978. if (!minVector || !maxVector) {
  33979. minVector = boundingBox.minimumWorld;
  33980. maxVector = boundingBox.maximumWorld;
  33981. }
  33982. else {
  33983. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33984. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33985. }
  33986. });
  33987. if (!minVector || !maxVector) {
  33988. return {
  33989. min: BABYLON.Vector3.Zero(),
  33990. max: BABYLON.Vector3.Zero()
  33991. };
  33992. }
  33993. return {
  33994. min: minVector,
  33995. max: maxVector
  33996. };
  33997. };
  33998. /**
  33999. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34000. */
  34001. Mesh.Center = function (meshesOrMinMaxVector) {
  34002. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34003. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34004. };
  34005. /**
  34006. * Merge the array of meshes into a single mesh for performance reasons.
  34007. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  34008. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  34009. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34010. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34011. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34012. */
  34013. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34014. if (disposeSource === void 0) { disposeSource = true; }
  34015. var index;
  34016. if (!allow32BitsIndices) {
  34017. var totalVertices = 0;
  34018. // Counting vertices
  34019. for (index = 0; index < meshes.length; index++) {
  34020. if (meshes[index]) {
  34021. totalVertices += meshes[index].getTotalVertices();
  34022. if (totalVertices > 65536) {
  34023. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34024. return null;
  34025. }
  34026. }
  34027. }
  34028. }
  34029. // Merge
  34030. var vertexData = null;
  34031. var otherVertexData;
  34032. var indiceArray = new Array();
  34033. var source = null;
  34034. for (index = 0; index < meshes.length; index++) {
  34035. if (meshes[index]) {
  34036. var wm = meshes[index].computeWorldMatrix(true);
  34037. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34038. otherVertexData.transform(wm);
  34039. if (vertexData) {
  34040. vertexData.merge(otherVertexData, allow32BitsIndices);
  34041. }
  34042. else {
  34043. vertexData = otherVertexData;
  34044. source = meshes[index];
  34045. }
  34046. if (subdivideWithSubMeshes) {
  34047. indiceArray.push(meshes[index].getTotalIndices());
  34048. }
  34049. }
  34050. }
  34051. source = source;
  34052. if (!meshSubclass) {
  34053. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34054. }
  34055. vertexData.applyToMesh(meshSubclass);
  34056. // Setting properties
  34057. meshSubclass.material = source.material;
  34058. meshSubclass.checkCollisions = source.checkCollisions;
  34059. // Cleaning
  34060. if (disposeSource) {
  34061. for (index = 0; index < meshes.length; index++) {
  34062. if (meshes[index]) {
  34063. meshes[index].dispose();
  34064. }
  34065. }
  34066. }
  34067. // Subdivide
  34068. if (subdivideWithSubMeshes) {
  34069. //-- removal of global submesh
  34070. meshSubclass.releaseSubMeshes();
  34071. index = 0;
  34072. var offset = 0;
  34073. //-- apply subdivision according to index table
  34074. while (index < indiceArray.length) {
  34075. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34076. offset += indiceArray[index];
  34077. index++;
  34078. }
  34079. }
  34080. return meshSubclass;
  34081. };
  34082. // Consts
  34083. Mesh._FRONTSIDE = 0;
  34084. Mesh._BACKSIDE = 1;
  34085. Mesh._DOUBLESIDE = 2;
  34086. Mesh._DEFAULTSIDE = 0;
  34087. Mesh._NO_CAP = 0;
  34088. Mesh._CAP_START = 1;
  34089. Mesh._CAP_END = 2;
  34090. Mesh._CAP_ALL = 3;
  34091. return Mesh;
  34092. }(BABYLON.AbstractMesh));
  34093. BABYLON.Mesh = Mesh;
  34094. })(BABYLON || (BABYLON = {}));
  34095. //# sourceMappingURL=babylon.mesh.js.map
  34096. var BABYLON;
  34097. (function (BABYLON) {
  34098. var BaseSubMesh = /** @class */ (function () {
  34099. function BaseSubMesh() {
  34100. }
  34101. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34102. get: function () {
  34103. return this._materialEffect;
  34104. },
  34105. enumerable: true,
  34106. configurable: true
  34107. });
  34108. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34109. if (defines === void 0) { defines = null; }
  34110. if (this._materialEffect === effect) {
  34111. if (!effect) {
  34112. this._materialDefines = null;
  34113. }
  34114. return;
  34115. }
  34116. this._materialDefines = defines;
  34117. this._materialEffect = effect;
  34118. };
  34119. return BaseSubMesh;
  34120. }());
  34121. BABYLON.BaseSubMesh = BaseSubMesh;
  34122. var SubMesh = /** @class */ (function (_super) {
  34123. __extends(SubMesh, _super);
  34124. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34125. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34126. var _this = _super.call(this) || this;
  34127. _this.materialIndex = materialIndex;
  34128. _this.verticesStart = verticesStart;
  34129. _this.verticesCount = verticesCount;
  34130. _this.indexStart = indexStart;
  34131. _this.indexCount = indexCount;
  34132. /** @hidden */
  34133. _this._renderId = 0;
  34134. _this._mesh = mesh;
  34135. _this._renderingMesh = renderingMesh || mesh;
  34136. mesh.subMeshes.push(_this);
  34137. _this._trianglePlanes = [];
  34138. _this._id = mesh.subMeshes.length - 1;
  34139. if (createBoundingBox) {
  34140. _this.refreshBoundingInfo();
  34141. mesh.computeWorldMatrix(true);
  34142. }
  34143. return _this;
  34144. }
  34145. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34146. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34147. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34148. };
  34149. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34150. get: function () {
  34151. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34152. },
  34153. enumerable: true,
  34154. configurable: true
  34155. });
  34156. /**
  34157. * Returns the submesh BoudingInfo object.
  34158. */
  34159. SubMesh.prototype.getBoundingInfo = function () {
  34160. if (this.IsGlobal) {
  34161. return this._mesh.getBoundingInfo();
  34162. }
  34163. return this._boundingInfo;
  34164. };
  34165. /**
  34166. * Sets the submesh BoundingInfo.
  34167. * Return the SubMesh.
  34168. */
  34169. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34170. this._boundingInfo = boundingInfo;
  34171. return this;
  34172. };
  34173. /**
  34174. * Returns the mesh of the current submesh.
  34175. */
  34176. SubMesh.prototype.getMesh = function () {
  34177. return this._mesh;
  34178. };
  34179. /**
  34180. * Returns the rendering mesh of the submesh.
  34181. */
  34182. SubMesh.prototype.getRenderingMesh = function () {
  34183. return this._renderingMesh;
  34184. };
  34185. /**
  34186. * Returns the submesh material.
  34187. */
  34188. SubMesh.prototype.getMaterial = function () {
  34189. var rootMaterial = this._renderingMesh.material;
  34190. if (rootMaterial === null || rootMaterial === undefined) {
  34191. return this._mesh.getScene().defaultMaterial;
  34192. }
  34193. else if (rootMaterial.getSubMaterial) {
  34194. var multiMaterial = rootMaterial;
  34195. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34196. if (this._currentMaterial !== effectiveMaterial) {
  34197. this._currentMaterial = effectiveMaterial;
  34198. this._materialDefines = null;
  34199. }
  34200. return effectiveMaterial;
  34201. }
  34202. return rootMaterial;
  34203. };
  34204. // Methods
  34205. /**
  34206. * Sets a new updated BoundingInfo object to the submesh.
  34207. * Returns the SubMesh.
  34208. */
  34209. SubMesh.prototype.refreshBoundingInfo = function () {
  34210. this._lastColliderWorldVertices = null;
  34211. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34212. return this;
  34213. }
  34214. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34215. if (!data) {
  34216. this._boundingInfo = this._mesh.getBoundingInfo();
  34217. return this;
  34218. }
  34219. var indices = this._renderingMesh.getIndices();
  34220. var extend;
  34221. //is this the only submesh?
  34222. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34223. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34224. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34225. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34226. }
  34227. else {
  34228. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34229. }
  34230. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34231. return this;
  34232. };
  34233. /** @hidden */
  34234. SubMesh.prototype._checkCollision = function (collider) {
  34235. var boundingInfo = this.getBoundingInfo();
  34236. return boundingInfo._checkCollision(collider);
  34237. };
  34238. /**
  34239. * Updates the submesh BoundingInfo.
  34240. * Returns the Submesh.
  34241. */
  34242. SubMesh.prototype.updateBoundingInfo = function (world) {
  34243. var boundingInfo = this.getBoundingInfo();
  34244. if (!boundingInfo) {
  34245. this.refreshBoundingInfo();
  34246. boundingInfo = this.getBoundingInfo();
  34247. }
  34248. boundingInfo.update(world);
  34249. return this;
  34250. };
  34251. /**
  34252. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34253. * Boolean returned.
  34254. */
  34255. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34256. var boundingInfo = this.getBoundingInfo();
  34257. if (!boundingInfo) {
  34258. return false;
  34259. }
  34260. return boundingInfo.isInFrustum(frustumPlanes);
  34261. };
  34262. /**
  34263. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34264. * Boolean returned.
  34265. */
  34266. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34267. var boundingInfo = this.getBoundingInfo();
  34268. if (!boundingInfo) {
  34269. return false;
  34270. }
  34271. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34272. };
  34273. /**
  34274. * Renders the submesh.
  34275. * Returns it.
  34276. */
  34277. SubMesh.prototype.render = function (enableAlphaMode) {
  34278. this._renderingMesh.render(this, enableAlphaMode);
  34279. return this;
  34280. };
  34281. /**
  34282. * Returns a new Index Buffer.
  34283. * Type returned : WebGLBuffer.
  34284. */
  34285. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34286. if (!this._linesIndexBuffer) {
  34287. var linesIndices = [];
  34288. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34289. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34290. }
  34291. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34292. this.linesIndexCount = linesIndices.length;
  34293. }
  34294. return this._linesIndexBuffer;
  34295. };
  34296. /**
  34297. * True is the passed Ray intersects the submesh bounding box.
  34298. * Boolean returned.
  34299. */
  34300. SubMesh.prototype.canIntersects = function (ray) {
  34301. var boundingInfo = this.getBoundingInfo();
  34302. if (!boundingInfo) {
  34303. return false;
  34304. }
  34305. return ray.intersectsBox(boundingInfo.boundingBox);
  34306. };
  34307. /**
  34308. * Returns an object IntersectionInfo.
  34309. */
  34310. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34311. var intersectInfo = null;
  34312. var material = this.getMaterial();
  34313. if (!material) {
  34314. return null;
  34315. }
  34316. switch (material.fillMode) {
  34317. case BABYLON.Material.PointListDrawMode:
  34318. case BABYLON.Material.LineListDrawMode:
  34319. case BABYLON.Material.LineLoopDrawMode:
  34320. case BABYLON.Material.LineStripDrawMode:
  34321. case BABYLON.Material.TriangleFanDrawMode:
  34322. case BABYLON.Material.TriangleStripDrawMode:
  34323. return null;
  34324. }
  34325. // LineMesh first as it's also a Mesh...
  34326. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34327. var lineMesh = this._mesh;
  34328. // Line test
  34329. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34330. var p0 = positions[indices[index]];
  34331. var p1 = positions[indices[index + 1]];
  34332. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34333. if (length < 0) {
  34334. continue;
  34335. }
  34336. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34337. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34338. if (fastCheck) {
  34339. break;
  34340. }
  34341. }
  34342. }
  34343. }
  34344. else {
  34345. // Triangles test
  34346. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34347. var p0 = positions[indices[index]];
  34348. var p1 = positions[indices[index + 1]];
  34349. var p2 = positions[indices[index + 2]];
  34350. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34351. if (currentIntersectInfo) {
  34352. if (currentIntersectInfo.distance < 0) {
  34353. continue;
  34354. }
  34355. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34356. intersectInfo = currentIntersectInfo;
  34357. intersectInfo.faceId = index / 3;
  34358. if (fastCheck) {
  34359. break;
  34360. }
  34361. }
  34362. }
  34363. }
  34364. }
  34365. return intersectInfo;
  34366. };
  34367. /** @hidden */
  34368. SubMesh.prototype._rebuild = function () {
  34369. if (this._linesIndexBuffer) {
  34370. this._linesIndexBuffer = null;
  34371. }
  34372. };
  34373. // Clone
  34374. /**
  34375. * Creates a new Submesh from the passed Mesh.
  34376. */
  34377. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34378. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34379. if (!this.IsGlobal) {
  34380. var boundingInfo = this.getBoundingInfo();
  34381. if (!boundingInfo) {
  34382. return result;
  34383. }
  34384. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34385. }
  34386. return result;
  34387. };
  34388. // Dispose
  34389. /**
  34390. * Disposes the Submesh.
  34391. * Returns nothing.
  34392. */
  34393. SubMesh.prototype.dispose = function () {
  34394. if (this._linesIndexBuffer) {
  34395. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34396. this._linesIndexBuffer = null;
  34397. }
  34398. // Remove from mesh
  34399. var index = this._mesh.subMeshes.indexOf(this);
  34400. this._mesh.subMeshes.splice(index, 1);
  34401. };
  34402. // Statics
  34403. /**
  34404. * Creates a new Submesh from the passed parameters :
  34405. * - materialIndex (integer) : the index of the main mesh material.
  34406. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34407. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34408. * - mesh (Mesh) : the main mesh to create the submesh from.
  34409. * - renderingMesh (optional Mesh) : rendering mesh.
  34410. */
  34411. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34412. var minVertexIndex = Number.MAX_VALUE;
  34413. var maxVertexIndex = -Number.MAX_VALUE;
  34414. renderingMesh = (renderingMesh || mesh);
  34415. var indices = renderingMesh.getIndices();
  34416. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34417. var vertexIndex = indices[index];
  34418. if (vertexIndex < minVertexIndex)
  34419. minVertexIndex = vertexIndex;
  34420. if (vertexIndex > maxVertexIndex)
  34421. maxVertexIndex = vertexIndex;
  34422. }
  34423. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34424. };
  34425. return SubMesh;
  34426. }(BaseSubMesh));
  34427. BABYLON.SubMesh = SubMesh;
  34428. })(BABYLON || (BABYLON = {}));
  34429. //# sourceMappingURL=babylon.subMesh.js.map
  34430. var __assign = (this && this.__assign) || function () {
  34431. __assign = Object.assign || function(t) {
  34432. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34433. s = arguments[i];
  34434. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34435. t[p] = s[p];
  34436. }
  34437. return t;
  34438. };
  34439. return __assign.apply(this, arguments);
  34440. };
  34441. var BABYLON;
  34442. (function (BABYLON) {
  34443. /**
  34444. * Manages the defines for the Material
  34445. */
  34446. var MaterialDefines = /** @class */ (function () {
  34447. function MaterialDefines() {
  34448. this._isDirty = true;
  34449. /** @hidden */
  34450. this._areLightsDirty = true;
  34451. /** @hidden */
  34452. this._areAttributesDirty = true;
  34453. /** @hidden */
  34454. this._areTexturesDirty = true;
  34455. /** @hidden */
  34456. this._areFresnelDirty = true;
  34457. /** @hidden */
  34458. this._areMiscDirty = true;
  34459. /** @hidden */
  34460. this._areImageProcessingDirty = true;
  34461. /** @hidden */
  34462. this._normals = false;
  34463. /** @hidden */
  34464. this._uvs = false;
  34465. /** @hidden */
  34466. this._needNormals = false;
  34467. /** @hidden */
  34468. this._needUVs = false;
  34469. }
  34470. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34471. /**
  34472. * Specifies if the material needs to be re-calculated
  34473. */
  34474. get: function () {
  34475. return this._isDirty;
  34476. },
  34477. enumerable: true,
  34478. configurable: true
  34479. });
  34480. /**
  34481. * Marks the material to indicate that it has been re-calculated
  34482. */
  34483. MaterialDefines.prototype.markAsProcessed = function () {
  34484. this._isDirty = false;
  34485. this._areAttributesDirty = false;
  34486. this._areTexturesDirty = false;
  34487. this._areFresnelDirty = false;
  34488. this._areLightsDirty = false;
  34489. this._areMiscDirty = false;
  34490. this._areImageProcessingDirty = false;
  34491. };
  34492. /**
  34493. * Marks the material to indicate that it needs to be re-calculated
  34494. */
  34495. MaterialDefines.prototype.markAsUnprocessed = function () {
  34496. this._isDirty = true;
  34497. };
  34498. /**
  34499. * Marks the material to indicate all of its defines need to be re-calculated
  34500. */
  34501. MaterialDefines.prototype.markAllAsDirty = function () {
  34502. this._areTexturesDirty = true;
  34503. this._areAttributesDirty = true;
  34504. this._areLightsDirty = true;
  34505. this._areFresnelDirty = true;
  34506. this._areMiscDirty = true;
  34507. this._areImageProcessingDirty = true;
  34508. this._isDirty = true;
  34509. };
  34510. /**
  34511. * Marks the material to indicate that image processing needs to be re-calculated
  34512. */
  34513. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34514. this._areImageProcessingDirty = true;
  34515. this._isDirty = true;
  34516. };
  34517. /**
  34518. * Marks the material to indicate the lights need to be re-calculated
  34519. */
  34520. MaterialDefines.prototype.markAsLightDirty = function () {
  34521. this._areLightsDirty = true;
  34522. this._isDirty = true;
  34523. };
  34524. /**
  34525. * Marks the attribute state as changed
  34526. */
  34527. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34528. this._areAttributesDirty = true;
  34529. this._isDirty = true;
  34530. };
  34531. /**
  34532. * Marks the texture state as changed
  34533. */
  34534. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34535. this._areTexturesDirty = true;
  34536. this._isDirty = true;
  34537. };
  34538. /**
  34539. * Marks the fresnel state as changed
  34540. */
  34541. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34542. this._areFresnelDirty = true;
  34543. this._isDirty = true;
  34544. };
  34545. /**
  34546. * Marks the misc state as changed
  34547. */
  34548. MaterialDefines.prototype.markAsMiscDirty = function () {
  34549. this._areMiscDirty = true;
  34550. this._isDirty = true;
  34551. };
  34552. /**
  34553. * Rebuilds the material defines
  34554. */
  34555. MaterialDefines.prototype.rebuild = function () {
  34556. if (this._keys) {
  34557. delete this._keys;
  34558. }
  34559. this._keys = [];
  34560. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34561. var key = _a[_i];
  34562. if (key[0] === "_") {
  34563. continue;
  34564. }
  34565. this._keys.push(key);
  34566. }
  34567. };
  34568. /**
  34569. * Specifies if two material defines are equal
  34570. * @param other - A material define instance to compare to
  34571. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34572. */
  34573. MaterialDefines.prototype.isEqual = function (other) {
  34574. if (this._keys.length !== other._keys.length) {
  34575. return false;
  34576. }
  34577. for (var index = 0; index < this._keys.length; index++) {
  34578. var prop = this._keys[index];
  34579. if (this[prop] !== other[prop]) {
  34580. return false;
  34581. }
  34582. }
  34583. return true;
  34584. };
  34585. /**
  34586. * Clones this instance's defines to another instance
  34587. * @param other - material defines to clone values to
  34588. */
  34589. MaterialDefines.prototype.cloneTo = function (other) {
  34590. if (this._keys.length !== other._keys.length) {
  34591. other._keys = this._keys.slice(0);
  34592. }
  34593. for (var index = 0; index < this._keys.length; index++) {
  34594. var prop = this._keys[index];
  34595. other[prop] = this[prop];
  34596. }
  34597. };
  34598. /**
  34599. * Resets the material define values
  34600. */
  34601. MaterialDefines.prototype.reset = function () {
  34602. for (var index = 0; index < this._keys.length; index++) {
  34603. var prop = this._keys[index];
  34604. var type = typeof this[prop];
  34605. switch (type) {
  34606. case "number":
  34607. this[prop] = 0;
  34608. break;
  34609. case "string":
  34610. this[prop] = "";
  34611. break;
  34612. default:
  34613. this[prop] = false;
  34614. break;
  34615. }
  34616. }
  34617. };
  34618. /**
  34619. * Converts the material define values to a string
  34620. * @returns - String of material define information
  34621. */
  34622. MaterialDefines.prototype.toString = function () {
  34623. var result = "";
  34624. for (var index = 0; index < this._keys.length; index++) {
  34625. var prop = this._keys[index];
  34626. var value = this[prop];
  34627. var type = typeof value;
  34628. switch (type) {
  34629. case "number":
  34630. case "string":
  34631. result += "#define " + prop + " " + value + "\n";
  34632. break;
  34633. default:
  34634. if (value) {
  34635. result += "#define " + prop + "\n";
  34636. }
  34637. break;
  34638. }
  34639. }
  34640. return result;
  34641. };
  34642. return MaterialDefines;
  34643. }());
  34644. BABYLON.MaterialDefines = MaterialDefines;
  34645. /**
  34646. * Base class for the main features of a material in Babylon.js
  34647. */
  34648. var Material = /** @class */ (function () {
  34649. /**
  34650. * Creates a material instance
  34651. * @param name defines the name of the material
  34652. * @param scene defines the scene to reference
  34653. * @param doNotAdd specifies if the material should be added to the scene
  34654. */
  34655. function Material(name, scene, doNotAdd) {
  34656. /**
  34657. * Specifies if the ready state should be checked on each call
  34658. */
  34659. this.checkReadyOnEveryCall = false;
  34660. /**
  34661. * Specifies if the ready state should be checked once
  34662. */
  34663. this.checkReadyOnlyOnce = false;
  34664. /**
  34665. * The state of the material
  34666. */
  34667. this.state = "";
  34668. /**
  34669. * The alpha value of the material
  34670. */
  34671. this._alpha = 1.0;
  34672. /**
  34673. * Specifies if back face culling is enabled
  34674. */
  34675. this._backFaceCulling = true;
  34676. /**
  34677. * Specifies if the material should be serialized
  34678. */
  34679. this.doNotSerialize = false;
  34680. /**
  34681. * Specifies if the effect should be stored on sub meshes
  34682. */
  34683. this.storeEffectOnSubMeshes = false;
  34684. /**
  34685. * An event triggered when the material is disposed
  34686. */
  34687. this.onDisposeObservable = new BABYLON.Observable();
  34688. /**
  34689. * Stores the value of the alpha mode
  34690. */
  34691. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34692. /**
  34693. * Stores the state of the need depth pre-pass value
  34694. */
  34695. this._needDepthPrePass = false;
  34696. /**
  34697. * Specifies if depth writing should be disabled
  34698. */
  34699. this.disableDepthWrite = false;
  34700. /**
  34701. * Specifies if depth writing should be forced
  34702. */
  34703. this.forceDepthWrite = false;
  34704. /**
  34705. * Specifies if there should be a separate pass for culling
  34706. */
  34707. this.separateCullingPass = false;
  34708. /**
  34709. * Stores the state specifing if fog should be enabled
  34710. */
  34711. this._fogEnabled = true;
  34712. /**
  34713. * Stores the size of points
  34714. */
  34715. this.pointSize = 1.0;
  34716. /**
  34717. * Stores the z offset value
  34718. */
  34719. this.zOffset = 0;
  34720. /**
  34721. * @hidden
  34722. * Specifies if the material was previously ready
  34723. */
  34724. this._wasPreviouslyReady = false;
  34725. /**
  34726. * Stores the fill mode state
  34727. */
  34728. this._fillMode = Material.TriangleFillMode;
  34729. this.name = name;
  34730. this.id = name || BABYLON.Tools.RandomId();
  34731. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34732. this.uniqueId = this._scene.getUniqueId();
  34733. if (this._scene.useRightHandedSystem) {
  34734. this.sideOrientation = Material.ClockWiseSideOrientation;
  34735. }
  34736. else {
  34737. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34738. }
  34739. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34740. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34741. if (!doNotAdd) {
  34742. this._scene.materials.push(this);
  34743. }
  34744. }
  34745. Object.defineProperty(Material, "TriangleFillMode", {
  34746. /**
  34747. * Returns the triangle fill mode
  34748. */
  34749. get: function () {
  34750. return Material._TriangleFillMode;
  34751. },
  34752. enumerable: true,
  34753. configurable: true
  34754. });
  34755. Object.defineProperty(Material, "WireFrameFillMode", {
  34756. /**
  34757. * Returns the wireframe mode
  34758. */
  34759. get: function () {
  34760. return Material._WireFrameFillMode;
  34761. },
  34762. enumerable: true,
  34763. configurable: true
  34764. });
  34765. Object.defineProperty(Material, "PointFillMode", {
  34766. /**
  34767. * Returns the point fill mode
  34768. */
  34769. get: function () {
  34770. return Material._PointFillMode;
  34771. },
  34772. enumerable: true,
  34773. configurable: true
  34774. });
  34775. Object.defineProperty(Material, "PointListDrawMode", {
  34776. /**
  34777. * Returns the point list draw mode
  34778. */
  34779. get: function () {
  34780. return Material._PointListDrawMode;
  34781. },
  34782. enumerable: true,
  34783. configurable: true
  34784. });
  34785. Object.defineProperty(Material, "LineListDrawMode", {
  34786. /**
  34787. * Returns the line list draw mode
  34788. */
  34789. get: function () {
  34790. return Material._LineListDrawMode;
  34791. },
  34792. enumerable: true,
  34793. configurable: true
  34794. });
  34795. Object.defineProperty(Material, "LineLoopDrawMode", {
  34796. /**
  34797. * Returns the line loop draw mode
  34798. */
  34799. get: function () {
  34800. return Material._LineLoopDrawMode;
  34801. },
  34802. enumerable: true,
  34803. configurable: true
  34804. });
  34805. Object.defineProperty(Material, "LineStripDrawMode", {
  34806. /**
  34807. * Returns the line strip draw mode
  34808. */
  34809. get: function () {
  34810. return Material._LineStripDrawMode;
  34811. },
  34812. enumerable: true,
  34813. configurable: true
  34814. });
  34815. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34816. /**
  34817. * Returns the triangle strip draw mode
  34818. */
  34819. get: function () {
  34820. return Material._TriangleStripDrawMode;
  34821. },
  34822. enumerable: true,
  34823. configurable: true
  34824. });
  34825. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34826. /**
  34827. * Returns the triangle fan draw mode
  34828. */
  34829. get: function () {
  34830. return Material._TriangleFanDrawMode;
  34831. },
  34832. enumerable: true,
  34833. configurable: true
  34834. });
  34835. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34836. /**
  34837. * Returns the clock-wise side orientation
  34838. */
  34839. get: function () {
  34840. return Material._ClockWiseSideOrientation;
  34841. },
  34842. enumerable: true,
  34843. configurable: true
  34844. });
  34845. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34846. /**
  34847. * Returns the counter clock-wise side orientation
  34848. */
  34849. get: function () {
  34850. return Material._CounterClockWiseSideOrientation;
  34851. },
  34852. enumerable: true,
  34853. configurable: true
  34854. });
  34855. Object.defineProperty(Material, "TextureDirtyFlag", {
  34856. /**
  34857. * Returns the dirty texture flag value
  34858. */
  34859. get: function () {
  34860. return Material._TextureDirtyFlag;
  34861. },
  34862. enumerable: true,
  34863. configurable: true
  34864. });
  34865. Object.defineProperty(Material, "LightDirtyFlag", {
  34866. /**
  34867. * Returns the dirty light flag value
  34868. */
  34869. get: function () {
  34870. return Material._LightDirtyFlag;
  34871. },
  34872. enumerable: true,
  34873. configurable: true
  34874. });
  34875. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34876. /**
  34877. * Returns the dirty fresnel flag value
  34878. */
  34879. get: function () {
  34880. return Material._FresnelDirtyFlag;
  34881. },
  34882. enumerable: true,
  34883. configurable: true
  34884. });
  34885. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34886. /**
  34887. * Returns the dirty attributes flag value
  34888. */
  34889. get: function () {
  34890. return Material._AttributesDirtyFlag;
  34891. },
  34892. enumerable: true,
  34893. configurable: true
  34894. });
  34895. Object.defineProperty(Material, "MiscDirtyFlag", {
  34896. /**
  34897. * Returns the dirty misc flag value
  34898. */
  34899. get: function () {
  34900. return Material._MiscDirtyFlag;
  34901. },
  34902. enumerable: true,
  34903. configurable: true
  34904. });
  34905. Object.defineProperty(Material.prototype, "alpha", {
  34906. /**
  34907. * Gets the alpha value of the material
  34908. */
  34909. get: function () {
  34910. return this._alpha;
  34911. },
  34912. /**
  34913. * Sets the alpha value of the material
  34914. */
  34915. set: function (value) {
  34916. if (this._alpha === value) {
  34917. return;
  34918. }
  34919. this._alpha = value;
  34920. this.markAsDirty(Material.MiscDirtyFlag);
  34921. },
  34922. enumerable: true,
  34923. configurable: true
  34924. });
  34925. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34926. /**
  34927. * Gets the back-face culling state
  34928. */
  34929. get: function () {
  34930. return this._backFaceCulling;
  34931. },
  34932. /**
  34933. * Sets the back-face culling state
  34934. */
  34935. set: function (value) {
  34936. if (this._backFaceCulling === value) {
  34937. return;
  34938. }
  34939. this._backFaceCulling = value;
  34940. this.markAsDirty(Material.TextureDirtyFlag);
  34941. },
  34942. enumerable: true,
  34943. configurable: true
  34944. });
  34945. Object.defineProperty(Material.prototype, "onDispose", {
  34946. /**
  34947. * Called during a dispose event
  34948. */
  34949. set: function (callback) {
  34950. if (this._onDisposeObserver) {
  34951. this.onDisposeObservable.remove(this._onDisposeObserver);
  34952. }
  34953. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34954. },
  34955. enumerable: true,
  34956. configurable: true
  34957. });
  34958. Object.defineProperty(Material.prototype, "onBindObservable", {
  34959. /**
  34960. * An event triggered when the material is bound
  34961. */
  34962. get: function () {
  34963. if (!this._onBindObservable) {
  34964. this._onBindObservable = new BABYLON.Observable();
  34965. }
  34966. return this._onBindObservable;
  34967. },
  34968. enumerable: true,
  34969. configurable: true
  34970. });
  34971. Object.defineProperty(Material.prototype, "onBind", {
  34972. /**
  34973. * Called during a bind event
  34974. */
  34975. set: function (callback) {
  34976. if (this._onBindObserver) {
  34977. this.onBindObservable.remove(this._onBindObserver);
  34978. }
  34979. this._onBindObserver = this.onBindObservable.add(callback);
  34980. },
  34981. enumerable: true,
  34982. configurable: true
  34983. });
  34984. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34985. /**
  34986. * An event triggered when the material is unbound
  34987. */
  34988. get: function () {
  34989. if (!this._onUnBindObservable) {
  34990. this._onUnBindObservable = new BABYLON.Observable();
  34991. }
  34992. return this._onUnBindObservable;
  34993. },
  34994. enumerable: true,
  34995. configurable: true
  34996. });
  34997. Object.defineProperty(Material.prototype, "alphaMode", {
  34998. /**
  34999. * Gets the value of the alpha mode
  35000. */
  35001. get: function () {
  35002. return this._alphaMode;
  35003. },
  35004. /**
  35005. * Sets the value of the alpha mode.
  35006. *
  35007. * | Value | Type | Description |
  35008. * | --- | --- | --- |
  35009. * | 0 | ALPHA_DISABLE | |
  35010. * | 1 | ALPHA_ADD | |
  35011. * | 2 | ALPHA_COMBINE | |
  35012. * | 3 | ALPHA_SUBTRACT | |
  35013. * | 4 | ALPHA_MULTIPLY | |
  35014. * | 5 | ALPHA_MAXIMIZED | |
  35015. * | 6 | ALPHA_ONEONE | |
  35016. * | 7 | ALPHA_PREMULTIPLIED | |
  35017. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35018. * | 9 | ALPHA_INTERPOLATE | |
  35019. * | 10 | ALPHA_SCREENMODE | |
  35020. *
  35021. */
  35022. set: function (value) {
  35023. if (this._alphaMode === value) {
  35024. return;
  35025. }
  35026. this._alphaMode = value;
  35027. this.markAsDirty(Material.TextureDirtyFlag);
  35028. },
  35029. enumerable: true,
  35030. configurable: true
  35031. });
  35032. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35033. /**
  35034. * Gets the depth pre-pass value
  35035. */
  35036. get: function () {
  35037. return this._needDepthPrePass;
  35038. },
  35039. /**
  35040. * Sets the need depth pre-pass value
  35041. */
  35042. set: function (value) {
  35043. if (this._needDepthPrePass === value) {
  35044. return;
  35045. }
  35046. this._needDepthPrePass = value;
  35047. if (this._needDepthPrePass) {
  35048. this.checkReadyOnEveryCall = true;
  35049. }
  35050. },
  35051. enumerable: true,
  35052. configurable: true
  35053. });
  35054. Object.defineProperty(Material.prototype, "fogEnabled", {
  35055. /**
  35056. * Gets the value of the fog enabled state
  35057. */
  35058. get: function () {
  35059. return this._fogEnabled;
  35060. },
  35061. /**
  35062. * Sets the state for enabling fog
  35063. */
  35064. set: function (value) {
  35065. if (this._fogEnabled === value) {
  35066. return;
  35067. }
  35068. this._fogEnabled = value;
  35069. this.markAsDirty(Material.MiscDirtyFlag);
  35070. },
  35071. enumerable: true,
  35072. configurable: true
  35073. });
  35074. Object.defineProperty(Material.prototype, "wireframe", {
  35075. /**
  35076. * Gets a value specifying if wireframe mode is enabled
  35077. */
  35078. get: function () {
  35079. switch (this._fillMode) {
  35080. case Material.WireFrameFillMode:
  35081. case Material.LineListDrawMode:
  35082. case Material.LineLoopDrawMode:
  35083. case Material.LineStripDrawMode:
  35084. return true;
  35085. }
  35086. return this._scene.forceWireframe;
  35087. },
  35088. /**
  35089. * Sets the state of wireframe mode
  35090. */
  35091. set: function (value) {
  35092. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35093. },
  35094. enumerable: true,
  35095. configurable: true
  35096. });
  35097. Object.defineProperty(Material.prototype, "pointsCloud", {
  35098. /**
  35099. * Gets the value specifying if point clouds are enabled
  35100. */
  35101. get: function () {
  35102. switch (this._fillMode) {
  35103. case Material.PointFillMode:
  35104. case Material.PointListDrawMode:
  35105. return true;
  35106. }
  35107. return this._scene.forcePointsCloud;
  35108. },
  35109. /**
  35110. * Sets the state of point cloud mode
  35111. */
  35112. set: function (value) {
  35113. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35114. },
  35115. enumerable: true,
  35116. configurable: true
  35117. });
  35118. Object.defineProperty(Material.prototype, "fillMode", {
  35119. /**
  35120. * Gets the material fill mode
  35121. */
  35122. get: function () {
  35123. return this._fillMode;
  35124. },
  35125. /**
  35126. * Sets the material fill mode
  35127. */
  35128. set: function (value) {
  35129. if (this._fillMode === value) {
  35130. return;
  35131. }
  35132. this._fillMode = value;
  35133. this.markAsDirty(Material.MiscDirtyFlag);
  35134. },
  35135. enumerable: true,
  35136. configurable: true
  35137. });
  35138. /**
  35139. * Returns a string representation of the current material
  35140. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35141. * @returns a string with material information
  35142. */
  35143. Material.prototype.toString = function (fullDetails) {
  35144. var ret = "Name: " + this.name;
  35145. if (fullDetails) {
  35146. }
  35147. return ret;
  35148. };
  35149. /**
  35150. * Gets the class name of the material
  35151. * @returns a string with the class name of the material
  35152. */
  35153. Material.prototype.getClassName = function () {
  35154. return "Material";
  35155. };
  35156. Object.defineProperty(Material.prototype, "isFrozen", {
  35157. /**
  35158. * Specifies if updates for the material been locked
  35159. */
  35160. get: function () {
  35161. return this.checkReadyOnlyOnce;
  35162. },
  35163. enumerable: true,
  35164. configurable: true
  35165. });
  35166. /**
  35167. * Locks updates for the material
  35168. */
  35169. Material.prototype.freeze = function () {
  35170. this.checkReadyOnlyOnce = true;
  35171. };
  35172. /**
  35173. * Unlocks updates for the material
  35174. */
  35175. Material.prototype.unfreeze = function () {
  35176. this.checkReadyOnlyOnce = false;
  35177. };
  35178. /**
  35179. * Specifies if the material is ready to be used
  35180. * @param mesh defines the mesh to check
  35181. * @param useInstances specifies if instances should be used
  35182. * @returns a boolean indicating if the material is ready to be used
  35183. */
  35184. Material.prototype.isReady = function (mesh, useInstances) {
  35185. return true;
  35186. };
  35187. /**
  35188. * Specifies that the submesh is ready to be used
  35189. * @param mesh defines the mesh to check
  35190. * @param subMesh defines which submesh to check
  35191. * @param useInstances specifies that instances should be used
  35192. * @returns a boolean indicating that the submesh is ready or not
  35193. */
  35194. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35195. return false;
  35196. };
  35197. /**
  35198. * Returns the material effect
  35199. * @returns the effect associated with the material
  35200. */
  35201. Material.prototype.getEffect = function () {
  35202. return this._effect;
  35203. };
  35204. /**
  35205. * Returns the current scene
  35206. * @returns a Scene
  35207. */
  35208. Material.prototype.getScene = function () {
  35209. return this._scene;
  35210. };
  35211. /**
  35212. * Specifies if the material will require alpha blending
  35213. * @returns a boolean specifying if alpha blending is needed
  35214. */
  35215. Material.prototype.needAlphaBlending = function () {
  35216. return (this.alpha < 1.0);
  35217. };
  35218. /**
  35219. * Specifies if the mesh will require alpha blending
  35220. * @param mesh defines the mesh to check
  35221. * @returns a boolean specifying if alpha blending is needed for the mesh
  35222. */
  35223. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35224. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35225. };
  35226. /**
  35227. * Specifies if this material should be rendered in alpha test mode
  35228. * @returns a boolean specifying if an alpha test is needed.
  35229. */
  35230. Material.prototype.needAlphaTesting = function () {
  35231. return false;
  35232. };
  35233. /**
  35234. * Gets the texture used for the alpha test
  35235. * @returns the texture to use for alpha testing
  35236. */
  35237. Material.prototype.getAlphaTestTexture = function () {
  35238. return null;
  35239. };
  35240. /**
  35241. * Marks the material to indicate that it needs to be re-calculated
  35242. */
  35243. Material.prototype.markDirty = function () {
  35244. this._wasPreviouslyReady = false;
  35245. };
  35246. /** @hidden */
  35247. Material.prototype._preBind = function (effect, overrideOrientation) {
  35248. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35249. var engine = this._scene.getEngine();
  35250. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35251. var reverse = orientation === Material.ClockWiseSideOrientation;
  35252. engine.enableEffect(effect ? effect : this._effect);
  35253. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35254. return reverse;
  35255. };
  35256. /**
  35257. * Binds the material to the mesh
  35258. * @param world defines the world transformation matrix
  35259. * @param mesh defines the mesh to bind the material to
  35260. */
  35261. Material.prototype.bind = function (world, mesh) {
  35262. };
  35263. /**
  35264. * Binds the submesh to the material
  35265. * @param world defines the world transformation matrix
  35266. * @param mesh defines the mesh containing the submesh
  35267. * @param subMesh defines the submesh to bind the material to
  35268. */
  35269. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35270. };
  35271. /**
  35272. * Binds the world matrix to the material
  35273. * @param world defines the world transformation matrix
  35274. */
  35275. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35276. };
  35277. /**
  35278. * Binds the scene's uniform buffer to the effect.
  35279. * @param effect defines the effect to bind to the scene uniform buffer
  35280. * @param sceneUbo defines the uniform buffer storing scene data
  35281. */
  35282. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35283. sceneUbo.bindToEffect(effect, "Scene");
  35284. };
  35285. /**
  35286. * Binds the view matrix to the effect
  35287. * @param effect defines the effect to bind the view matrix to
  35288. */
  35289. Material.prototype.bindView = function (effect) {
  35290. if (!this._useUBO) {
  35291. effect.setMatrix("view", this.getScene().getViewMatrix());
  35292. }
  35293. else {
  35294. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35295. }
  35296. };
  35297. /**
  35298. * Binds the view projection matrix to the effect
  35299. * @param effect defines the effect to bind the view projection matrix to
  35300. */
  35301. Material.prototype.bindViewProjection = function (effect) {
  35302. if (!this._useUBO) {
  35303. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35304. }
  35305. else {
  35306. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35307. }
  35308. };
  35309. /**
  35310. * Specifies if material alpha testing should be turned on for the mesh
  35311. * @param mesh defines the mesh to check
  35312. */
  35313. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35314. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35315. };
  35316. /**
  35317. * Processes to execute after binding the material to a mesh
  35318. * @param mesh defines the rendered mesh
  35319. */
  35320. Material.prototype._afterBind = function (mesh) {
  35321. this._scene._cachedMaterial = this;
  35322. if (mesh) {
  35323. this._scene._cachedVisibility = mesh.visibility;
  35324. }
  35325. else {
  35326. this._scene._cachedVisibility = 1;
  35327. }
  35328. if (this._onBindObservable && mesh) {
  35329. this._onBindObservable.notifyObservers(mesh);
  35330. }
  35331. if (this.disableDepthWrite) {
  35332. var engine = this._scene.getEngine();
  35333. this._cachedDepthWriteState = engine.getDepthWrite();
  35334. engine.setDepthWrite(false);
  35335. }
  35336. };
  35337. /**
  35338. * Unbinds the material from the mesh
  35339. */
  35340. Material.prototype.unbind = function () {
  35341. if (this._onUnBindObservable) {
  35342. this._onUnBindObservable.notifyObservers(this);
  35343. }
  35344. if (this.disableDepthWrite) {
  35345. var engine = this._scene.getEngine();
  35346. engine.setDepthWrite(this._cachedDepthWriteState);
  35347. }
  35348. };
  35349. /**
  35350. * Gets the active textures from the material
  35351. * @returns an array of textures
  35352. */
  35353. Material.prototype.getActiveTextures = function () {
  35354. return [];
  35355. };
  35356. /**
  35357. * Specifies if the material uses a texture
  35358. * @param texture defines the texture to check against the material
  35359. * @returns a boolean specifying if the material uses the texture
  35360. */
  35361. Material.prototype.hasTexture = function (texture) {
  35362. return false;
  35363. };
  35364. /**
  35365. * Makes a duplicate of the material, and gives it a new name
  35366. * @param name defines the new name for the duplicated material
  35367. * @returns the cloned material
  35368. */
  35369. Material.prototype.clone = function (name) {
  35370. return null;
  35371. };
  35372. /**
  35373. * Gets the meshes bound to the material
  35374. * @returns an array of meshes bound to the material
  35375. */
  35376. Material.prototype.getBindedMeshes = function () {
  35377. var result = new Array();
  35378. for (var index = 0; index < this._scene.meshes.length; index++) {
  35379. var mesh = this._scene.meshes[index];
  35380. if (mesh.material === this) {
  35381. result.push(mesh);
  35382. }
  35383. }
  35384. return result;
  35385. };
  35386. /**
  35387. * Force shader compilation
  35388. * @param mesh defines the mesh associated with this material
  35389. * @param onCompiled defines a function to execute once the material is compiled
  35390. * @param options defines the options to configure the compilation
  35391. */
  35392. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35393. var _this = this;
  35394. var localOptions = __assign({ clipPlane: false }, options);
  35395. var subMesh = new BABYLON.BaseSubMesh();
  35396. var scene = this.getScene();
  35397. var checkReady = function () {
  35398. if (!_this._scene || !_this._scene.getEngine()) {
  35399. return;
  35400. }
  35401. if (subMesh._materialDefines) {
  35402. subMesh._materialDefines._renderId = -1;
  35403. }
  35404. var clipPlaneState = scene.clipPlane;
  35405. if (localOptions.clipPlane) {
  35406. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35407. }
  35408. if (_this.storeEffectOnSubMeshes) {
  35409. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35410. if (onCompiled) {
  35411. onCompiled(_this);
  35412. }
  35413. }
  35414. else {
  35415. setTimeout(checkReady, 16);
  35416. }
  35417. }
  35418. else {
  35419. if (_this.isReady(mesh)) {
  35420. if (onCompiled) {
  35421. onCompiled(_this);
  35422. }
  35423. }
  35424. else {
  35425. setTimeout(checkReady, 16);
  35426. }
  35427. }
  35428. if (localOptions.clipPlane) {
  35429. scene.clipPlane = clipPlaneState;
  35430. }
  35431. };
  35432. checkReady();
  35433. };
  35434. /**
  35435. * Force shader compilation
  35436. * @param mesh defines the mesh that will use this material
  35437. * @param options defines additional options for compiling the shaders
  35438. * @returns a promise that resolves when the compilation completes
  35439. */
  35440. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35441. var _this = this;
  35442. return new Promise(function (resolve) {
  35443. _this.forceCompilation(mesh, function () {
  35444. resolve();
  35445. }, options);
  35446. });
  35447. };
  35448. /**
  35449. * Marks a define in the material to indicate that it needs to be re-computed
  35450. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35451. */
  35452. Material.prototype.markAsDirty = function (flag) {
  35453. if (flag & Material.TextureDirtyFlag) {
  35454. this._markAllSubMeshesAsTexturesDirty();
  35455. }
  35456. if (flag & Material.LightDirtyFlag) {
  35457. this._markAllSubMeshesAsLightsDirty();
  35458. }
  35459. if (flag & Material.FresnelDirtyFlag) {
  35460. this._markAllSubMeshesAsFresnelDirty();
  35461. }
  35462. if (flag & Material.AttributesDirtyFlag) {
  35463. this._markAllSubMeshesAsAttributesDirty();
  35464. }
  35465. if (flag & Material.MiscDirtyFlag) {
  35466. this._markAllSubMeshesAsMiscDirty();
  35467. }
  35468. this.getScene().resetCachedMaterial();
  35469. };
  35470. /**
  35471. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35472. * @param func defines a function which checks material defines against the submeshes
  35473. */
  35474. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35475. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35476. var mesh = _a[_i];
  35477. if (!mesh.subMeshes) {
  35478. continue;
  35479. }
  35480. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35481. var subMesh = _c[_b];
  35482. if (subMesh.getMaterial() !== this) {
  35483. continue;
  35484. }
  35485. if (!subMesh._materialDefines) {
  35486. continue;
  35487. }
  35488. func(subMesh._materialDefines);
  35489. }
  35490. }
  35491. };
  35492. /**
  35493. * Indicates that image processing needs to be re-calculated for all submeshes
  35494. */
  35495. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35496. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35497. };
  35498. /**
  35499. * Indicates that textures need to be re-calculated for all submeshes
  35500. */
  35501. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35502. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35503. };
  35504. /**
  35505. * Indicates that fresnel needs to be re-calculated for all submeshes
  35506. */
  35507. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35508. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35509. };
  35510. /**
  35511. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35512. */
  35513. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35514. this._markAllSubMeshesAsDirty(function (defines) {
  35515. defines.markAsFresnelDirty();
  35516. defines.markAsMiscDirty();
  35517. });
  35518. };
  35519. /**
  35520. * Indicates that lights need to be re-calculated for all submeshes
  35521. */
  35522. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35523. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35524. };
  35525. /**
  35526. * Indicates that attributes need to be re-calculated for all submeshes
  35527. */
  35528. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35529. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35530. };
  35531. /**
  35532. * Indicates that misc needs to be re-calculated for all submeshes
  35533. */
  35534. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35535. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35536. };
  35537. /**
  35538. * Indicates that textures and misc need to be re-calculated for all submeshes
  35539. */
  35540. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35541. this._markAllSubMeshesAsDirty(function (defines) {
  35542. defines.markAsTexturesDirty();
  35543. defines.markAsMiscDirty();
  35544. });
  35545. };
  35546. /**
  35547. * Disposes the material
  35548. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35549. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35550. */
  35551. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35552. // Animations
  35553. this.getScene().stopAnimation(this);
  35554. this.getScene().freeProcessedMaterials();
  35555. // Remove from scene
  35556. var index = this._scene.materials.indexOf(this);
  35557. if (index >= 0) {
  35558. this._scene.materials.splice(index, 1);
  35559. }
  35560. // Remove from meshes
  35561. for (index = 0; index < this._scene.meshes.length; index++) {
  35562. var mesh = this._scene.meshes[index];
  35563. if (mesh.material === this) {
  35564. mesh.material = null;
  35565. if (mesh.geometry) {
  35566. var geometry = (mesh.geometry);
  35567. if (this.storeEffectOnSubMeshes) {
  35568. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35569. var subMesh = _a[_i];
  35570. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35571. if (forceDisposeEffect && subMesh._materialEffect) {
  35572. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35573. }
  35574. }
  35575. }
  35576. else {
  35577. geometry._releaseVertexArrayObject(this._effect);
  35578. }
  35579. }
  35580. }
  35581. }
  35582. this._uniformBuffer.dispose();
  35583. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35584. if (forceDisposeEffect && this._effect) {
  35585. if (!this.storeEffectOnSubMeshes) {
  35586. this._scene.getEngine()._releaseEffect(this._effect);
  35587. }
  35588. this._effect = null;
  35589. }
  35590. // Callback
  35591. this.onDisposeObservable.notifyObservers(this);
  35592. this.onDisposeObservable.clear();
  35593. if (this._onBindObservable) {
  35594. this._onBindObservable.clear();
  35595. }
  35596. if (this._onUnBindObservable) {
  35597. this._onUnBindObservable.clear();
  35598. }
  35599. };
  35600. /**
  35601. * Serializes this material
  35602. * @returns the serialized material object
  35603. */
  35604. Material.prototype.serialize = function () {
  35605. return BABYLON.SerializationHelper.Serialize(this);
  35606. };
  35607. /**
  35608. * Creates a MultiMaterial from parsed MultiMaterial data.
  35609. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35610. * @param scene defines the hosting scene
  35611. * @returns a new MultiMaterial
  35612. */
  35613. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35614. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35615. multiMaterial.id = parsedMultiMaterial.id;
  35616. if (BABYLON.Tags) {
  35617. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35618. }
  35619. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35620. var subMatId = parsedMultiMaterial.materials[matIndex];
  35621. if (subMatId) {
  35622. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35623. }
  35624. else {
  35625. multiMaterial.subMaterials.push(null);
  35626. }
  35627. }
  35628. return multiMaterial;
  35629. };
  35630. /**
  35631. * Creates a material from parsed material data
  35632. * @param parsedMaterial defines parsed material data
  35633. * @param scene defines the hosting scene
  35634. * @param rootUrl defines the root URL to use to load textures
  35635. * @returns a new material
  35636. */
  35637. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35638. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35639. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35640. }
  35641. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35642. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35643. if (!BABYLON.LegacyPBRMaterial) {
  35644. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35645. return;
  35646. }
  35647. }
  35648. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35649. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35650. };
  35651. // Triangle views
  35652. Material._TriangleFillMode = 0;
  35653. Material._WireFrameFillMode = 1;
  35654. Material._PointFillMode = 2;
  35655. // Draw modes
  35656. Material._PointListDrawMode = 3;
  35657. Material._LineListDrawMode = 4;
  35658. Material._LineLoopDrawMode = 5;
  35659. Material._LineStripDrawMode = 6;
  35660. Material._TriangleStripDrawMode = 7;
  35661. Material._TriangleFanDrawMode = 8;
  35662. /**
  35663. * Stores the clock-wise side orientation
  35664. */
  35665. Material._ClockWiseSideOrientation = 0;
  35666. /**
  35667. * Stores the counter clock-wise side orientation
  35668. */
  35669. Material._CounterClockWiseSideOrientation = 1;
  35670. /**
  35671. * The dirty texture flag value
  35672. */
  35673. Material._TextureDirtyFlag = 1;
  35674. /**
  35675. * The dirty light flag value
  35676. */
  35677. Material._LightDirtyFlag = 2;
  35678. /**
  35679. * The dirty fresnel flag value
  35680. */
  35681. Material._FresnelDirtyFlag = 4;
  35682. /**
  35683. * The dirty attribute flag value
  35684. */
  35685. Material._AttributesDirtyFlag = 8;
  35686. /**
  35687. * The dirty misc flag value
  35688. */
  35689. Material._MiscDirtyFlag = 16;
  35690. __decorate([
  35691. BABYLON.serialize()
  35692. ], Material.prototype, "id", void 0);
  35693. __decorate([
  35694. BABYLON.serialize()
  35695. ], Material.prototype, "uniqueId", void 0);
  35696. __decorate([
  35697. BABYLON.serialize()
  35698. ], Material.prototype, "name", void 0);
  35699. __decorate([
  35700. BABYLON.serialize()
  35701. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35702. __decorate([
  35703. BABYLON.serialize()
  35704. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35705. __decorate([
  35706. BABYLON.serialize()
  35707. ], Material.prototype, "state", void 0);
  35708. __decorate([
  35709. BABYLON.serialize("alpha")
  35710. ], Material.prototype, "_alpha", void 0);
  35711. __decorate([
  35712. BABYLON.serialize("backFaceCulling")
  35713. ], Material.prototype, "_backFaceCulling", void 0);
  35714. __decorate([
  35715. BABYLON.serialize()
  35716. ], Material.prototype, "sideOrientation", void 0);
  35717. __decorate([
  35718. BABYLON.serialize("alphaMode")
  35719. ], Material.prototype, "_alphaMode", void 0);
  35720. __decorate([
  35721. BABYLON.serialize()
  35722. ], Material.prototype, "_needDepthPrePass", void 0);
  35723. __decorate([
  35724. BABYLON.serialize()
  35725. ], Material.prototype, "disableDepthWrite", void 0);
  35726. __decorate([
  35727. BABYLON.serialize()
  35728. ], Material.prototype, "forceDepthWrite", void 0);
  35729. __decorate([
  35730. BABYLON.serialize()
  35731. ], Material.prototype, "separateCullingPass", void 0);
  35732. __decorate([
  35733. BABYLON.serialize("fogEnabled")
  35734. ], Material.prototype, "_fogEnabled", void 0);
  35735. __decorate([
  35736. BABYLON.serialize()
  35737. ], Material.prototype, "pointSize", void 0);
  35738. __decorate([
  35739. BABYLON.serialize()
  35740. ], Material.prototype, "zOffset", void 0);
  35741. __decorate([
  35742. BABYLON.serialize()
  35743. ], Material.prototype, "wireframe", null);
  35744. __decorate([
  35745. BABYLON.serialize()
  35746. ], Material.prototype, "pointsCloud", null);
  35747. __decorate([
  35748. BABYLON.serialize()
  35749. ], Material.prototype, "fillMode", null);
  35750. return Material;
  35751. }());
  35752. BABYLON.Material = Material;
  35753. })(BABYLON || (BABYLON = {}));
  35754. //# sourceMappingURL=babylon.material.js.map
  35755. var BABYLON;
  35756. (function (BABYLON) {
  35757. var UniformBuffer = /** @class */ (function () {
  35758. /**
  35759. * Uniform buffer objects.
  35760. *
  35761. * Handles blocks of uniform on the GPU.
  35762. *
  35763. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35764. *
  35765. * For more information, please refer to :
  35766. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35767. */
  35768. function UniformBuffer(engine, data, dynamic) {
  35769. this._engine = engine;
  35770. this._noUBO = !engine.supportsUniformBuffers;
  35771. this._dynamic = dynamic;
  35772. this._data = data || [];
  35773. this._uniformLocations = {};
  35774. this._uniformSizes = {};
  35775. this._uniformLocationPointer = 0;
  35776. this._needSync = false;
  35777. if (this._noUBO) {
  35778. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35779. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35780. this.updateFloat = this._updateFloatForEffect;
  35781. this.updateFloat2 = this._updateFloat2ForEffect;
  35782. this.updateFloat3 = this._updateFloat3ForEffect;
  35783. this.updateFloat4 = this._updateFloat4ForEffect;
  35784. this.updateMatrix = this._updateMatrixForEffect;
  35785. this.updateVector3 = this._updateVector3ForEffect;
  35786. this.updateVector4 = this._updateVector4ForEffect;
  35787. this.updateColor3 = this._updateColor3ForEffect;
  35788. this.updateColor4 = this._updateColor4ForEffect;
  35789. }
  35790. else {
  35791. this._engine._uniformBuffers.push(this);
  35792. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35793. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35794. this.updateFloat = this._updateFloatForUniform;
  35795. this.updateFloat2 = this._updateFloat2ForUniform;
  35796. this.updateFloat3 = this._updateFloat3ForUniform;
  35797. this.updateFloat4 = this._updateFloat4ForUniform;
  35798. this.updateMatrix = this._updateMatrixForUniform;
  35799. this.updateVector3 = this._updateVector3ForUniform;
  35800. this.updateVector4 = this._updateVector4ForUniform;
  35801. this.updateColor3 = this._updateColor3ForUniform;
  35802. this.updateColor4 = this._updateColor4ForUniform;
  35803. }
  35804. }
  35805. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35806. // Properties
  35807. /**
  35808. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35809. * or just falling back on setUniformXXX calls.
  35810. */
  35811. get: function () {
  35812. return !this._noUBO;
  35813. },
  35814. enumerable: true,
  35815. configurable: true
  35816. });
  35817. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35818. /**
  35819. * Indicates if the WebGL underlying uniform buffer is in sync
  35820. * with the javascript cache data.
  35821. */
  35822. get: function () {
  35823. return !this._needSync;
  35824. },
  35825. enumerable: true,
  35826. configurable: true
  35827. });
  35828. /**
  35829. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35830. * Also, a dynamic UniformBuffer will disable cache verification and always
  35831. * update the underlying WebGL uniform buffer to the GPU.
  35832. */
  35833. UniformBuffer.prototype.isDynamic = function () {
  35834. return this._dynamic !== undefined;
  35835. };
  35836. /**
  35837. * The data cache on JS side.
  35838. */
  35839. UniformBuffer.prototype.getData = function () {
  35840. return this._bufferData;
  35841. };
  35842. /**
  35843. * The underlying WebGL Uniform buffer.
  35844. */
  35845. UniformBuffer.prototype.getBuffer = function () {
  35846. return this._buffer;
  35847. };
  35848. /**
  35849. * std140 layout specifies how to align data within an UBO structure.
  35850. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35851. * for specs.
  35852. */
  35853. UniformBuffer.prototype._fillAlignment = function (size) {
  35854. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35855. // and 4x4 matrices
  35856. // TODO : change if other types are used
  35857. var alignment;
  35858. if (size <= 2) {
  35859. alignment = size;
  35860. }
  35861. else {
  35862. alignment = 4;
  35863. }
  35864. if ((this._uniformLocationPointer % alignment) !== 0) {
  35865. var oldPointer = this._uniformLocationPointer;
  35866. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35867. var diff = this._uniformLocationPointer - oldPointer;
  35868. for (var i = 0; i < diff; i++) {
  35869. this._data.push(0);
  35870. }
  35871. }
  35872. };
  35873. /**
  35874. * Adds an uniform in the buffer.
  35875. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35876. * for the layout to be correct !
  35877. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35878. * @param {number|number[]} size Data size, or data directly.
  35879. */
  35880. UniformBuffer.prototype.addUniform = function (name, size) {
  35881. if (this._noUBO) {
  35882. return;
  35883. }
  35884. if (this._uniformLocations[name] !== undefined) {
  35885. // Already existing uniform
  35886. return;
  35887. }
  35888. // This function must be called in the order of the shader layout !
  35889. // size can be the size of the uniform, or data directly
  35890. var data;
  35891. if (size instanceof Array) {
  35892. data = size;
  35893. size = data.length;
  35894. }
  35895. else {
  35896. size = size;
  35897. data = [];
  35898. // Fill with zeros
  35899. for (var i = 0; i < size; i++) {
  35900. data.push(0);
  35901. }
  35902. }
  35903. this._fillAlignment(size);
  35904. this._uniformSizes[name] = size;
  35905. this._uniformLocations[name] = this._uniformLocationPointer;
  35906. this._uniformLocationPointer += size;
  35907. for (var i = 0; i < size; i++) {
  35908. this._data.push(data[i]);
  35909. }
  35910. this._needSync = true;
  35911. };
  35912. /**
  35913. * Wrapper for addUniform.
  35914. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35915. * @param {Matrix} mat A 4x4 matrix.
  35916. */
  35917. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35918. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35919. };
  35920. /**
  35921. * Wrapper for addUniform.
  35922. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35923. * @param {number} x
  35924. * @param {number} y
  35925. */
  35926. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35927. var temp = [x, y];
  35928. this.addUniform(name, temp);
  35929. };
  35930. /**
  35931. * Wrapper for addUniform.
  35932. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35933. * @param {number} x
  35934. * @param {number} y
  35935. * @param {number} z
  35936. */
  35937. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35938. var temp = [x, y, z];
  35939. this.addUniform(name, temp);
  35940. };
  35941. /**
  35942. * Wrapper for addUniform.
  35943. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35944. * @param {Color3} color
  35945. */
  35946. UniformBuffer.prototype.addColor3 = function (name, color) {
  35947. var temp = new Array();
  35948. color.toArray(temp);
  35949. this.addUniform(name, temp);
  35950. };
  35951. /**
  35952. * Wrapper for addUniform.
  35953. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35954. * @param {Color3} color
  35955. * @param {number} alpha
  35956. */
  35957. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35958. var temp = new Array();
  35959. color.toArray(temp);
  35960. temp.push(alpha);
  35961. this.addUniform(name, temp);
  35962. };
  35963. /**
  35964. * Wrapper for addUniform.
  35965. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35966. * @param {Vector3} vector
  35967. */
  35968. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35969. var temp = new Array();
  35970. vector.toArray(temp);
  35971. this.addUniform(name, temp);
  35972. };
  35973. /**
  35974. * Wrapper for addUniform.
  35975. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35976. */
  35977. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35978. this.addUniform(name, 12);
  35979. };
  35980. /**
  35981. * Wrapper for addUniform.
  35982. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35983. */
  35984. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35985. this.addUniform(name, 8);
  35986. };
  35987. /**
  35988. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35989. */
  35990. UniformBuffer.prototype.create = function () {
  35991. if (this._noUBO) {
  35992. return;
  35993. }
  35994. if (this._buffer) {
  35995. return; // nothing to do
  35996. }
  35997. // See spec, alignment must be filled as a vec4
  35998. this._fillAlignment(4);
  35999. this._bufferData = new Float32Array(this._data);
  36000. this._rebuild();
  36001. this._needSync = true;
  36002. };
  36003. /** @hidden */
  36004. UniformBuffer.prototype._rebuild = function () {
  36005. if (this._noUBO) {
  36006. return;
  36007. }
  36008. if (this._dynamic) {
  36009. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36010. }
  36011. else {
  36012. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36013. }
  36014. };
  36015. /**
  36016. * Updates the WebGL Uniform Buffer on the GPU.
  36017. * If the `dynamic` flag is set to true, no cache comparison is done.
  36018. * Otherwise, the buffer will be updated only if the cache differs.
  36019. */
  36020. UniformBuffer.prototype.update = function () {
  36021. if (!this._buffer) {
  36022. this.create();
  36023. return;
  36024. }
  36025. if (!this._dynamic && !this._needSync) {
  36026. return;
  36027. }
  36028. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36029. this._needSync = false;
  36030. };
  36031. /**
  36032. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36033. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36034. * @param {number[]|Float32Array} data Flattened data
  36035. * @param {number} size Size of the data.
  36036. */
  36037. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36038. var location = this._uniformLocations[uniformName];
  36039. if (location === undefined) {
  36040. if (this._buffer) {
  36041. // Cannot add an uniform if the buffer is already created
  36042. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36043. return;
  36044. }
  36045. this.addUniform(uniformName, size);
  36046. location = this._uniformLocations[uniformName];
  36047. }
  36048. if (!this._buffer) {
  36049. this.create();
  36050. }
  36051. if (!this._dynamic) {
  36052. // Cache for static uniform buffers
  36053. var changed = false;
  36054. for (var i = 0; i < size; i++) {
  36055. if (this._bufferData[location + i] !== data[i]) {
  36056. changed = true;
  36057. this._bufferData[location + i] = data[i];
  36058. }
  36059. }
  36060. this._needSync = this._needSync || changed;
  36061. }
  36062. else {
  36063. // No cache for dynamic
  36064. for (var i = 0; i < size; i++) {
  36065. this._bufferData[location + i] = data[i];
  36066. }
  36067. }
  36068. };
  36069. // Update methods
  36070. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36071. // To match std140, matrix must be realigned
  36072. for (var i = 0; i < 3; i++) {
  36073. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36074. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36075. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36076. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36077. }
  36078. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36079. };
  36080. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36081. this._currentEffect.setMatrix3x3(name, matrix);
  36082. };
  36083. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36084. this._currentEffect.setMatrix2x2(name, matrix);
  36085. };
  36086. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36087. // To match std140, matrix must be realigned
  36088. for (var i = 0; i < 2; i++) {
  36089. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36090. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36091. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36092. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36093. }
  36094. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36095. };
  36096. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36097. this._currentEffect.setFloat(name, x);
  36098. };
  36099. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36100. UniformBuffer._tempBuffer[0] = x;
  36101. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36102. };
  36103. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36104. if (suffix === void 0) { suffix = ""; }
  36105. this._currentEffect.setFloat2(name + suffix, x, y);
  36106. };
  36107. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36108. if (suffix === void 0) { suffix = ""; }
  36109. UniformBuffer._tempBuffer[0] = x;
  36110. UniformBuffer._tempBuffer[1] = y;
  36111. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36112. };
  36113. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36114. if (suffix === void 0) { suffix = ""; }
  36115. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36116. };
  36117. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36118. if (suffix === void 0) { suffix = ""; }
  36119. UniformBuffer._tempBuffer[0] = x;
  36120. UniformBuffer._tempBuffer[1] = y;
  36121. UniformBuffer._tempBuffer[2] = z;
  36122. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36123. };
  36124. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36125. if (suffix === void 0) { suffix = ""; }
  36126. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36127. };
  36128. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36129. if (suffix === void 0) { suffix = ""; }
  36130. UniformBuffer._tempBuffer[0] = x;
  36131. UniformBuffer._tempBuffer[1] = y;
  36132. UniformBuffer._tempBuffer[2] = z;
  36133. UniformBuffer._tempBuffer[3] = w;
  36134. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36135. };
  36136. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36137. this._currentEffect.setMatrix(name, mat);
  36138. };
  36139. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36140. this.updateUniform(name, mat.toArray(), 16);
  36141. };
  36142. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36143. this._currentEffect.setVector3(name, vector);
  36144. };
  36145. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36146. vector.toArray(UniformBuffer._tempBuffer);
  36147. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36148. };
  36149. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36150. this._currentEffect.setVector4(name, vector);
  36151. };
  36152. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36153. vector.toArray(UniformBuffer._tempBuffer);
  36154. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36155. };
  36156. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36157. if (suffix === void 0) { suffix = ""; }
  36158. this._currentEffect.setColor3(name + suffix, color);
  36159. };
  36160. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36161. if (suffix === void 0) { suffix = ""; }
  36162. color.toArray(UniformBuffer._tempBuffer);
  36163. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36164. };
  36165. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36166. if (suffix === void 0) { suffix = ""; }
  36167. this._currentEffect.setColor4(name + suffix, color, alpha);
  36168. };
  36169. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36170. if (suffix === void 0) { suffix = ""; }
  36171. color.toArray(UniformBuffer._tempBuffer);
  36172. UniformBuffer._tempBuffer[3] = alpha;
  36173. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36174. };
  36175. /**
  36176. * Sets a sampler uniform on the effect.
  36177. * @param {string} name Name of the sampler.
  36178. * @param {Texture} texture
  36179. */
  36180. UniformBuffer.prototype.setTexture = function (name, texture) {
  36181. this._currentEffect.setTexture(name, texture);
  36182. };
  36183. /**
  36184. * Directly updates the value of the uniform in the cache AND on the GPU.
  36185. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36186. * @param {number[]|Float32Array} data Flattened data
  36187. */
  36188. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36189. this.updateUniform(uniformName, data, data.length);
  36190. this.update();
  36191. };
  36192. /**
  36193. * Binds this uniform buffer to an effect.
  36194. * @param {Effect} effect
  36195. * @param {string} name Name of the uniform block in the shader.
  36196. */
  36197. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36198. this._currentEffect = effect;
  36199. if (this._noUBO || !this._buffer) {
  36200. return;
  36201. }
  36202. effect.bindUniformBuffer(this._buffer, name);
  36203. };
  36204. /**
  36205. * Disposes the uniform buffer.
  36206. */
  36207. UniformBuffer.prototype.dispose = function () {
  36208. if (this._noUBO) {
  36209. return;
  36210. }
  36211. var index = this._engine._uniformBuffers.indexOf(this);
  36212. if (index !== -1) {
  36213. this._engine._uniformBuffers.splice(index, 1);
  36214. }
  36215. if (!this._buffer) {
  36216. return;
  36217. }
  36218. if (this._engine._releaseBuffer(this._buffer)) {
  36219. this._buffer = null;
  36220. }
  36221. };
  36222. // Pool for avoiding memory leaks
  36223. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36224. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36225. return UniformBuffer;
  36226. }());
  36227. BABYLON.UniformBuffer = UniformBuffer;
  36228. })(BABYLON || (BABYLON = {}));
  36229. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36230. var BABYLON;
  36231. (function (BABYLON) {
  36232. /**
  36233. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36234. */
  36235. var VertexData = /** @class */ (function () {
  36236. function VertexData() {
  36237. }
  36238. /**
  36239. * Uses the passed data array to set the set the values for the specified kind of data
  36240. * @param data a linear array of floating numbers
  36241. * @param kind the type of data that is being set, eg positions, colors etc
  36242. */
  36243. VertexData.prototype.set = function (data, kind) {
  36244. switch (kind) {
  36245. case BABYLON.VertexBuffer.PositionKind:
  36246. this.positions = data;
  36247. break;
  36248. case BABYLON.VertexBuffer.NormalKind:
  36249. this.normals = data;
  36250. break;
  36251. case BABYLON.VertexBuffer.TangentKind:
  36252. this.tangents = data;
  36253. break;
  36254. case BABYLON.VertexBuffer.UVKind:
  36255. this.uvs = data;
  36256. break;
  36257. case BABYLON.VertexBuffer.UV2Kind:
  36258. this.uvs2 = data;
  36259. break;
  36260. case BABYLON.VertexBuffer.UV3Kind:
  36261. this.uvs3 = data;
  36262. break;
  36263. case BABYLON.VertexBuffer.UV4Kind:
  36264. this.uvs4 = data;
  36265. break;
  36266. case BABYLON.VertexBuffer.UV5Kind:
  36267. this.uvs5 = data;
  36268. break;
  36269. case BABYLON.VertexBuffer.UV6Kind:
  36270. this.uvs6 = data;
  36271. break;
  36272. case BABYLON.VertexBuffer.ColorKind:
  36273. this.colors = data;
  36274. break;
  36275. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36276. this.matricesIndices = data;
  36277. break;
  36278. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36279. this.matricesWeights = data;
  36280. break;
  36281. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36282. this.matricesIndicesExtra = data;
  36283. break;
  36284. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36285. this.matricesWeightsExtra = data;
  36286. break;
  36287. }
  36288. };
  36289. /**
  36290. * Associates the vertexData to the passed Mesh.
  36291. * Sets it as updatable or not (default `false`)
  36292. * @param mesh the mesh the vertexData is applied to
  36293. * @param updatable when used and having the value true allows new data to update the vertexData
  36294. * @returns the VertexData
  36295. */
  36296. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36297. this._applyTo(mesh, updatable);
  36298. return this;
  36299. };
  36300. /**
  36301. * Associates the vertexData to the passed Geometry.
  36302. * Sets it as updatable or not (default `false`)
  36303. * @param geometry the geometry the vertexData is applied to
  36304. * @param updatable when used and having the value true allows new data to update the vertexData
  36305. * @returns VertexData
  36306. */
  36307. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36308. this._applyTo(geometry, updatable);
  36309. return this;
  36310. };
  36311. /**
  36312. * Updates the associated mesh
  36313. * @param mesh the mesh to be updated
  36314. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36315. * @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
  36316. * @returns VertexData
  36317. */
  36318. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36319. this._update(mesh);
  36320. return this;
  36321. };
  36322. /**
  36323. * Updates the associated geometry
  36324. * @param geometry the geometry to be updated
  36325. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36326. * @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
  36327. * @returns VertexData.
  36328. */
  36329. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36330. this._update(geometry);
  36331. return this;
  36332. };
  36333. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36334. if (updatable === void 0) { updatable = false; }
  36335. if (this.positions) {
  36336. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36337. }
  36338. if (this.normals) {
  36339. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36340. }
  36341. if (this.tangents) {
  36342. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36343. }
  36344. if (this.uvs) {
  36345. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36346. }
  36347. if (this.uvs2) {
  36348. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36349. }
  36350. if (this.uvs3) {
  36351. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36352. }
  36353. if (this.uvs4) {
  36354. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36355. }
  36356. if (this.uvs5) {
  36357. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36358. }
  36359. if (this.uvs6) {
  36360. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36361. }
  36362. if (this.colors) {
  36363. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36364. }
  36365. if (this.matricesIndices) {
  36366. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36367. }
  36368. if (this.matricesWeights) {
  36369. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36370. }
  36371. if (this.matricesIndicesExtra) {
  36372. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36373. }
  36374. if (this.matricesWeightsExtra) {
  36375. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36376. }
  36377. if (this.indices) {
  36378. meshOrGeometry.setIndices(this.indices, null, updatable);
  36379. }
  36380. else {
  36381. meshOrGeometry.setIndices([], null);
  36382. }
  36383. return this;
  36384. };
  36385. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36386. if (this.positions) {
  36387. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36388. }
  36389. if (this.normals) {
  36390. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36391. }
  36392. if (this.tangents) {
  36393. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36394. }
  36395. if (this.uvs) {
  36396. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36397. }
  36398. if (this.uvs2) {
  36399. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36400. }
  36401. if (this.uvs3) {
  36402. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36403. }
  36404. if (this.uvs4) {
  36405. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36406. }
  36407. if (this.uvs5) {
  36408. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36409. }
  36410. if (this.uvs6) {
  36411. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36412. }
  36413. if (this.colors) {
  36414. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36415. }
  36416. if (this.matricesIndices) {
  36417. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36418. }
  36419. if (this.matricesWeights) {
  36420. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36421. }
  36422. if (this.matricesIndicesExtra) {
  36423. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36424. }
  36425. if (this.matricesWeightsExtra) {
  36426. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36427. }
  36428. if (this.indices) {
  36429. meshOrGeometry.setIndices(this.indices, null);
  36430. }
  36431. return this;
  36432. };
  36433. /**
  36434. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36435. * @param matrix the transforming matrix
  36436. * @returns the VertexData
  36437. */
  36438. VertexData.prototype.transform = function (matrix) {
  36439. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36440. var transformed = BABYLON.Vector3.Zero();
  36441. var index;
  36442. if (this.positions) {
  36443. var position = BABYLON.Vector3.Zero();
  36444. for (index = 0; index < this.positions.length; index += 3) {
  36445. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36446. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36447. this.positions[index] = transformed.x;
  36448. this.positions[index + 1] = transformed.y;
  36449. this.positions[index + 2] = transformed.z;
  36450. }
  36451. }
  36452. if (this.normals) {
  36453. var normal = BABYLON.Vector3.Zero();
  36454. for (index = 0; index < this.normals.length; index += 3) {
  36455. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36456. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36457. this.normals[index] = transformed.x;
  36458. this.normals[index + 1] = transformed.y;
  36459. this.normals[index + 2] = transformed.z;
  36460. }
  36461. }
  36462. if (this.tangents) {
  36463. var tangent = BABYLON.Vector4.Zero();
  36464. var tangentTransformed = BABYLON.Vector4.Zero();
  36465. for (index = 0; index < this.tangents.length; index += 4) {
  36466. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36467. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36468. this.tangents[index] = tangentTransformed.x;
  36469. this.tangents[index + 1] = tangentTransformed.y;
  36470. this.tangents[index + 2] = tangentTransformed.z;
  36471. this.tangents[index + 3] = tangentTransformed.w;
  36472. }
  36473. }
  36474. if (flip && this.indices) {
  36475. for (index = 0; index < this.indices.length; index += 3) {
  36476. var tmp = this.indices[index + 1];
  36477. this.indices[index + 1] = this.indices[index + 2];
  36478. this.indices[index + 2] = tmp;
  36479. }
  36480. }
  36481. return this;
  36482. };
  36483. /**
  36484. * Merges the passed VertexData into the current one
  36485. * @param other the VertexData to be merged into the current one
  36486. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36487. * @returns the modified VertexData
  36488. */
  36489. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36490. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36491. this._validate();
  36492. other._validate();
  36493. if (!this.normals !== !other.normals ||
  36494. !this.tangents !== !other.tangents ||
  36495. !this.uvs !== !other.uvs ||
  36496. !this.uvs2 !== !other.uvs2 ||
  36497. !this.uvs3 !== !other.uvs3 ||
  36498. !this.uvs4 !== !other.uvs4 ||
  36499. !this.uvs5 !== !other.uvs5 ||
  36500. !this.uvs6 !== !other.uvs6 ||
  36501. !this.colors !== !other.colors ||
  36502. !this.matricesIndices !== !other.matricesIndices ||
  36503. !this.matricesWeights !== !other.matricesWeights ||
  36504. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36505. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36506. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36507. }
  36508. if (other.indices) {
  36509. if (!this.indices) {
  36510. this.indices = [];
  36511. }
  36512. var offset = this.positions ? this.positions.length / 3 : 0;
  36513. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36514. if (isSrcTypedArray) {
  36515. var len = this.indices.length + other.indices.length;
  36516. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36517. temp.set(this.indices);
  36518. var decal = this.indices.length;
  36519. for (var index = 0; index < other.indices.length; index++) {
  36520. temp[decal + index] = other.indices[index] + offset;
  36521. }
  36522. this.indices = temp;
  36523. }
  36524. else {
  36525. for (var index = 0; index < other.indices.length; index++) {
  36526. this.indices.push(other.indices[index] + offset);
  36527. }
  36528. }
  36529. }
  36530. this.positions = this._mergeElement(this.positions, other.positions);
  36531. this.normals = this._mergeElement(this.normals, other.normals);
  36532. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36533. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36534. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36535. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36536. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36537. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36538. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36539. this.colors = this._mergeElement(this.colors, other.colors);
  36540. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36541. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36542. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36543. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36544. return this;
  36545. };
  36546. VertexData.prototype._mergeElement = function (source, other) {
  36547. if (!source) {
  36548. return other;
  36549. }
  36550. if (!other) {
  36551. return source;
  36552. }
  36553. var len = other.length + source.length;
  36554. var isSrcTypedArray = source instanceof Float32Array;
  36555. var isOthTypedArray = other instanceof Float32Array;
  36556. // use non-loop method when the source is Float32Array
  36557. if (isSrcTypedArray) {
  36558. var ret32 = new Float32Array(len);
  36559. ret32.set(source);
  36560. ret32.set(other, source.length);
  36561. return ret32;
  36562. // source is number[], when other is also use concat
  36563. }
  36564. else if (!isOthTypedArray) {
  36565. return source.concat(other);
  36566. // source is a number[], but other is a Float32Array, loop required
  36567. }
  36568. else {
  36569. var ret = source.slice(0); // copy source to a separate array
  36570. for (var i = 0, len = other.length; i < len; i++) {
  36571. ret.push(other[i]);
  36572. }
  36573. return ret;
  36574. }
  36575. };
  36576. VertexData.prototype._validate = function () {
  36577. if (!this.positions) {
  36578. throw new Error("Positions are required");
  36579. }
  36580. var getElementCount = function (kind, values) {
  36581. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36582. if ((values.length % stride) !== 0) {
  36583. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36584. }
  36585. return values.length / stride;
  36586. };
  36587. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36588. var validateElementCount = function (kind, values) {
  36589. var elementCount = getElementCount(kind, values);
  36590. if (elementCount !== positionsElementCount) {
  36591. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36592. }
  36593. };
  36594. if (this.normals)
  36595. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36596. if (this.tangents)
  36597. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36598. if (this.uvs)
  36599. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36600. if (this.uvs2)
  36601. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36602. if (this.uvs3)
  36603. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36604. if (this.uvs4)
  36605. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36606. if (this.uvs5)
  36607. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36608. if (this.uvs6)
  36609. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36610. if (this.colors)
  36611. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36612. if (this.matricesIndices)
  36613. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36614. if (this.matricesWeights)
  36615. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36616. if (this.matricesIndicesExtra)
  36617. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36618. if (this.matricesWeightsExtra)
  36619. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36620. };
  36621. /**
  36622. * Serializes the VertexData
  36623. * @returns a serialized object
  36624. */
  36625. VertexData.prototype.serialize = function () {
  36626. var serializationObject = this.serialize();
  36627. if (this.positions) {
  36628. serializationObject.positions = this.positions;
  36629. }
  36630. if (this.normals) {
  36631. serializationObject.normals = this.normals;
  36632. }
  36633. if (this.tangents) {
  36634. serializationObject.tangents = this.tangents;
  36635. }
  36636. if (this.uvs) {
  36637. serializationObject.uvs = this.uvs;
  36638. }
  36639. if (this.uvs2) {
  36640. serializationObject.uvs2 = this.uvs2;
  36641. }
  36642. if (this.uvs3) {
  36643. serializationObject.uvs3 = this.uvs3;
  36644. }
  36645. if (this.uvs4) {
  36646. serializationObject.uvs4 = this.uvs4;
  36647. }
  36648. if (this.uvs5) {
  36649. serializationObject.uvs5 = this.uvs5;
  36650. }
  36651. if (this.uvs6) {
  36652. serializationObject.uvs6 = this.uvs6;
  36653. }
  36654. if (this.colors) {
  36655. serializationObject.colors = this.colors;
  36656. }
  36657. if (this.matricesIndices) {
  36658. serializationObject.matricesIndices = this.matricesIndices;
  36659. serializationObject.matricesIndices._isExpanded = true;
  36660. }
  36661. if (this.matricesWeights) {
  36662. serializationObject.matricesWeights = this.matricesWeights;
  36663. }
  36664. if (this.matricesIndicesExtra) {
  36665. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36666. serializationObject.matricesIndicesExtra._isExpanded = true;
  36667. }
  36668. if (this.matricesWeightsExtra) {
  36669. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36670. }
  36671. serializationObject.indices = this.indices;
  36672. return serializationObject;
  36673. };
  36674. // Statics
  36675. /**
  36676. * Extracts the vertexData from a mesh
  36677. * @param mesh the mesh from which to extract the VertexData
  36678. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36679. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36680. * @returns the object VertexData associated to the passed mesh
  36681. */
  36682. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36683. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36684. };
  36685. /**
  36686. * Extracts the vertexData from the geometry
  36687. * @param geometry the geometry from which to extract the VertexData
  36688. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36689. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36690. * @returns the object VertexData associated to the passed mesh
  36691. */
  36692. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36693. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36694. };
  36695. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36696. var result = new VertexData();
  36697. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36698. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36699. }
  36700. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36701. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36702. }
  36703. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36704. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36705. }
  36706. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36707. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36708. }
  36709. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36710. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36711. }
  36712. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36713. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36714. }
  36715. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36716. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36717. }
  36718. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36719. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36720. }
  36721. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36722. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36723. }
  36724. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36725. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36726. }
  36727. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36728. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36729. }
  36730. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36731. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36732. }
  36733. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36734. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36735. }
  36736. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36737. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36738. }
  36739. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36740. return result;
  36741. };
  36742. /**
  36743. * Creates the VertexData for a Ribbon
  36744. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36745. * * pathArray array of paths, each of which an array of successive Vector3
  36746. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36747. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36748. * * 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
  36749. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36750. * * 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)
  36751. * * 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)
  36752. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36753. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36754. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36755. * @returns the VertexData of the ribbon
  36756. */
  36757. VertexData.CreateRibbon = function (options) {
  36758. var pathArray = options.pathArray;
  36759. var closeArray = options.closeArray || false;
  36760. var closePath = options.closePath || false;
  36761. var invertUV = options.invertUV || false;
  36762. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36763. var offset = options.offset || defaultOffset;
  36764. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36765. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36766. var customUV = options.uvs;
  36767. var customColors = options.colors;
  36768. var positions = [];
  36769. var indices = [];
  36770. var normals = [];
  36771. var uvs = [];
  36772. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36773. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36774. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36775. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36776. var minlg; // minimal length among all paths from pathArray
  36777. var lg = []; // array of path lengths : nb of vertex per path
  36778. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36779. var p; // path iterator
  36780. var i; // point iterator
  36781. var j; // point iterator
  36782. // if single path in pathArray
  36783. if (pathArray.length < 2) {
  36784. var ar1 = [];
  36785. var ar2 = [];
  36786. for (i = 0; i < pathArray[0].length - offset; i++) {
  36787. ar1.push(pathArray[0][i]);
  36788. ar2.push(pathArray[0][i + offset]);
  36789. }
  36790. pathArray = [ar1, ar2];
  36791. }
  36792. // positions and horizontal distances (u)
  36793. var idc = 0;
  36794. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36795. var path;
  36796. var l;
  36797. minlg = pathArray[0].length;
  36798. var vectlg;
  36799. var dist;
  36800. for (p = 0; p < pathArray.length; p++) {
  36801. uTotalDistance[p] = 0;
  36802. us[p] = [0];
  36803. path = pathArray[p];
  36804. l = path.length;
  36805. minlg = (minlg < l) ? minlg : l;
  36806. j = 0;
  36807. while (j < l) {
  36808. positions.push(path[j].x, path[j].y, path[j].z);
  36809. if (j > 0) {
  36810. vectlg = path[j].subtract(path[j - 1]).length();
  36811. dist = vectlg + uTotalDistance[p];
  36812. us[p].push(dist);
  36813. uTotalDistance[p] = dist;
  36814. }
  36815. j++;
  36816. }
  36817. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36818. j--;
  36819. positions.push(path[0].x, path[0].y, path[0].z);
  36820. vectlg = path[j].subtract(path[0]).length();
  36821. dist = vectlg + uTotalDistance[p];
  36822. us[p].push(dist);
  36823. uTotalDistance[p] = dist;
  36824. }
  36825. lg[p] = l + closePathCorr;
  36826. idx[p] = idc;
  36827. idc += (l + closePathCorr);
  36828. }
  36829. // vertical distances (v)
  36830. var path1;
  36831. var path2;
  36832. var vertex1 = null;
  36833. var vertex2 = null;
  36834. for (i = 0; i < minlg + closePathCorr; i++) {
  36835. vTotalDistance[i] = 0;
  36836. vs[i] = [0];
  36837. for (p = 0; p < pathArray.length - 1; p++) {
  36838. path1 = pathArray[p];
  36839. path2 = pathArray[p + 1];
  36840. if (i === minlg) { // closePath
  36841. vertex1 = path1[0];
  36842. vertex2 = path2[0];
  36843. }
  36844. else {
  36845. vertex1 = path1[i];
  36846. vertex2 = path2[i];
  36847. }
  36848. vectlg = vertex2.subtract(vertex1).length();
  36849. dist = vectlg + vTotalDistance[i];
  36850. vs[i].push(dist);
  36851. vTotalDistance[i] = dist;
  36852. }
  36853. if (closeArray && vertex2 && vertex1) {
  36854. path1 = pathArray[p];
  36855. path2 = pathArray[0];
  36856. if (i === minlg) { // closePath
  36857. vertex2 = path2[0];
  36858. }
  36859. vectlg = vertex2.subtract(vertex1).length();
  36860. dist = vectlg + vTotalDistance[i];
  36861. vTotalDistance[i] = dist;
  36862. }
  36863. }
  36864. // uvs
  36865. var u;
  36866. var v;
  36867. if (customUV) {
  36868. for (p = 0; p < customUV.length; p++) {
  36869. uvs.push(customUV[p].x, customUV[p].y);
  36870. }
  36871. }
  36872. else {
  36873. for (p = 0; p < pathArray.length; p++) {
  36874. for (i = 0; i < minlg + closePathCorr; i++) {
  36875. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36876. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36877. if (invertUV) {
  36878. uvs.push(v, u);
  36879. }
  36880. else {
  36881. uvs.push(u, v);
  36882. }
  36883. }
  36884. }
  36885. }
  36886. // indices
  36887. p = 0; // path index
  36888. var pi = 0; // positions array index
  36889. var l1 = lg[p] - 1; // path1 length
  36890. var l2 = lg[p + 1] - 1; // path2 length
  36891. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36892. var shft = idx[1] - idx[0]; // shift
  36893. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36894. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36895. // 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
  36896. indices.push(pi, pi + shft, pi + 1);
  36897. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36898. pi += 1;
  36899. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36900. p++;
  36901. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36902. shft = idx[0] - idx[p];
  36903. l1 = lg[p] - 1;
  36904. l2 = lg[0] - 1;
  36905. }
  36906. else {
  36907. shft = idx[p + 1] - idx[p];
  36908. l1 = lg[p] - 1;
  36909. l2 = lg[p + 1] - 1;
  36910. }
  36911. pi = idx[p];
  36912. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36913. }
  36914. }
  36915. // normals
  36916. VertexData.ComputeNormals(positions, indices, normals);
  36917. if (closePath) { // update both the first and last vertex normals to their average value
  36918. var indexFirst = 0;
  36919. var indexLast = 0;
  36920. for (p = 0; p < pathArray.length; p++) {
  36921. indexFirst = idx[p] * 3;
  36922. if (p + 1 < pathArray.length) {
  36923. indexLast = (idx[p + 1] - 1) * 3;
  36924. }
  36925. else {
  36926. indexLast = normals.length - 3;
  36927. }
  36928. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36929. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36930. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36931. normals[indexLast] = normals[indexFirst];
  36932. normals[indexLast + 1] = normals[indexFirst + 1];
  36933. normals[indexLast + 2] = normals[indexFirst + 2];
  36934. }
  36935. }
  36936. // sides
  36937. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36938. // Colors
  36939. var colors = null;
  36940. if (customColors) {
  36941. colors = new Float32Array(customColors.length * 4);
  36942. for (var c = 0; c < customColors.length; c++) {
  36943. colors[c * 4] = customColors[c].r;
  36944. colors[c * 4 + 1] = customColors[c].g;
  36945. colors[c * 4 + 2] = customColors[c].b;
  36946. colors[c * 4 + 3] = customColors[c].a;
  36947. }
  36948. }
  36949. // Result
  36950. var vertexData = new VertexData();
  36951. var positions32 = new Float32Array(positions);
  36952. var normals32 = new Float32Array(normals);
  36953. var uvs32 = new Float32Array(uvs);
  36954. vertexData.indices = indices;
  36955. vertexData.positions = positions32;
  36956. vertexData.normals = normals32;
  36957. vertexData.uvs = uvs32;
  36958. if (colors) {
  36959. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36960. }
  36961. if (closePath) {
  36962. vertexData._idx = idx;
  36963. }
  36964. return vertexData;
  36965. };
  36966. /**
  36967. * Creates the VertexData for a box
  36968. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36969. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36970. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36971. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36972. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36973. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36974. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36975. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36976. * * 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)
  36977. * * 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)
  36978. * @returns the VertexData of the box
  36979. */
  36980. VertexData.CreateBox = function (options) {
  36981. var normalsSource = [
  36982. new BABYLON.Vector3(0, 0, 1),
  36983. new BABYLON.Vector3(0, 0, -1),
  36984. new BABYLON.Vector3(1, 0, 0),
  36985. new BABYLON.Vector3(-1, 0, 0),
  36986. new BABYLON.Vector3(0, 1, 0),
  36987. new BABYLON.Vector3(0, -1, 0)
  36988. ];
  36989. var indices = [];
  36990. var positions = [];
  36991. var normals = [];
  36992. var uvs = [];
  36993. var width = options.width || options.size || 1;
  36994. var height = options.height || options.size || 1;
  36995. var depth = options.depth || options.size || 1;
  36996. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36997. var faceUV = options.faceUV || new Array(6);
  36998. var faceColors = options.faceColors;
  36999. var colors = [];
  37000. // default face colors and UV if undefined
  37001. for (var f = 0; f < 6; f++) {
  37002. if (faceUV[f] === undefined) {
  37003. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37004. }
  37005. if (faceColors && faceColors[f] === undefined) {
  37006. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37007. }
  37008. }
  37009. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37010. // Create each face in turn.
  37011. for (var index = 0; index < normalsSource.length; index++) {
  37012. var normal = normalsSource[index];
  37013. // Get two vectors perpendicular to the face normal and to each other.
  37014. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37015. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37016. // Six indices (two triangles) per face.
  37017. var verticesLength = positions.length / 3;
  37018. indices.push(verticesLength);
  37019. indices.push(verticesLength + 1);
  37020. indices.push(verticesLength + 2);
  37021. indices.push(verticesLength);
  37022. indices.push(verticesLength + 2);
  37023. indices.push(verticesLength + 3);
  37024. // Four vertices per face.
  37025. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37026. positions.push(vertex.x, vertex.y, vertex.z);
  37027. normals.push(normal.x, normal.y, normal.z);
  37028. uvs.push(faceUV[index].z, faceUV[index].w);
  37029. if (faceColors) {
  37030. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37031. }
  37032. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37033. positions.push(vertex.x, vertex.y, vertex.z);
  37034. normals.push(normal.x, normal.y, normal.z);
  37035. uvs.push(faceUV[index].x, faceUV[index].w);
  37036. if (faceColors) {
  37037. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37038. }
  37039. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37040. positions.push(vertex.x, vertex.y, vertex.z);
  37041. normals.push(normal.x, normal.y, normal.z);
  37042. uvs.push(faceUV[index].x, faceUV[index].y);
  37043. if (faceColors) {
  37044. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37045. }
  37046. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37047. positions.push(vertex.x, vertex.y, vertex.z);
  37048. normals.push(normal.x, normal.y, normal.z);
  37049. uvs.push(faceUV[index].z, faceUV[index].y);
  37050. if (faceColors) {
  37051. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37052. }
  37053. }
  37054. // sides
  37055. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37056. // Result
  37057. var vertexData = new VertexData();
  37058. vertexData.indices = indices;
  37059. vertexData.positions = positions;
  37060. vertexData.normals = normals;
  37061. vertexData.uvs = uvs;
  37062. if (faceColors) {
  37063. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37064. vertexData.colors = totalColors;
  37065. }
  37066. return vertexData;
  37067. };
  37068. /**
  37069. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37070. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37071. * * segments sets the number of horizontal strips optional, default 32
  37072. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37073. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37074. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37075. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37076. * * 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
  37077. * * 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
  37078. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37079. * * 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)
  37080. * * 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)
  37081. * @returns the VertexData of the ellipsoid
  37082. */
  37083. VertexData.CreateSphere = function (options) {
  37084. var segments = options.segments || 32;
  37085. var diameterX = options.diameterX || options.diameter || 1;
  37086. var diameterY = options.diameterY || options.diameter || 1;
  37087. var diameterZ = options.diameterZ || options.diameter || 1;
  37088. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37089. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37090. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37091. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37092. var totalZRotationSteps = 2 + segments;
  37093. var totalYRotationSteps = 2 * totalZRotationSteps;
  37094. var indices = [];
  37095. var positions = [];
  37096. var normals = [];
  37097. var uvs = [];
  37098. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37099. var normalizedZ = zRotationStep / totalZRotationSteps;
  37100. var angleZ = normalizedZ * Math.PI * slice;
  37101. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37102. var normalizedY = yRotationStep / totalYRotationSteps;
  37103. var angleY = normalizedY * Math.PI * 2 * arc;
  37104. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37105. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37106. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37107. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37108. var vertex = complete.multiply(radius);
  37109. var normal = complete.divide(radius).normalize();
  37110. positions.push(vertex.x, vertex.y, vertex.z);
  37111. normals.push(normal.x, normal.y, normal.z);
  37112. uvs.push(normalizedY, normalizedZ);
  37113. }
  37114. if (zRotationStep > 0) {
  37115. var verticesCount = positions.length / 3;
  37116. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37117. indices.push((firstIndex));
  37118. indices.push((firstIndex + 1));
  37119. indices.push(firstIndex + totalYRotationSteps + 1);
  37120. indices.push((firstIndex + totalYRotationSteps + 1));
  37121. indices.push((firstIndex + 1));
  37122. indices.push((firstIndex + totalYRotationSteps + 2));
  37123. }
  37124. }
  37125. }
  37126. // Sides
  37127. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37128. // Result
  37129. var vertexData = new VertexData();
  37130. vertexData.indices = indices;
  37131. vertexData.positions = positions;
  37132. vertexData.normals = normals;
  37133. vertexData.uvs = uvs;
  37134. return vertexData;
  37135. };
  37136. /**
  37137. * Creates the VertexData for a cylinder, cone or prism
  37138. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37139. * * height sets the height (y direction) of the cylinder, optional, default 2
  37140. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37141. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37142. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37143. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37144. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37145. * * 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
  37146. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37147. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37148. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37149. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37150. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37151. * * 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)
  37152. * * 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)
  37153. * @returns the VertexData of the cylinder, cone or prism
  37154. */
  37155. VertexData.CreateCylinder = function (options) {
  37156. var height = options.height || 2;
  37157. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37158. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37159. var tessellation = options.tessellation || 24;
  37160. var subdivisions = options.subdivisions || 1;
  37161. var hasRings = options.hasRings ? true : false;
  37162. var enclose = options.enclose ? true : false;
  37163. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37164. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37165. var faceUV = options.faceUV || new Array(3);
  37166. var faceColors = options.faceColors;
  37167. // default face colors and UV if undefined
  37168. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37169. var ringNb = (hasRings) ? subdivisions : 1;
  37170. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37171. var f;
  37172. for (f = 0; f < surfaceNb; f++) {
  37173. if (faceColors && faceColors[f] === undefined) {
  37174. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37175. }
  37176. }
  37177. for (f = 0; f < surfaceNb; f++) {
  37178. if (faceUV && faceUV[f] === undefined) {
  37179. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37180. }
  37181. }
  37182. var indices = new Array();
  37183. var positions = new Array();
  37184. var normals = new Array();
  37185. var uvs = new Array();
  37186. var colors = new Array();
  37187. var angle_step = Math.PI * 2 * arc / tessellation;
  37188. var angle;
  37189. var h;
  37190. var radius;
  37191. var tan = (diameterBottom - diameterTop) / 2 / height;
  37192. var ringVertex = BABYLON.Vector3.Zero();
  37193. var ringNormal = BABYLON.Vector3.Zero();
  37194. var ringFirstVertex = BABYLON.Vector3.Zero();
  37195. var ringFirstNormal = BABYLON.Vector3.Zero();
  37196. var quadNormal = BABYLON.Vector3.Zero();
  37197. var Y = BABYLON.Axis.Y;
  37198. // positions, normals, uvs
  37199. var i;
  37200. var j;
  37201. var r;
  37202. var ringIdx = 1;
  37203. var s = 1; // surface index
  37204. var cs = 0;
  37205. var v = 0;
  37206. for (i = 0; i <= subdivisions; i++) {
  37207. h = i / subdivisions;
  37208. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37209. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37210. for (r = 0; r < ringIdx; r++) {
  37211. if (hasRings) {
  37212. s += r;
  37213. }
  37214. if (enclose) {
  37215. s += 2 * r;
  37216. }
  37217. for (j = 0; j <= tessellation; j++) {
  37218. angle = j * angle_step;
  37219. // position
  37220. ringVertex.x = Math.cos(-angle) * radius;
  37221. ringVertex.y = -height / 2 + h * height;
  37222. ringVertex.z = Math.sin(-angle) * radius;
  37223. // normal
  37224. if (diameterTop === 0 && i === subdivisions) {
  37225. // if no top cap, reuse former normals
  37226. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37227. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37228. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37229. }
  37230. else {
  37231. ringNormal.x = ringVertex.x;
  37232. ringNormal.z = ringVertex.z;
  37233. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37234. ringNormal.normalize();
  37235. }
  37236. // keep first ring vertex values for enclose
  37237. if (j === 0) {
  37238. ringFirstVertex.copyFrom(ringVertex);
  37239. ringFirstNormal.copyFrom(ringNormal);
  37240. }
  37241. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37242. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37243. if (hasRings) {
  37244. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37245. }
  37246. else {
  37247. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37248. }
  37249. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37250. if (faceColors) {
  37251. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37252. }
  37253. }
  37254. // if enclose, add four vertices and their dedicated normals
  37255. if (arc !== 1 && enclose) {
  37256. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37257. positions.push(0, ringVertex.y, 0);
  37258. positions.push(0, ringVertex.y, 0);
  37259. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37260. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37261. quadNormal.normalize();
  37262. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37263. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37264. quadNormal.normalize();
  37265. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37266. if (hasRings) {
  37267. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37268. }
  37269. else {
  37270. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37271. }
  37272. uvs.push(faceUV[s + 1].x, v);
  37273. uvs.push(faceUV[s + 1].z, v);
  37274. if (hasRings) {
  37275. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37276. }
  37277. else {
  37278. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37279. }
  37280. uvs.push(faceUV[s + 2].x, v);
  37281. uvs.push(faceUV[s + 2].z, v);
  37282. if (faceColors) {
  37283. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37284. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37285. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37286. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37287. }
  37288. }
  37289. if (cs !== s) {
  37290. cs = s;
  37291. }
  37292. }
  37293. }
  37294. // indices
  37295. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37296. var s;
  37297. i = 0;
  37298. for (s = 0; s < subdivisions; s++) {
  37299. var i0 = 0;
  37300. var i1 = 0;
  37301. var i2 = 0;
  37302. var i3 = 0;
  37303. for (j = 0; j < tessellation; j++) {
  37304. i0 = i * (e + 1) + j;
  37305. i1 = (i + 1) * (e + 1) + j;
  37306. i2 = i * (e + 1) + (j + 1);
  37307. i3 = (i + 1) * (e + 1) + (j + 1);
  37308. indices.push(i0, i1, i2);
  37309. indices.push(i3, i2, i1);
  37310. }
  37311. if (arc !== 1 && enclose) { // if enclose, add two quads
  37312. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37313. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37314. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37315. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37316. }
  37317. i = (hasRings) ? (i + 2) : (i + 1);
  37318. }
  37319. // Caps
  37320. var createCylinderCap = function (isTop) {
  37321. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37322. if (radius === 0) {
  37323. return;
  37324. }
  37325. // Cap positions, normals & uvs
  37326. var angle;
  37327. var circleVector;
  37328. var i;
  37329. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37330. var c = null;
  37331. if (faceColors) {
  37332. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37333. }
  37334. // cap center
  37335. var vbase = positions.length / 3;
  37336. var offset = isTop ? height / 2 : -height / 2;
  37337. var center = new BABYLON.Vector3(0, offset, 0);
  37338. positions.push(center.x, center.y, center.z);
  37339. normals.push(0, isTop ? 1 : -1, 0);
  37340. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37341. if (c) {
  37342. colors.push(c.r, c.g, c.b, c.a);
  37343. }
  37344. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37345. for (i = 0; i <= tessellation; i++) {
  37346. angle = Math.PI * 2 * i * arc / tessellation;
  37347. var cos = Math.cos(-angle);
  37348. var sin = Math.sin(-angle);
  37349. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37350. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37351. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37352. normals.push(0, isTop ? 1 : -1, 0);
  37353. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37354. if (c) {
  37355. colors.push(c.r, c.g, c.b, c.a);
  37356. }
  37357. }
  37358. // Cap indices
  37359. for (i = 0; i < tessellation; i++) {
  37360. if (!isTop) {
  37361. indices.push(vbase);
  37362. indices.push(vbase + (i + 1));
  37363. indices.push(vbase + (i + 2));
  37364. }
  37365. else {
  37366. indices.push(vbase);
  37367. indices.push(vbase + (i + 2));
  37368. indices.push(vbase + (i + 1));
  37369. }
  37370. }
  37371. };
  37372. // add caps to geometry
  37373. createCylinderCap(false);
  37374. createCylinderCap(true);
  37375. // Sides
  37376. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37377. var vertexData = new VertexData();
  37378. vertexData.indices = indices;
  37379. vertexData.positions = positions;
  37380. vertexData.normals = normals;
  37381. vertexData.uvs = uvs;
  37382. if (faceColors) {
  37383. vertexData.colors = colors;
  37384. }
  37385. return vertexData;
  37386. };
  37387. /**
  37388. * Creates the VertexData for a torus
  37389. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37390. * * diameter the diameter of the torus, optional default 1
  37391. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37392. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37393. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37394. * * 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)
  37395. * * 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)
  37396. * @returns the VertexData of the torus
  37397. */
  37398. VertexData.CreateTorus = function (options) {
  37399. var indices = [];
  37400. var positions = [];
  37401. var normals = [];
  37402. var uvs = [];
  37403. var diameter = options.diameter || 1;
  37404. var thickness = options.thickness || 0.5;
  37405. var tessellation = options.tessellation || 16;
  37406. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37407. var stride = tessellation + 1;
  37408. for (var i = 0; i <= tessellation; i++) {
  37409. var u = i / tessellation;
  37410. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37411. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37412. for (var j = 0; j <= tessellation; j++) {
  37413. var v = 1 - j / tessellation;
  37414. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37415. var dx = Math.cos(innerAngle);
  37416. var dy = Math.sin(innerAngle);
  37417. // Create a vertex.
  37418. var normal = new BABYLON.Vector3(dx, dy, 0);
  37419. var position = normal.scale(thickness / 2);
  37420. var textureCoordinate = new BABYLON.Vector2(u, v);
  37421. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37422. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37423. positions.push(position.x, position.y, position.z);
  37424. normals.push(normal.x, normal.y, normal.z);
  37425. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37426. // And create indices for two triangles.
  37427. var nextI = (i + 1) % stride;
  37428. var nextJ = (j + 1) % stride;
  37429. indices.push(i * stride + j);
  37430. indices.push(i * stride + nextJ);
  37431. indices.push(nextI * stride + j);
  37432. indices.push(i * stride + nextJ);
  37433. indices.push(nextI * stride + nextJ);
  37434. indices.push(nextI * stride + j);
  37435. }
  37436. }
  37437. // Sides
  37438. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37439. // Result
  37440. var vertexData = new VertexData();
  37441. vertexData.indices = indices;
  37442. vertexData.positions = positions;
  37443. vertexData.normals = normals;
  37444. vertexData.uvs = uvs;
  37445. return vertexData;
  37446. };
  37447. /**
  37448. * Creates the VertexData of the LineSystem
  37449. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37450. * - lines an array of lines, each line being an array of successive Vector3
  37451. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37452. * @returns the VertexData of the LineSystem
  37453. */
  37454. VertexData.CreateLineSystem = function (options) {
  37455. var indices = [];
  37456. var positions = [];
  37457. var lines = options.lines;
  37458. var colors = options.colors;
  37459. var vertexColors = [];
  37460. var idx = 0;
  37461. for (var l = 0; l < lines.length; l++) {
  37462. var points = lines[l];
  37463. for (var index = 0; index < points.length; index++) {
  37464. positions.push(points[index].x, points[index].y, points[index].z);
  37465. if (colors) {
  37466. var color = colors[l];
  37467. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37468. }
  37469. if (index > 0) {
  37470. indices.push(idx - 1);
  37471. indices.push(idx);
  37472. }
  37473. idx++;
  37474. }
  37475. }
  37476. var vertexData = new VertexData();
  37477. vertexData.indices = indices;
  37478. vertexData.positions = positions;
  37479. if (colors) {
  37480. vertexData.colors = vertexColors;
  37481. }
  37482. return vertexData;
  37483. };
  37484. /**
  37485. * Create the VertexData for a DashedLines
  37486. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37487. * - points an array successive Vector3
  37488. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37489. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37490. * - dashNb the intended total number of dashes, optional, default 200
  37491. * @returns the VertexData for the DashedLines
  37492. */
  37493. VertexData.CreateDashedLines = function (options) {
  37494. var dashSize = options.dashSize || 3;
  37495. var gapSize = options.gapSize || 1;
  37496. var dashNb = options.dashNb || 200;
  37497. var points = options.points;
  37498. var positions = new Array();
  37499. var indices = new Array();
  37500. var curvect = BABYLON.Vector3.Zero();
  37501. var lg = 0;
  37502. var nb = 0;
  37503. var shft = 0;
  37504. var dashshft = 0;
  37505. var curshft = 0;
  37506. var idx = 0;
  37507. var i = 0;
  37508. for (i = 0; i < points.length - 1; i++) {
  37509. points[i + 1].subtractToRef(points[i], curvect);
  37510. lg += curvect.length();
  37511. }
  37512. shft = lg / dashNb;
  37513. dashshft = dashSize * shft / (dashSize + gapSize);
  37514. for (i = 0; i < points.length - 1; i++) {
  37515. points[i + 1].subtractToRef(points[i], curvect);
  37516. nb = Math.floor(curvect.length() / shft);
  37517. curvect.normalize();
  37518. for (var j = 0; j < nb; j++) {
  37519. curshft = shft * j;
  37520. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37521. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37522. indices.push(idx, idx + 1);
  37523. idx += 2;
  37524. }
  37525. }
  37526. // Result
  37527. var vertexData = new VertexData();
  37528. vertexData.positions = positions;
  37529. vertexData.indices = indices;
  37530. return vertexData;
  37531. };
  37532. /**
  37533. * Creates the VertexData for a Ground
  37534. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37535. * - width the width (x direction) of the ground, optional, default 1
  37536. * - height the height (z direction) of the ground, optional, default 1
  37537. * - subdivisions the number of subdivisions per side, optional, default 1
  37538. * @returns the VertexData of the Ground
  37539. */
  37540. VertexData.CreateGround = function (options) {
  37541. var indices = [];
  37542. var positions = [];
  37543. var normals = [];
  37544. var uvs = [];
  37545. var row, col;
  37546. var width = options.width || 1;
  37547. var height = options.height || 1;
  37548. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37549. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37550. for (row = 0; row <= subdivisionsY; row++) {
  37551. for (col = 0; col <= subdivisionsX; col++) {
  37552. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37553. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37554. positions.push(position.x, position.y, position.z);
  37555. normals.push(normal.x, normal.y, normal.z);
  37556. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37557. }
  37558. }
  37559. for (row = 0; row < subdivisionsY; row++) {
  37560. for (col = 0; col < subdivisionsX; col++) {
  37561. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37562. indices.push(col + 1 + row * (subdivisionsX + 1));
  37563. indices.push(col + row * (subdivisionsX + 1));
  37564. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37565. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37566. indices.push(col + row * (subdivisionsX + 1));
  37567. }
  37568. }
  37569. // Result
  37570. var vertexData = new VertexData();
  37571. vertexData.indices = indices;
  37572. vertexData.positions = positions;
  37573. vertexData.normals = normals;
  37574. vertexData.uvs = uvs;
  37575. return vertexData;
  37576. };
  37577. /**
  37578. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37579. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37580. * * xmin the ground minimum X coordinate, optional, default -1
  37581. * * zmin the ground minimum Z coordinate, optional, default -1
  37582. * * xmax the ground maximum X coordinate, optional, default 1
  37583. * * zmax the ground maximum Z coordinate, optional, default 1
  37584. * * 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}
  37585. * * 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}
  37586. * @returns the VertexData of the TiledGround
  37587. */
  37588. VertexData.CreateTiledGround = function (options) {
  37589. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37590. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37591. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37592. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37593. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37594. var precision = options.precision || { w: 1, h: 1 };
  37595. var indices = new Array();
  37596. var positions = new Array();
  37597. var normals = new Array();
  37598. var uvs = new Array();
  37599. var row, col, tileRow, tileCol;
  37600. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37601. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37602. precision.w = (precision.w < 1) ? 1 : precision.w;
  37603. precision.h = (precision.h < 1) ? 1 : precision.h;
  37604. var tileSize = {
  37605. 'w': (xmax - xmin) / subdivisions.w,
  37606. 'h': (zmax - zmin) / subdivisions.h
  37607. };
  37608. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37609. // Indices
  37610. var base = positions.length / 3;
  37611. var rowLength = precision.w + 1;
  37612. for (row = 0; row < precision.h; row++) {
  37613. for (col = 0; col < precision.w; col++) {
  37614. var square = [
  37615. base + col + row * rowLength,
  37616. base + (col + 1) + row * rowLength,
  37617. base + (col + 1) + (row + 1) * rowLength,
  37618. base + col + (row + 1) * rowLength
  37619. ];
  37620. indices.push(square[1]);
  37621. indices.push(square[2]);
  37622. indices.push(square[3]);
  37623. indices.push(square[0]);
  37624. indices.push(square[1]);
  37625. indices.push(square[3]);
  37626. }
  37627. }
  37628. // Position, normals and uvs
  37629. var position = BABYLON.Vector3.Zero();
  37630. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37631. for (row = 0; row <= precision.h; row++) {
  37632. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37633. for (col = 0; col <= precision.w; col++) {
  37634. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37635. position.y = 0;
  37636. positions.push(position.x, position.y, position.z);
  37637. normals.push(normal.x, normal.y, normal.z);
  37638. uvs.push(col / precision.w, row / precision.h);
  37639. }
  37640. }
  37641. }
  37642. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37643. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37644. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37645. }
  37646. }
  37647. // Result
  37648. var vertexData = new VertexData();
  37649. vertexData.indices = indices;
  37650. vertexData.positions = positions;
  37651. vertexData.normals = normals;
  37652. vertexData.uvs = uvs;
  37653. return vertexData;
  37654. };
  37655. /**
  37656. * Creates the VertexData of the Ground designed from a heightmap
  37657. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37658. * * width the width (x direction) of the ground
  37659. * * height the height (z direction) of the ground
  37660. * * subdivisions the number of subdivisions per side
  37661. * * minHeight the minimum altitude on the ground, optional, default 0
  37662. * * maxHeight the maximum altitude on the ground, optional default 1
  37663. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37664. * * buffer the array holding the image color data
  37665. * * bufferWidth the width of image
  37666. * * bufferHeight the height of image
  37667. * @returns the VertexData of the Ground designed from a heightmap
  37668. */
  37669. VertexData.CreateGroundFromHeightMap = function (options) {
  37670. var indices = [];
  37671. var positions = [];
  37672. var normals = [];
  37673. var uvs = [];
  37674. var row, col;
  37675. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37676. // Vertices
  37677. for (row = 0; row <= options.subdivisions; row++) {
  37678. for (col = 0; col <= options.subdivisions; col++) {
  37679. 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));
  37680. // Compute height
  37681. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37682. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37683. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37684. var r = options.buffer[pos] / 255.0;
  37685. var g = options.buffer[pos + 1] / 255.0;
  37686. var b = options.buffer[pos + 2] / 255.0;
  37687. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37688. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37689. // Add vertex
  37690. positions.push(position.x, position.y, position.z);
  37691. normals.push(0, 0, 0);
  37692. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37693. }
  37694. }
  37695. // Indices
  37696. for (row = 0; row < options.subdivisions; row++) {
  37697. for (col = 0; col < options.subdivisions; col++) {
  37698. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37699. indices.push(col + 1 + row * (options.subdivisions + 1));
  37700. indices.push(col + row * (options.subdivisions + 1));
  37701. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37702. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37703. indices.push(col + row * (options.subdivisions + 1));
  37704. }
  37705. }
  37706. // Normals
  37707. VertexData.ComputeNormals(positions, indices, normals);
  37708. // Result
  37709. var vertexData = new VertexData();
  37710. vertexData.indices = indices;
  37711. vertexData.positions = positions;
  37712. vertexData.normals = normals;
  37713. vertexData.uvs = uvs;
  37714. return vertexData;
  37715. };
  37716. /**
  37717. * Creates the VertexData for a Plane
  37718. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37719. * * size sets the width and height of the plane to the value of size, optional default 1
  37720. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37721. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37722. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37723. * * 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)
  37724. * * 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)
  37725. * @returns the VertexData of the box
  37726. */
  37727. VertexData.CreatePlane = function (options) {
  37728. var indices = [];
  37729. var positions = [];
  37730. var normals = [];
  37731. var uvs = [];
  37732. var width = options.width || options.size || 1;
  37733. var height = options.height || options.size || 1;
  37734. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37735. // Vertices
  37736. var halfWidth = width / 2.0;
  37737. var halfHeight = height / 2.0;
  37738. positions.push(-halfWidth, -halfHeight, 0);
  37739. normals.push(0, 0, -1.0);
  37740. uvs.push(0.0, 0.0);
  37741. positions.push(halfWidth, -halfHeight, 0);
  37742. normals.push(0, 0, -1.0);
  37743. uvs.push(1.0, 0.0);
  37744. positions.push(halfWidth, halfHeight, 0);
  37745. normals.push(0, 0, -1.0);
  37746. uvs.push(1.0, 1.0);
  37747. positions.push(-halfWidth, halfHeight, 0);
  37748. normals.push(0, 0, -1.0);
  37749. uvs.push(0.0, 1.0);
  37750. // Indices
  37751. indices.push(0);
  37752. indices.push(1);
  37753. indices.push(2);
  37754. indices.push(0);
  37755. indices.push(2);
  37756. indices.push(3);
  37757. // Sides
  37758. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37759. // Result
  37760. var vertexData = new VertexData();
  37761. vertexData.indices = indices;
  37762. vertexData.positions = positions;
  37763. vertexData.normals = normals;
  37764. vertexData.uvs = uvs;
  37765. return vertexData;
  37766. };
  37767. /**
  37768. * Creates the VertexData of the Disc or regular Polygon
  37769. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37770. * * radius the radius of the disc, optional default 0.5
  37771. * * tessellation the number of polygon sides, optional, default 64
  37772. * * 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
  37773. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37774. * * 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)
  37775. * * 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)
  37776. * @returns the VertexData of the box
  37777. */
  37778. VertexData.CreateDisc = function (options) {
  37779. var positions = new Array();
  37780. var indices = new Array();
  37781. var normals = new Array();
  37782. var uvs = new Array();
  37783. var radius = options.radius || 0.5;
  37784. var tessellation = options.tessellation || 64;
  37785. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37786. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37787. // positions and uvs
  37788. positions.push(0, 0, 0); // disc center first
  37789. uvs.push(0.5, 0.5);
  37790. var theta = Math.PI * 2 * arc;
  37791. var step = theta / tessellation;
  37792. for (var a = 0; a < theta; a += step) {
  37793. var x = Math.cos(a);
  37794. var y = Math.sin(a);
  37795. var u = (x + 1) / 2;
  37796. var v = (1 - y) / 2;
  37797. positions.push(radius * x, radius * y, 0);
  37798. uvs.push(u, v);
  37799. }
  37800. if (arc === 1) {
  37801. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37802. uvs.push(uvs[2], uvs[3]);
  37803. }
  37804. //indices
  37805. var vertexNb = positions.length / 3;
  37806. for (var i = 1; i < vertexNb - 1; i++) {
  37807. indices.push(i + 1, 0, i);
  37808. }
  37809. // result
  37810. VertexData.ComputeNormals(positions, indices, normals);
  37811. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37812. var vertexData = new VertexData();
  37813. vertexData.indices = indices;
  37814. vertexData.positions = positions;
  37815. vertexData.normals = normals;
  37816. vertexData.uvs = uvs;
  37817. return vertexData;
  37818. };
  37819. /**
  37820. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37821. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37822. * @param polygon a mesh built from polygonTriangulation.build()
  37823. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37824. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37825. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37826. * @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)
  37827. * @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)
  37828. * @returns the VertexData of the Polygon
  37829. */
  37830. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37831. var faceUV = fUV || new Array(3);
  37832. var faceColors = fColors;
  37833. var colors = [];
  37834. // default face colors and UV if undefined
  37835. for (var f = 0; f < 3; f++) {
  37836. if (faceUV[f] === undefined) {
  37837. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37838. }
  37839. if (faceColors && faceColors[f] === undefined) {
  37840. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37841. }
  37842. }
  37843. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37844. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37845. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37846. var indices = polygon.getIndices();
  37847. // set face colours and textures
  37848. var idx = 0;
  37849. var face = 0;
  37850. for (var index = 0; index < normals.length; index += 3) {
  37851. //Edge Face no. 1
  37852. if (Math.abs(normals[index + 1]) < 0.001) {
  37853. face = 1;
  37854. }
  37855. //Top Face no. 0
  37856. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37857. face = 0;
  37858. }
  37859. //Bottom Face no. 2
  37860. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37861. face = 2;
  37862. }
  37863. idx = index / 3;
  37864. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37865. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37866. if (faceColors) {
  37867. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37868. }
  37869. }
  37870. // sides
  37871. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37872. // Result
  37873. var vertexData = new VertexData();
  37874. vertexData.indices = indices;
  37875. vertexData.positions = positions;
  37876. vertexData.normals = normals;
  37877. vertexData.uvs = uvs;
  37878. if (faceColors) {
  37879. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37880. vertexData.colors = totalColors;
  37881. }
  37882. return vertexData;
  37883. };
  37884. /**
  37885. * Creates the VertexData of the IcoSphere
  37886. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37887. * * radius the radius of the IcoSphere, optional default 1
  37888. * * radiusX allows stretching in the x direction, optional, default radius
  37889. * * radiusY allows stretching in the y direction, optional, default radius
  37890. * * radiusZ allows stretching in the z direction, optional, default radius
  37891. * * flat when true creates a flat shaded mesh, optional, default true
  37892. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37893. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37894. * * 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)
  37895. * * 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)
  37896. * @returns the VertexData of the IcoSphere
  37897. */
  37898. VertexData.CreateIcoSphere = function (options) {
  37899. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37900. var radius = options.radius || 1;
  37901. var flat = (options.flat === undefined) ? true : options.flat;
  37902. var subdivisions = options.subdivisions || 4;
  37903. var radiusX = options.radiusX || radius;
  37904. var radiusY = options.radiusY || radius;
  37905. var radiusZ = options.radiusZ || radius;
  37906. var t = (1 + Math.sqrt(5)) / 2;
  37907. // 12 vertex x,y,z
  37908. var ico_vertices = [
  37909. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37910. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37911. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37912. ];
  37913. // index of 3 vertex makes a face of icopshere
  37914. var ico_indices = [
  37915. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37916. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37917. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37918. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37919. ];
  37920. // vertex for uv have aliased position, not for UV
  37921. var vertices_unalias_id = [
  37922. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37923. // vertex alias
  37924. 0,
  37925. 2,
  37926. 3,
  37927. 3,
  37928. 3,
  37929. 4,
  37930. 7,
  37931. 8,
  37932. 9,
  37933. 9,
  37934. 10,
  37935. 11 // 23: B + 12
  37936. ];
  37937. // uv as integer step (not pixels !)
  37938. var ico_vertexuv = [
  37939. 5, 1, 3, 1, 6, 4, 0, 0,
  37940. 5, 3, 4, 2, 2, 2, 4, 0,
  37941. 2, 0, 1, 1, 6, 0, 6, 2,
  37942. // vertex alias (for same vertex on different faces)
  37943. 0, 4,
  37944. 3, 3,
  37945. 4, 4,
  37946. 3, 1,
  37947. 4, 2,
  37948. 4, 4,
  37949. 0, 2,
  37950. 1, 1,
  37951. 2, 2,
  37952. 3, 3,
  37953. 1, 3,
  37954. 2, 4 // 23: B + 12
  37955. ];
  37956. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37957. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37958. // First island of uv mapping
  37959. // v = 4h 3+ 2
  37960. // v = 3h 9+ 4
  37961. // v = 2h 9+ 5 B
  37962. // v = 1h 9 1 0
  37963. // v = 0h 3 8 7 A
  37964. // u = 0 1 2 3 4 5 6 *a
  37965. // Second island of uv mapping
  37966. // v = 4h 0+ B+ 4+
  37967. // v = 3h A+ 2+
  37968. // v = 2h 7+ 6 3+
  37969. // v = 1h 8+ 3+
  37970. // v = 0h
  37971. // u = 0 1 2 3 4 5 6 *a
  37972. // Face layout on texture UV mapping
  37973. // ============
  37974. // \ 4 /\ 16 / ======
  37975. // \ / \ / /\ 11 /
  37976. // \/ 7 \/ / \ /
  37977. // ======= / 10 \/
  37978. // /\ 17 /\ =======
  37979. // / \ / \ \ 15 /\
  37980. // / 8 \/ 12 \ \ / \
  37981. // ============ \/ 6 \
  37982. // \ 18 /\ ============
  37983. // \ / \ \ 5 /\ 0 /
  37984. // \/ 13 \ \ / \ /
  37985. // ======= \/ 1 \/
  37986. // =============
  37987. // /\ 19 /\ 2 /\
  37988. // / \ / \ / \
  37989. // / 14 \/ 9 \/ 3 \
  37990. // ===================
  37991. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37992. var ustep = 138 / 1024;
  37993. var vstep = 239 / 1024;
  37994. var uoffset = 60 / 1024;
  37995. var voffset = 26 / 1024;
  37996. // Second island should have margin, not to touch the first island
  37997. // avoid any borderline artefact in pixel rounding
  37998. var island_u_offset = -40 / 1024;
  37999. var island_v_offset = +20 / 1024;
  38000. // face is either island 0 or 1 :
  38001. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38002. var island = [
  38003. 0, 0, 0, 0, 1,
  38004. 0, 0, 1, 1, 0,
  38005. 0, 0, 1, 1, 0,
  38006. 0, 1, 1, 1, 0 // 15 - 19
  38007. ];
  38008. var indices = new Array();
  38009. var positions = new Array();
  38010. var normals = new Array();
  38011. var uvs = new Array();
  38012. var current_indice = 0;
  38013. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38014. var face_vertex_pos = new Array(3);
  38015. var face_vertex_uv = new Array(3);
  38016. var v012;
  38017. for (v012 = 0; v012 < 3; v012++) {
  38018. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38019. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38020. }
  38021. // create all with normals
  38022. for (var face = 0; face < 20; face++) {
  38023. // 3 vertex per face
  38024. for (v012 = 0; v012 < 3; v012++) {
  38025. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38026. var v_id = ico_indices[3 * face + v012];
  38027. // vertex have 3D position (x,y,z)
  38028. 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]);
  38029. // Normalize to get normal, then scale to radius
  38030. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38031. // uv Coordinates from vertex ID
  38032. 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);
  38033. }
  38034. // Subdivide the face (interpolate pos, norm, uv)
  38035. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38036. // - norm is linear interpolation of vertex corner normal
  38037. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38038. // - uv is linear interpolation
  38039. //
  38040. // Topology is as below for sub-divide by 2
  38041. // vertex shown as v0,v1,v2
  38042. // interp index is i1 to progress in range [v0,v1[
  38043. // interp index is i2 to progress in range [v0,v2[
  38044. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38045. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38046. //
  38047. //
  38048. // i2 v2
  38049. // ^ ^
  38050. // / / \
  38051. // / / \
  38052. // / / \
  38053. // / / (0,1) \
  38054. // / #---------\
  38055. // / / \ (0,0)'/ \
  38056. // / / \ / \
  38057. // / / \ / \
  38058. // / / (0,0) \ / (1,0) \
  38059. // / #---------#---------\
  38060. // v0 v1
  38061. //
  38062. // --------------------> i1
  38063. //
  38064. // interp of (i1,i2):
  38065. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38066. // along i1 : lerp(x0,x1, i1/(S-i2))
  38067. //
  38068. // centroid of triangle is needed to get help normal computation
  38069. // (c1,c2) are used for centroid location
  38070. var interp_vertex = function (i1, i2, c1, c2) {
  38071. // vertex is interpolated from
  38072. // - face_vertex_pos[0..2]
  38073. // - face_vertex_uv[0..2]
  38074. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38075. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38076. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38077. pos_interp.normalize();
  38078. var vertex_normal;
  38079. if (flat) {
  38080. // in flat mode, recalculate normal as face centroid normal
  38081. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38082. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38083. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38084. }
  38085. else {
  38086. // in smooth mode, recalculate normal from each single vertex position
  38087. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38088. }
  38089. // Vertex normal need correction due to X,Y,Z radius scaling
  38090. vertex_normal.x /= radiusX;
  38091. vertex_normal.y /= radiusY;
  38092. vertex_normal.z /= radiusZ;
  38093. vertex_normal.normalize();
  38094. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38095. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38096. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38097. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38098. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38099. uvs.push(uv_interp.x, uv_interp.y);
  38100. // push each vertex has member of a face
  38101. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38102. indices.push(current_indice);
  38103. current_indice++;
  38104. };
  38105. for (var i2 = 0; i2 < subdivisions; i2++) {
  38106. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38107. // face : (i1,i2) for /\ :
  38108. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38109. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38110. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38111. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38112. if (i1 + i2 + 1 < subdivisions) {
  38113. // face : (i1,i2)' for \/ :
  38114. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38115. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38116. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38117. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38118. }
  38119. }
  38120. }
  38121. }
  38122. // Sides
  38123. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38124. // Result
  38125. var vertexData = new VertexData();
  38126. vertexData.indices = indices;
  38127. vertexData.positions = positions;
  38128. vertexData.normals = normals;
  38129. vertexData.uvs = uvs;
  38130. return vertexData;
  38131. };
  38132. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38133. /**
  38134. * Creates the VertexData for a Polyhedron
  38135. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38136. * * type provided types are:
  38137. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38138. * * 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)
  38139. * * size the size of the IcoSphere, optional default 1
  38140. * * sizeX allows stretching in the x direction, optional, default size
  38141. * * sizeY allows stretching in the y direction, optional, default size
  38142. * * sizeZ allows stretching in the z direction, optional, default size
  38143. * * 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
  38144. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38145. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38146. * * flat when true creates a flat shaded mesh, optional, default true
  38147. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38148. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38149. * * 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)
  38150. * * 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)
  38151. * @returns the VertexData of the Polyhedron
  38152. */
  38153. VertexData.CreatePolyhedron = function (options) {
  38154. // provided polyhedron types :
  38155. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38156. // 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)
  38157. var polyhedra = [];
  38158. 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]] };
  38159. 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]] };
  38160. polyhedra[2] = {
  38161. 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]],
  38162. 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]]
  38163. };
  38164. polyhedra[3] = {
  38165. 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]],
  38166. 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]]
  38167. };
  38168. polyhedra[4] = {
  38169. 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]],
  38170. 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]]
  38171. };
  38172. 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]] };
  38173. 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]] };
  38174. 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]] };
  38175. 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]] };
  38176. 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]] };
  38177. 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]] };
  38178. 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]] };
  38179. 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]] };
  38180. 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]] };
  38181. polyhedra[14] = {
  38182. 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]],
  38183. 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]]
  38184. };
  38185. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38186. var size = options.size;
  38187. var sizeX = options.sizeX || size || 1;
  38188. var sizeY = options.sizeY || size || 1;
  38189. var sizeZ = options.sizeZ || size || 1;
  38190. var data = options.custom || polyhedra[type];
  38191. var nbfaces = data.face.length;
  38192. var faceUV = options.faceUV || new Array(nbfaces);
  38193. var faceColors = options.faceColors;
  38194. var flat = (options.flat === undefined) ? true : options.flat;
  38195. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38196. var positions = new Array();
  38197. var indices = new Array();
  38198. var normals = new Array();
  38199. var uvs = new Array();
  38200. var colors = new Array();
  38201. var index = 0;
  38202. var faceIdx = 0; // face cursor in the array "indexes"
  38203. var indexes = new Array();
  38204. var i = 0;
  38205. var f = 0;
  38206. var u, v, ang, x, y, tmp;
  38207. // default face colors and UV if undefined
  38208. if (flat) {
  38209. for (f = 0; f < nbfaces; f++) {
  38210. if (faceColors && faceColors[f] === undefined) {
  38211. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38212. }
  38213. if (faceUV && faceUV[f] === undefined) {
  38214. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38215. }
  38216. }
  38217. }
  38218. if (!flat) {
  38219. for (i = 0; i < data.vertex.length; i++) {
  38220. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38221. uvs.push(0, 0);
  38222. }
  38223. for (f = 0; f < nbfaces; f++) {
  38224. for (i = 0; i < data.face[f].length - 2; i++) {
  38225. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38226. }
  38227. }
  38228. }
  38229. else {
  38230. for (f = 0; f < nbfaces; f++) {
  38231. var fl = data.face[f].length; // number of vertices of the current face
  38232. ang = 2 * Math.PI / fl;
  38233. x = 0.5 * Math.tan(ang / 2);
  38234. y = 0.5;
  38235. // positions, uvs, colors
  38236. for (i = 0; i < fl; i++) {
  38237. // positions
  38238. 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);
  38239. indexes.push(index);
  38240. index++;
  38241. // uvs
  38242. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38243. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38244. uvs.push(u, v);
  38245. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38246. y = x * Math.sin(ang) + y * Math.cos(ang);
  38247. x = tmp;
  38248. // colors
  38249. if (faceColors) {
  38250. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38251. }
  38252. }
  38253. // indices from indexes
  38254. for (i = 0; i < fl - 2; i++) {
  38255. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38256. }
  38257. faceIdx += fl;
  38258. }
  38259. }
  38260. VertexData.ComputeNormals(positions, indices, normals);
  38261. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38262. var vertexData = new VertexData();
  38263. vertexData.positions = positions;
  38264. vertexData.indices = indices;
  38265. vertexData.normals = normals;
  38266. vertexData.uvs = uvs;
  38267. if (faceColors && flat) {
  38268. vertexData.colors = colors;
  38269. }
  38270. return vertexData;
  38271. };
  38272. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38273. /**
  38274. * Creates the VertexData for a TorusKnot
  38275. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38276. * * radius the radius of the torus knot, optional, default 2
  38277. * * tube the thickness of the tube, optional, default 0.5
  38278. * * radialSegments the number of sides on each tube segments, optional, default 32
  38279. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38280. * * p the number of windings around the z axis, optional, default 2
  38281. * * q the number of windings around the x axis, optional, default 3
  38282. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38283. * * 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)
  38284. * * 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)
  38285. * @returns the VertexData of the Torus Knot
  38286. */
  38287. VertexData.CreateTorusKnot = function (options) {
  38288. var indices = new Array();
  38289. var positions = new Array();
  38290. var normals = new Array();
  38291. var uvs = new Array();
  38292. var radius = options.radius || 2;
  38293. var tube = options.tube || 0.5;
  38294. var radialSegments = options.radialSegments || 32;
  38295. var tubularSegments = options.tubularSegments || 32;
  38296. var p = options.p || 2;
  38297. var q = options.q || 3;
  38298. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38299. // Helper
  38300. var getPos = function (angle) {
  38301. var cu = Math.cos(angle);
  38302. var su = Math.sin(angle);
  38303. var quOverP = q / p * angle;
  38304. var cs = Math.cos(quOverP);
  38305. var tx = radius * (2 + cs) * 0.5 * cu;
  38306. var ty = radius * (2 + cs) * su * 0.5;
  38307. var tz = radius * Math.sin(quOverP) * 0.5;
  38308. return new BABYLON.Vector3(tx, ty, tz);
  38309. };
  38310. // Vertices
  38311. var i;
  38312. var j;
  38313. for (i = 0; i <= radialSegments; i++) {
  38314. var modI = i % radialSegments;
  38315. var u = modI / radialSegments * 2 * p * Math.PI;
  38316. var p1 = getPos(u);
  38317. var p2 = getPos(u + 0.01);
  38318. var tang = p2.subtract(p1);
  38319. var n = p2.add(p1);
  38320. var bitan = BABYLON.Vector3.Cross(tang, n);
  38321. n = BABYLON.Vector3.Cross(bitan, tang);
  38322. bitan.normalize();
  38323. n.normalize();
  38324. for (j = 0; j < tubularSegments; j++) {
  38325. var modJ = j % tubularSegments;
  38326. var v = modJ / tubularSegments * 2 * Math.PI;
  38327. var cx = -tube * Math.cos(v);
  38328. var cy = tube * Math.sin(v);
  38329. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38330. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38331. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38332. uvs.push(i / radialSegments);
  38333. uvs.push(j / tubularSegments);
  38334. }
  38335. }
  38336. for (i = 0; i < radialSegments; i++) {
  38337. for (j = 0; j < tubularSegments; j++) {
  38338. var jNext = (j + 1) % tubularSegments;
  38339. var a = i * tubularSegments + j;
  38340. var b = (i + 1) * tubularSegments + j;
  38341. var c = (i + 1) * tubularSegments + jNext;
  38342. var d = i * tubularSegments + jNext;
  38343. indices.push(d);
  38344. indices.push(b);
  38345. indices.push(a);
  38346. indices.push(d);
  38347. indices.push(c);
  38348. indices.push(b);
  38349. }
  38350. }
  38351. // Normals
  38352. VertexData.ComputeNormals(positions, indices, normals);
  38353. // Sides
  38354. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38355. // Result
  38356. var vertexData = new VertexData();
  38357. vertexData.indices = indices;
  38358. vertexData.positions = positions;
  38359. vertexData.normals = normals;
  38360. vertexData.uvs = uvs;
  38361. return vertexData;
  38362. };
  38363. // Tools
  38364. /**
  38365. * Compute normals for given positions and indices
  38366. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38367. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38368. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38369. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38370. * * facetNormals : optional array of facet normals (vector3)
  38371. * * facetPositions : optional array of facet positions (vector3)
  38372. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38373. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38374. * * bInfo : optional bounding info, required for facetPartitioning computation
  38375. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38376. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38377. * * useRightHandedSystem: optional boolean to for right handed system computation
  38378. * * depthSort : optional boolean to enable the facet depth sort computation
  38379. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38380. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38381. */
  38382. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38383. // temporary scalar variables
  38384. var index = 0; // facet index
  38385. var p1p2x = 0.0; // p1p2 vector x coordinate
  38386. var p1p2y = 0.0; // p1p2 vector y coordinate
  38387. var p1p2z = 0.0; // p1p2 vector z coordinate
  38388. var p3p2x = 0.0; // p3p2 vector x coordinate
  38389. var p3p2y = 0.0; // p3p2 vector y coordinate
  38390. var p3p2z = 0.0; // p3p2 vector z coordinate
  38391. var faceNormalx = 0.0; // facet normal x coordinate
  38392. var faceNormaly = 0.0; // facet normal y coordinate
  38393. var faceNormalz = 0.0; // facet normal z coordinate
  38394. var length = 0.0; // facet normal length before normalization
  38395. var v1x = 0; // vector1 x index in the positions array
  38396. var v1y = 0; // vector1 y index in the positions array
  38397. var v1z = 0; // vector1 z index in the positions array
  38398. var v2x = 0; // vector2 x index in the positions array
  38399. var v2y = 0; // vector2 y index in the positions array
  38400. var v2z = 0; // vector2 z index in the positions array
  38401. var v3x = 0; // vector3 x index in the positions array
  38402. var v3y = 0; // vector3 y index in the positions array
  38403. var v3z = 0; // vector3 z index in the positions array
  38404. var computeFacetNormals = false;
  38405. var computeFacetPositions = false;
  38406. var computeFacetPartitioning = false;
  38407. var computeDepthSort = false;
  38408. var faceNormalSign = 1;
  38409. var ratio = 0;
  38410. var distanceTo = null;
  38411. if (options) {
  38412. computeFacetNormals = (options.facetNormals) ? true : false;
  38413. computeFacetPositions = (options.facetPositions) ? true : false;
  38414. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38415. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38416. ratio = options.ratio || 0;
  38417. computeDepthSort = (options.depthSort) ? true : false;
  38418. distanceTo = (options.distanceTo);
  38419. if (computeDepthSort) {
  38420. if (distanceTo === undefined) {
  38421. distanceTo = BABYLON.Vector3.Zero();
  38422. }
  38423. var depthSortedFacets = options.depthSortedFacets;
  38424. }
  38425. }
  38426. // facetPartitioning reinit if needed
  38427. var xSubRatio = 0;
  38428. var ySubRatio = 0;
  38429. var zSubRatio = 0;
  38430. var subSq = 0;
  38431. if (computeFacetPartitioning && options && options.bbSize) {
  38432. var ox = 0; // X partitioning index for facet position
  38433. var oy = 0; // Y partinioning index for facet position
  38434. var oz = 0; // Z partinioning index for facet position
  38435. var b1x = 0; // X partitioning index for facet v1 vertex
  38436. var b1y = 0; // Y partitioning index for facet v1 vertex
  38437. var b1z = 0; // z partitioning index for facet v1 vertex
  38438. var b2x = 0; // X partitioning index for facet v2 vertex
  38439. var b2y = 0; // Y partitioning index for facet v2 vertex
  38440. var b2z = 0; // Z partitioning index for facet v2 vertex
  38441. var b3x = 0; // X partitioning index for facet v3 vertex
  38442. var b3y = 0; // Y partitioning index for facet v3 vertex
  38443. var b3z = 0; // Z partitioning index for facet v3 vertex
  38444. var block_idx_o = 0; // facet barycenter block index
  38445. var block_idx_v1 = 0; // v1 vertex block index
  38446. var block_idx_v2 = 0; // v2 vertex block index
  38447. var block_idx_v3 = 0; // v3 vertex block index
  38448. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38449. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38450. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38451. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38452. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38453. subSq = options.subDiv.max * options.subDiv.max;
  38454. options.facetPartitioning.length = 0;
  38455. }
  38456. // reset the normals
  38457. for (index = 0; index < positions.length; index++) {
  38458. normals[index] = 0.0;
  38459. }
  38460. // Loop : 1 indice triplet = 1 facet
  38461. var nbFaces = (indices.length / 3) | 0;
  38462. for (index = 0; index < nbFaces; index++) {
  38463. // get the indexes of the coordinates of each vertex of the facet
  38464. v1x = indices[index * 3] * 3;
  38465. v1y = v1x + 1;
  38466. v1z = v1x + 2;
  38467. v2x = indices[index * 3 + 1] * 3;
  38468. v2y = v2x + 1;
  38469. v2z = v2x + 2;
  38470. v3x = indices[index * 3 + 2] * 3;
  38471. v3y = v3x + 1;
  38472. v3z = v3x + 2;
  38473. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38474. p1p2y = positions[v1y] - positions[v2y];
  38475. p1p2z = positions[v1z] - positions[v2z];
  38476. p3p2x = positions[v3x] - positions[v2x];
  38477. p3p2y = positions[v3y] - positions[v2y];
  38478. p3p2z = positions[v3z] - positions[v2z];
  38479. // compute the face normal with the cross product
  38480. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38481. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38482. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38483. // normalize this normal and store it in the array facetData
  38484. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38485. length = (length === 0) ? 1.0 : length;
  38486. faceNormalx /= length;
  38487. faceNormaly /= length;
  38488. faceNormalz /= length;
  38489. if (computeFacetNormals && options) {
  38490. options.facetNormals[index].x = faceNormalx;
  38491. options.facetNormals[index].y = faceNormaly;
  38492. options.facetNormals[index].z = faceNormalz;
  38493. }
  38494. if (computeFacetPositions && options) {
  38495. // compute and the facet barycenter coordinates in the array facetPositions
  38496. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38497. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38498. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38499. }
  38500. if (computeFacetPartitioning && options) {
  38501. // store the facet indexes in arrays in the main facetPartitioning array :
  38502. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38503. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38504. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38505. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38506. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38507. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38508. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38509. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38510. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38511. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38512. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38513. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38514. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38515. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38516. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38517. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38518. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38519. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38520. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38521. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38522. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38523. // push each facet index in each block containing the vertex
  38524. options.facetPartitioning[block_idx_v1].push(index);
  38525. if (block_idx_v2 != block_idx_v1) {
  38526. options.facetPartitioning[block_idx_v2].push(index);
  38527. }
  38528. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38529. options.facetPartitioning[block_idx_v3].push(index);
  38530. }
  38531. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38532. options.facetPartitioning[block_idx_o].push(index);
  38533. }
  38534. }
  38535. if (computeDepthSort && options && options.facetPositions) {
  38536. var dsf = depthSortedFacets[index];
  38537. dsf.ind = index * 3;
  38538. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38539. }
  38540. // compute the normals anyway
  38541. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38542. normals[v1y] += faceNormaly;
  38543. normals[v1z] += faceNormalz;
  38544. normals[v2x] += faceNormalx;
  38545. normals[v2y] += faceNormaly;
  38546. normals[v2z] += faceNormalz;
  38547. normals[v3x] += faceNormalx;
  38548. normals[v3y] += faceNormaly;
  38549. normals[v3z] += faceNormalz;
  38550. }
  38551. // last normalization of each normal
  38552. for (index = 0; index < normals.length / 3; index++) {
  38553. faceNormalx = normals[index * 3];
  38554. faceNormaly = normals[index * 3 + 1];
  38555. faceNormalz = normals[index * 3 + 2];
  38556. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38557. length = (length === 0) ? 1.0 : length;
  38558. faceNormalx /= length;
  38559. faceNormaly /= length;
  38560. faceNormalz /= length;
  38561. normals[index * 3] = faceNormalx;
  38562. normals[index * 3 + 1] = faceNormaly;
  38563. normals[index * 3 + 2] = faceNormalz;
  38564. }
  38565. };
  38566. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38567. var li = indices.length;
  38568. var ln = normals.length;
  38569. var i;
  38570. var n;
  38571. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38572. switch (sideOrientation) {
  38573. case BABYLON.Mesh.FRONTSIDE:
  38574. // nothing changed
  38575. break;
  38576. case BABYLON.Mesh.BACKSIDE:
  38577. var tmp;
  38578. // indices
  38579. for (i = 0; i < li; i += 3) {
  38580. tmp = indices[i];
  38581. indices[i] = indices[i + 2];
  38582. indices[i + 2] = tmp;
  38583. }
  38584. // normals
  38585. for (n = 0; n < ln; n++) {
  38586. normals[n] = -normals[n];
  38587. }
  38588. break;
  38589. case BABYLON.Mesh.DOUBLESIDE:
  38590. // positions
  38591. var lp = positions.length;
  38592. var l = lp / 3;
  38593. for (var p = 0; p < lp; p++) {
  38594. positions[lp + p] = positions[p];
  38595. }
  38596. // indices
  38597. for (i = 0; i < li; i += 3) {
  38598. indices[i + li] = indices[i + 2] + l;
  38599. indices[i + 1 + li] = indices[i + 1] + l;
  38600. indices[i + 2 + li] = indices[i] + l;
  38601. }
  38602. // normals
  38603. for (n = 0; n < ln; n++) {
  38604. normals[ln + n] = -normals[n];
  38605. }
  38606. // uvs
  38607. var lu = uvs.length;
  38608. var u = 0;
  38609. for (u = 0; u < lu; u++) {
  38610. uvs[u + lu] = uvs[u];
  38611. }
  38612. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38613. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38614. u = 0;
  38615. for (i = 0; i < lu / 2; i++) {
  38616. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38617. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38618. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38619. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38620. u += 2;
  38621. }
  38622. break;
  38623. }
  38624. };
  38625. /**
  38626. * Applies VertexData created from the imported parameters to the geometry
  38627. * @param parsedVertexData the parsed data from an imported file
  38628. * @param geometry the geometry to apply the VertexData to
  38629. */
  38630. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38631. var vertexData = new VertexData();
  38632. // positions
  38633. var positions = parsedVertexData.positions;
  38634. if (positions) {
  38635. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38636. }
  38637. // normals
  38638. var normals = parsedVertexData.normals;
  38639. if (normals) {
  38640. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38641. }
  38642. // tangents
  38643. var tangents = parsedVertexData.tangents;
  38644. if (tangents) {
  38645. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38646. }
  38647. // uvs
  38648. var uvs = parsedVertexData.uvs;
  38649. if (uvs) {
  38650. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38651. }
  38652. // uv2s
  38653. var uv2s = parsedVertexData.uv2s;
  38654. if (uv2s) {
  38655. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38656. }
  38657. // uv3s
  38658. var uv3s = parsedVertexData.uv3s;
  38659. if (uv3s) {
  38660. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38661. }
  38662. // uv4s
  38663. var uv4s = parsedVertexData.uv4s;
  38664. if (uv4s) {
  38665. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38666. }
  38667. // uv5s
  38668. var uv5s = parsedVertexData.uv5s;
  38669. if (uv5s) {
  38670. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38671. }
  38672. // uv6s
  38673. var uv6s = parsedVertexData.uv6s;
  38674. if (uv6s) {
  38675. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38676. }
  38677. // colors
  38678. var colors = parsedVertexData.colors;
  38679. if (colors) {
  38680. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38681. }
  38682. // matricesIndices
  38683. var matricesIndices = parsedVertexData.matricesIndices;
  38684. if (matricesIndices) {
  38685. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38686. }
  38687. // matricesWeights
  38688. var matricesWeights = parsedVertexData.matricesWeights;
  38689. if (matricesWeights) {
  38690. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38691. }
  38692. // indices
  38693. var indices = parsedVertexData.indices;
  38694. if (indices) {
  38695. vertexData.indices = indices;
  38696. }
  38697. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38698. };
  38699. return VertexData;
  38700. }());
  38701. BABYLON.VertexData = VertexData;
  38702. })(BABYLON || (BABYLON = {}));
  38703. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38704. var BABYLON;
  38705. (function (BABYLON) {
  38706. /**
  38707. * Class used to store geometry data (vertex buffers + index buffer)
  38708. */
  38709. var Geometry = /** @class */ (function () {
  38710. /**
  38711. * Creates a new geometry
  38712. * @param id defines the unique ID
  38713. * @param scene defines the hosting scene
  38714. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38715. * @param updatable defines if geometry must be updatable (false by default)
  38716. * @param mesh defines the mesh that will be associated with the geometry
  38717. */
  38718. function Geometry(id, scene, vertexData, updatable, mesh) {
  38719. if (updatable === void 0) { updatable = false; }
  38720. if (mesh === void 0) { mesh = null; }
  38721. /**
  38722. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38723. */
  38724. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38725. this._totalVertices = 0;
  38726. this._isDisposed = false;
  38727. this._indexBufferIsUpdatable = false;
  38728. this.id = id;
  38729. this._engine = scene.getEngine();
  38730. this._meshes = [];
  38731. this._scene = scene;
  38732. //Init vertex buffer cache
  38733. this._vertexBuffers = {};
  38734. this._indices = [];
  38735. this._updatable = updatable;
  38736. // vertexData
  38737. if (vertexData) {
  38738. this.setAllVerticesData(vertexData, updatable);
  38739. }
  38740. else {
  38741. this._totalVertices = 0;
  38742. this._indices = [];
  38743. }
  38744. if (this._engine.getCaps().vertexArrayObject) {
  38745. this._vertexArrayObjects = {};
  38746. }
  38747. // applyToMesh
  38748. if (mesh) {
  38749. if (mesh.getClassName() === "LinesMesh") {
  38750. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38751. this._updateExtend();
  38752. }
  38753. this.applyToMesh(mesh);
  38754. mesh.computeWorldMatrix(true);
  38755. }
  38756. }
  38757. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38758. /**
  38759. * 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
  38760. */
  38761. get: function () {
  38762. return this._boundingBias;
  38763. },
  38764. /**
  38765. * 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
  38766. */
  38767. set: function (value) {
  38768. if (this._boundingBias && this._boundingBias.equals(value)) {
  38769. return;
  38770. }
  38771. this._boundingBias = value.clone();
  38772. this._updateBoundingInfo(true, null);
  38773. },
  38774. enumerable: true,
  38775. configurable: true
  38776. });
  38777. /**
  38778. * Static function used to attach a new empty geometry to a mesh
  38779. * @param mesh defines the mesh to attach the geometry to
  38780. * @returns the new {BABYLON.Geometry}
  38781. */
  38782. Geometry.CreateGeometryForMesh = function (mesh) {
  38783. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38784. geometry.applyToMesh(mesh);
  38785. return geometry;
  38786. };
  38787. Object.defineProperty(Geometry.prototype, "extend", {
  38788. /**
  38789. * Gets the current extend of the geometry
  38790. */
  38791. get: function () {
  38792. return this._extend;
  38793. },
  38794. enumerable: true,
  38795. configurable: true
  38796. });
  38797. /**
  38798. * Gets the hosting scene
  38799. * @returns the hosting {BABYLON.Scene}
  38800. */
  38801. Geometry.prototype.getScene = function () {
  38802. return this._scene;
  38803. };
  38804. /**
  38805. * Gets the hosting engine
  38806. * @returns the hosting {BABYLON.Engine}
  38807. */
  38808. Geometry.prototype.getEngine = function () {
  38809. return this._engine;
  38810. };
  38811. /**
  38812. * Defines if the geometry is ready to use
  38813. * @returns true if the geometry is ready to be used
  38814. */
  38815. Geometry.prototype.isReady = function () {
  38816. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38817. };
  38818. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38819. /**
  38820. * Gets a value indicating that the geometry should not be serialized
  38821. */
  38822. get: function () {
  38823. for (var index = 0; index < this._meshes.length; index++) {
  38824. if (!this._meshes[index].doNotSerialize) {
  38825. return false;
  38826. }
  38827. }
  38828. return true;
  38829. },
  38830. enumerable: true,
  38831. configurable: true
  38832. });
  38833. /** @hidden */
  38834. Geometry.prototype._rebuild = function () {
  38835. if (this._vertexArrayObjects) {
  38836. this._vertexArrayObjects = {};
  38837. }
  38838. // Index buffer
  38839. if (this._meshes.length !== 0 && this._indices) {
  38840. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38841. }
  38842. // Vertex buffers
  38843. for (var key in this._vertexBuffers) {
  38844. var vertexBuffer = this._vertexBuffers[key];
  38845. vertexBuffer._rebuild();
  38846. }
  38847. };
  38848. /**
  38849. * Affects all geometry data in one call
  38850. * @param vertexData defines the geometry data
  38851. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38852. */
  38853. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38854. vertexData.applyToGeometry(this, updatable);
  38855. this.notifyUpdate();
  38856. };
  38857. /**
  38858. * Set specific vertex data
  38859. * @param kind defines the data kind (Position, normal, etc...)
  38860. * @param data defines the vertex data to use
  38861. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38862. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38863. */
  38864. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38865. if (updatable === void 0) { updatable = false; }
  38866. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38867. this.setVerticesBuffer(buffer);
  38868. };
  38869. /**
  38870. * Removes a specific vertex data
  38871. * @param kind defines the data kind (Position, normal, etc...)
  38872. */
  38873. Geometry.prototype.removeVerticesData = function (kind) {
  38874. if (this._vertexBuffers[kind]) {
  38875. this._vertexBuffers[kind].dispose();
  38876. delete this._vertexBuffers[kind];
  38877. }
  38878. };
  38879. /**
  38880. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38881. * @param buffer defines the vertex buffer to use
  38882. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38883. */
  38884. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38885. if (totalVertices === void 0) { totalVertices = null; }
  38886. var kind = buffer.getKind();
  38887. if (this._vertexBuffers[kind]) {
  38888. this._vertexBuffers[kind].dispose();
  38889. }
  38890. this._vertexBuffers[kind] = buffer;
  38891. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38892. var data = buffer.getData();
  38893. if (totalVertices != null) {
  38894. this._totalVertices = totalVertices;
  38895. }
  38896. else {
  38897. if (data != null) {
  38898. this._totalVertices = data.length / (buffer.byteStride / 4);
  38899. }
  38900. }
  38901. this._updateExtend(data);
  38902. this._resetPointsArrayCache();
  38903. var meshes = this._meshes;
  38904. var numOfMeshes = meshes.length;
  38905. for (var index = 0; index < numOfMeshes; index++) {
  38906. var mesh = meshes[index];
  38907. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38908. mesh._createGlobalSubMesh(false);
  38909. mesh.computeWorldMatrix(true);
  38910. }
  38911. }
  38912. this.notifyUpdate(kind);
  38913. if (this._vertexArrayObjects) {
  38914. this._disposeVertexArrayObjects();
  38915. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38916. }
  38917. };
  38918. /**
  38919. * Update a specific vertex buffer
  38920. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38921. * It will do nothing if the buffer is not updatable
  38922. * @param kind defines the data kind (Position, normal, etc...)
  38923. * @param data defines the data to use
  38924. * @param offset defines the offset in the target buffer where to store the data
  38925. * @param useBytes set to true if the offset is in bytes
  38926. */
  38927. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38928. if (useBytes === void 0) { useBytes = false; }
  38929. var vertexBuffer = this.getVertexBuffer(kind);
  38930. if (!vertexBuffer) {
  38931. return;
  38932. }
  38933. vertexBuffer.updateDirectly(data, offset, useBytes);
  38934. this.notifyUpdate(kind);
  38935. };
  38936. /**
  38937. * Update a specific vertex buffer
  38938. * This function will create a new buffer if the current one is not updatable
  38939. * @param kind defines the data kind (Position, normal, etc...)
  38940. * @param data defines the data to use
  38941. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38942. */
  38943. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38944. if (updateExtends === void 0) { updateExtends = false; }
  38945. var vertexBuffer = this.getVertexBuffer(kind);
  38946. if (!vertexBuffer) {
  38947. return;
  38948. }
  38949. vertexBuffer.update(data);
  38950. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38951. this._updateBoundingInfo(updateExtends, data);
  38952. }
  38953. this.notifyUpdate(kind);
  38954. };
  38955. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38956. if (updateExtends) {
  38957. this._updateExtend(data);
  38958. }
  38959. var meshes = this._meshes;
  38960. var numOfMeshes = meshes.length;
  38961. this._resetPointsArrayCache();
  38962. for (var index = 0; index < numOfMeshes; index++) {
  38963. var mesh = meshes[index];
  38964. if (updateExtends) {
  38965. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38966. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38967. var subMesh = mesh.subMeshes[subIndex];
  38968. subMesh.refreshBoundingInfo();
  38969. }
  38970. }
  38971. }
  38972. };
  38973. /** @hidden */
  38974. Geometry.prototype._bind = function (effect, indexToBind) {
  38975. if (!effect) {
  38976. return;
  38977. }
  38978. if (indexToBind === undefined) {
  38979. indexToBind = this._indexBuffer;
  38980. }
  38981. var vbs = this.getVertexBuffers();
  38982. if (!vbs) {
  38983. return;
  38984. }
  38985. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38986. this._engine.bindBuffers(vbs, indexToBind, effect);
  38987. return;
  38988. }
  38989. // Using VAO
  38990. if (!this._vertexArrayObjects[effect.key]) {
  38991. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38992. }
  38993. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38994. };
  38995. /**
  38996. * Gets total number of vertices
  38997. * @returns the total number of vertices
  38998. */
  38999. Geometry.prototype.getTotalVertices = function () {
  39000. if (!this.isReady()) {
  39001. return 0;
  39002. }
  39003. return this._totalVertices;
  39004. };
  39005. /**
  39006. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39007. * @param kind defines the data kind (Position, normal, etc...)
  39008. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39009. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39010. * @returns a float array containing vertex data
  39011. */
  39012. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39013. var vertexBuffer = this.getVertexBuffer(kind);
  39014. if (!vertexBuffer) {
  39015. return null;
  39016. }
  39017. var data = vertexBuffer.getData();
  39018. if (!data) {
  39019. return null;
  39020. }
  39021. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39022. var count = this._totalVertices * vertexBuffer.getSize();
  39023. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39024. var copy_1 = new Array(count);
  39025. vertexBuffer.forEach(count, function (value, index) {
  39026. copy_1[index] = value;
  39027. });
  39028. return copy_1;
  39029. }
  39030. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39031. if (data instanceof Array) {
  39032. var offset = vertexBuffer.byteOffset / 4;
  39033. return BABYLON.Tools.Slice(data, offset, offset + count);
  39034. }
  39035. else if (data instanceof ArrayBuffer) {
  39036. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39037. }
  39038. else {
  39039. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39040. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39041. var result = new Float32Array(count);
  39042. var source = new Float32Array(data.buffer, offset, count);
  39043. result.set(source);
  39044. return result;
  39045. }
  39046. return new Float32Array(data.buffer, offset, count);
  39047. }
  39048. }
  39049. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39050. return BABYLON.Tools.Slice(data);
  39051. }
  39052. return data;
  39053. };
  39054. /**
  39055. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39056. * @param kind defines the data kind (Position, normal, etc...)
  39057. * @returns true if the vertex buffer with the specified kind is updatable
  39058. */
  39059. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39060. var vb = this._vertexBuffers[kind];
  39061. if (!vb) {
  39062. return false;
  39063. }
  39064. return vb.isUpdatable();
  39065. };
  39066. /**
  39067. * Gets a specific vertex buffer
  39068. * @param kind defines the data kind (Position, normal, etc...)
  39069. * @returns a {BABYLON.VertexBuffer}
  39070. */
  39071. Geometry.prototype.getVertexBuffer = function (kind) {
  39072. if (!this.isReady()) {
  39073. return null;
  39074. }
  39075. return this._vertexBuffers[kind];
  39076. };
  39077. /**
  39078. * Returns all vertex buffers
  39079. * @return an object holding all vertex buffers indexed by kind
  39080. */
  39081. Geometry.prototype.getVertexBuffers = function () {
  39082. if (!this.isReady()) {
  39083. return null;
  39084. }
  39085. return this._vertexBuffers;
  39086. };
  39087. /**
  39088. * Gets a boolean indicating if specific vertex buffer is present
  39089. * @param kind defines the data kind (Position, normal, etc...)
  39090. * @returns true if data is present
  39091. */
  39092. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39093. if (!this._vertexBuffers) {
  39094. if (this._delayInfo) {
  39095. return this._delayInfo.indexOf(kind) !== -1;
  39096. }
  39097. return false;
  39098. }
  39099. return this._vertexBuffers[kind] !== undefined;
  39100. };
  39101. /**
  39102. * Gets a list of all attached data kinds (Position, normal, etc...)
  39103. * @returns a list of string containing all kinds
  39104. */
  39105. Geometry.prototype.getVerticesDataKinds = function () {
  39106. var result = [];
  39107. var kind;
  39108. if (!this._vertexBuffers && this._delayInfo) {
  39109. for (kind in this._delayInfo) {
  39110. result.push(kind);
  39111. }
  39112. }
  39113. else {
  39114. for (kind in this._vertexBuffers) {
  39115. result.push(kind);
  39116. }
  39117. }
  39118. return result;
  39119. };
  39120. /**
  39121. * Update index buffer
  39122. * @param indices defines the indices to store in the index buffer
  39123. * @param offset defines the offset in the target buffer where to store the data
  39124. */
  39125. Geometry.prototype.updateIndices = function (indices, offset) {
  39126. if (!this._indexBuffer) {
  39127. return;
  39128. }
  39129. if (!this._indexBufferIsUpdatable) {
  39130. this.setIndices(indices, null, true);
  39131. }
  39132. else {
  39133. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39134. }
  39135. };
  39136. /**
  39137. * Creates a new index buffer
  39138. * @param indices defines the indices to store in the index buffer
  39139. * @param totalVertices defines the total number of vertices (could be null)
  39140. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39141. */
  39142. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39143. if (totalVertices === void 0) { totalVertices = null; }
  39144. if (updatable === void 0) { updatable = false; }
  39145. if (this._indexBuffer) {
  39146. this._engine._releaseBuffer(this._indexBuffer);
  39147. }
  39148. this._disposeVertexArrayObjects();
  39149. this._indices = indices;
  39150. this._indexBufferIsUpdatable = updatable;
  39151. if (this._meshes.length !== 0 && this._indices) {
  39152. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39153. }
  39154. if (totalVertices != undefined) { // including null and undefined
  39155. this._totalVertices = totalVertices;
  39156. }
  39157. var meshes = this._meshes;
  39158. var numOfMeshes = meshes.length;
  39159. for (var index = 0; index < numOfMeshes; index++) {
  39160. meshes[index]._createGlobalSubMesh(true);
  39161. }
  39162. this.notifyUpdate();
  39163. };
  39164. /**
  39165. * Return the total number of indices
  39166. * @returns the total number of indices
  39167. */
  39168. Geometry.prototype.getTotalIndices = function () {
  39169. if (!this.isReady()) {
  39170. return 0;
  39171. }
  39172. return this._indices.length;
  39173. };
  39174. /**
  39175. * Gets the index buffer array
  39176. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39177. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39178. * @returns the index buffer array
  39179. */
  39180. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39181. if (!this.isReady()) {
  39182. return null;
  39183. }
  39184. var orig = this._indices;
  39185. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39186. return orig;
  39187. }
  39188. else {
  39189. var len = orig.length;
  39190. var copy = [];
  39191. for (var i = 0; i < len; i++) {
  39192. copy.push(orig[i]);
  39193. }
  39194. return copy;
  39195. }
  39196. };
  39197. /**
  39198. * Gets the index buffer
  39199. * @return the index buffer
  39200. */
  39201. Geometry.prototype.getIndexBuffer = function () {
  39202. if (!this.isReady()) {
  39203. return null;
  39204. }
  39205. return this._indexBuffer;
  39206. };
  39207. /** @hidden */
  39208. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39209. if (effect === void 0) { effect = null; }
  39210. if (!effect || !this._vertexArrayObjects) {
  39211. return;
  39212. }
  39213. if (this._vertexArrayObjects[effect.key]) {
  39214. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39215. delete this._vertexArrayObjects[effect.key];
  39216. }
  39217. };
  39218. /**
  39219. * Release the associated resources for a specific mesh
  39220. * @param mesh defines the source mesh
  39221. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39222. */
  39223. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39224. var meshes = this._meshes;
  39225. var index = meshes.indexOf(mesh);
  39226. if (index === -1) {
  39227. return;
  39228. }
  39229. meshes.splice(index, 1);
  39230. mesh._geometry = null;
  39231. if (meshes.length === 0 && shouldDispose) {
  39232. this.dispose();
  39233. }
  39234. };
  39235. /**
  39236. * Apply current geometry to a given mesh
  39237. * @param mesh defines the mesh to apply geometry to
  39238. */
  39239. Geometry.prototype.applyToMesh = function (mesh) {
  39240. if (mesh._geometry === this) {
  39241. return;
  39242. }
  39243. var previousGeometry = mesh._geometry;
  39244. if (previousGeometry) {
  39245. previousGeometry.releaseForMesh(mesh);
  39246. }
  39247. var meshes = this._meshes;
  39248. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39249. mesh._geometry = this;
  39250. this._scene.pushGeometry(this);
  39251. meshes.push(mesh);
  39252. if (this.isReady()) {
  39253. this._applyToMesh(mesh);
  39254. }
  39255. else {
  39256. mesh._boundingInfo = this._boundingInfo;
  39257. }
  39258. };
  39259. Geometry.prototype._updateExtend = function (data) {
  39260. if (data === void 0) { data = null; }
  39261. if (!data) {
  39262. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39263. }
  39264. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39265. };
  39266. Geometry.prototype._applyToMesh = function (mesh) {
  39267. var numOfMeshes = this._meshes.length;
  39268. // vertexBuffers
  39269. for (var kind in this._vertexBuffers) {
  39270. if (numOfMeshes === 1) {
  39271. this._vertexBuffers[kind].create();
  39272. }
  39273. var buffer = this._vertexBuffers[kind].getBuffer();
  39274. if (buffer)
  39275. buffer.references = numOfMeshes;
  39276. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39277. if (!this._extend) {
  39278. this._updateExtend();
  39279. }
  39280. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39281. mesh._createGlobalSubMesh(false);
  39282. //bounding info was just created again, world matrix should be applied again.
  39283. mesh._updateBoundingInfo();
  39284. }
  39285. }
  39286. // indexBuffer
  39287. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39288. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39289. }
  39290. if (this._indexBuffer) {
  39291. this._indexBuffer.references = numOfMeshes;
  39292. }
  39293. };
  39294. Geometry.prototype.notifyUpdate = function (kind) {
  39295. if (this.onGeometryUpdated) {
  39296. this.onGeometryUpdated(this, kind);
  39297. }
  39298. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39299. var mesh = _a[_i];
  39300. mesh._markSubMeshesAsAttributesDirty();
  39301. }
  39302. };
  39303. /**
  39304. * Load the geometry if it was flagged as delay loaded
  39305. * @param scene defines the hosting scene
  39306. * @param onLoaded defines a callback called when the geometry is loaded
  39307. */
  39308. Geometry.prototype.load = function (scene, onLoaded) {
  39309. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39310. return;
  39311. }
  39312. if (this.isReady()) {
  39313. if (onLoaded) {
  39314. onLoaded();
  39315. }
  39316. return;
  39317. }
  39318. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39319. this._queueLoad(scene, onLoaded);
  39320. };
  39321. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39322. var _this = this;
  39323. if (!this.delayLoadingFile) {
  39324. return;
  39325. }
  39326. scene._addPendingData(this);
  39327. scene._loadFile(this.delayLoadingFile, function (data) {
  39328. if (!_this._delayLoadingFunction) {
  39329. return;
  39330. }
  39331. _this._delayLoadingFunction(JSON.parse(data), _this);
  39332. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39333. _this._delayInfo = [];
  39334. scene._removePendingData(_this);
  39335. var meshes = _this._meshes;
  39336. var numOfMeshes = meshes.length;
  39337. for (var index = 0; index < numOfMeshes; index++) {
  39338. _this._applyToMesh(meshes[index]);
  39339. }
  39340. if (onLoaded) {
  39341. onLoaded();
  39342. }
  39343. }, undefined, true);
  39344. };
  39345. /**
  39346. * Invert the geometry to move from a right handed system to a left handed one.
  39347. */
  39348. Geometry.prototype.toLeftHanded = function () {
  39349. // Flip faces
  39350. var tIndices = this.getIndices(false);
  39351. if (tIndices != null && tIndices.length > 0) {
  39352. for (var i = 0; i < tIndices.length; i += 3) {
  39353. var tTemp = tIndices[i + 0];
  39354. tIndices[i + 0] = tIndices[i + 2];
  39355. tIndices[i + 2] = tTemp;
  39356. }
  39357. this.setIndices(tIndices);
  39358. }
  39359. // Negate position.z
  39360. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39361. if (tPositions != null && tPositions.length > 0) {
  39362. for (var i = 0; i < tPositions.length; i += 3) {
  39363. tPositions[i + 2] = -tPositions[i + 2];
  39364. }
  39365. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39366. }
  39367. // Negate normal.z
  39368. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39369. if (tNormals != null && tNormals.length > 0) {
  39370. for (var i = 0; i < tNormals.length; i += 3) {
  39371. tNormals[i + 2] = -tNormals[i + 2];
  39372. }
  39373. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39374. }
  39375. };
  39376. // Cache
  39377. /** @hidden */
  39378. Geometry.prototype._resetPointsArrayCache = function () {
  39379. this._positions = null;
  39380. };
  39381. /** @hidden */
  39382. Geometry.prototype._generatePointsArray = function () {
  39383. if (this._positions)
  39384. return true;
  39385. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39386. if (!data || data.length === 0) {
  39387. return false;
  39388. }
  39389. this._positions = [];
  39390. for (var index = 0; index < data.length; index += 3) {
  39391. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39392. }
  39393. return true;
  39394. };
  39395. /**
  39396. * Gets a value indicating if the geometry is disposed
  39397. * @returns true if the geometry was disposed
  39398. */
  39399. Geometry.prototype.isDisposed = function () {
  39400. return this._isDisposed;
  39401. };
  39402. Geometry.prototype._disposeVertexArrayObjects = function () {
  39403. if (this._vertexArrayObjects) {
  39404. for (var kind in this._vertexArrayObjects) {
  39405. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39406. }
  39407. this._vertexArrayObjects = {};
  39408. }
  39409. };
  39410. /**
  39411. * Free all associated resources
  39412. */
  39413. Geometry.prototype.dispose = function () {
  39414. var meshes = this._meshes;
  39415. var numOfMeshes = meshes.length;
  39416. var index;
  39417. for (index = 0; index < numOfMeshes; index++) {
  39418. this.releaseForMesh(meshes[index]);
  39419. }
  39420. this._meshes = [];
  39421. this._disposeVertexArrayObjects();
  39422. for (var kind in this._vertexBuffers) {
  39423. this._vertexBuffers[kind].dispose();
  39424. }
  39425. this._vertexBuffers = {};
  39426. this._totalVertices = 0;
  39427. if (this._indexBuffer) {
  39428. this._engine._releaseBuffer(this._indexBuffer);
  39429. }
  39430. this._indexBuffer = null;
  39431. this._indices = [];
  39432. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39433. this.delayLoadingFile = null;
  39434. this._delayLoadingFunction = null;
  39435. this._delayInfo = [];
  39436. this._boundingInfo = null;
  39437. this._scene.removeGeometry(this);
  39438. this._isDisposed = true;
  39439. };
  39440. /**
  39441. * Clone the current geometry into a new geometry
  39442. * @param id defines the unique ID of the new geometry
  39443. * @returns a new geometry object
  39444. */
  39445. Geometry.prototype.copy = function (id) {
  39446. var vertexData = new BABYLON.VertexData();
  39447. vertexData.indices = [];
  39448. var indices = this.getIndices();
  39449. if (indices) {
  39450. for (var index = 0; index < indices.length; index++) {
  39451. vertexData.indices.push(indices[index]);
  39452. }
  39453. }
  39454. var updatable = false;
  39455. var stopChecking = false;
  39456. var kind;
  39457. for (kind in this._vertexBuffers) {
  39458. // using slice() to make a copy of the array and not just reference it
  39459. var data = this.getVerticesData(kind);
  39460. if (data instanceof Float32Array) {
  39461. vertexData.set(new Float32Array(data), kind);
  39462. }
  39463. else {
  39464. vertexData.set(data.slice(0), kind);
  39465. }
  39466. if (!stopChecking) {
  39467. var vb = this.getVertexBuffer(kind);
  39468. if (vb) {
  39469. updatable = vb.isUpdatable();
  39470. stopChecking = !updatable;
  39471. }
  39472. }
  39473. }
  39474. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39475. geometry.delayLoadState = this.delayLoadState;
  39476. geometry.delayLoadingFile = this.delayLoadingFile;
  39477. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39478. for (kind in this._delayInfo) {
  39479. geometry._delayInfo = geometry._delayInfo || [];
  39480. geometry._delayInfo.push(kind);
  39481. }
  39482. // Bounding info
  39483. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39484. return geometry;
  39485. };
  39486. /**
  39487. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39488. * @return a JSON representation of the current geometry data (without the vertices data)
  39489. */
  39490. Geometry.prototype.serialize = function () {
  39491. var serializationObject = {};
  39492. serializationObject.id = this.id;
  39493. serializationObject.updatable = this._updatable;
  39494. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39495. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39496. }
  39497. return serializationObject;
  39498. };
  39499. Geometry.prototype.toNumberArray = function (origin) {
  39500. if (Array.isArray(origin)) {
  39501. return origin;
  39502. }
  39503. else {
  39504. return Array.prototype.slice.call(origin);
  39505. }
  39506. };
  39507. /**
  39508. * Serialize all vertices data into a JSON oject
  39509. * @returns a JSON representation of the current geometry data
  39510. */
  39511. Geometry.prototype.serializeVerticeData = function () {
  39512. var serializationObject = this.serialize();
  39513. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39514. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39515. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39516. serializationObject.positions._updatable = true;
  39517. }
  39518. }
  39519. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39520. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39521. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39522. serializationObject.normals._updatable = true;
  39523. }
  39524. }
  39525. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39526. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39527. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39528. serializationObject.tangets._updatable = true;
  39529. }
  39530. }
  39531. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39532. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39533. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39534. serializationObject.uvs._updatable = true;
  39535. }
  39536. }
  39537. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39538. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39539. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39540. serializationObject.uv2s._updatable = true;
  39541. }
  39542. }
  39543. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39544. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39545. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39546. serializationObject.uv3s._updatable = true;
  39547. }
  39548. }
  39549. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39550. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39551. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39552. serializationObject.uv4s._updatable = true;
  39553. }
  39554. }
  39555. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39556. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39557. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39558. serializationObject.uv5s._updatable = true;
  39559. }
  39560. }
  39561. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39562. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39563. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39564. serializationObject.uv6s._updatable = true;
  39565. }
  39566. }
  39567. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39568. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39569. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39570. serializationObject.colors._updatable = true;
  39571. }
  39572. }
  39573. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39574. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39575. serializationObject.matricesIndices._isExpanded = true;
  39576. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39577. serializationObject.matricesIndices._updatable = true;
  39578. }
  39579. }
  39580. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39581. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39582. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39583. serializationObject.matricesWeights._updatable = true;
  39584. }
  39585. }
  39586. serializationObject.indices = this.toNumberArray(this.getIndices());
  39587. return serializationObject;
  39588. };
  39589. // Statics
  39590. /**
  39591. * Extracts a clone of a mesh geometry
  39592. * @param mesh defines the source mesh
  39593. * @param id defines the unique ID of the new geometry object
  39594. * @returns the new geometry object
  39595. */
  39596. Geometry.ExtractFromMesh = function (mesh, id) {
  39597. var geometry = mesh._geometry;
  39598. if (!geometry) {
  39599. return null;
  39600. }
  39601. return geometry.copy(id);
  39602. };
  39603. /**
  39604. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39605. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39606. * Be aware Math.random() could cause collisions, but:
  39607. * "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"
  39608. * @returns a string containing a new GUID
  39609. */
  39610. Geometry.RandomId = function () {
  39611. return BABYLON.Tools.RandomId();
  39612. };
  39613. /** @hidden */
  39614. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39615. var scene = mesh.getScene();
  39616. // Geometry
  39617. var geometryId = parsedGeometry.geometryId;
  39618. if (geometryId) {
  39619. var geometry = scene.getGeometryByID(geometryId);
  39620. if (geometry) {
  39621. geometry.applyToMesh(mesh);
  39622. }
  39623. }
  39624. else if (parsedGeometry instanceof ArrayBuffer) {
  39625. var binaryInfo = mesh._binaryInfo;
  39626. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39627. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39628. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39629. }
  39630. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39631. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39632. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39633. }
  39634. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39635. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39636. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39637. }
  39638. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39639. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39640. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39641. }
  39642. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39643. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39644. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39645. }
  39646. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39647. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39648. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39649. }
  39650. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39651. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39652. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39653. }
  39654. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39655. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39656. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39657. }
  39658. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39659. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39660. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39661. }
  39662. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39663. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39664. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39665. }
  39666. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39667. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39668. var floatIndices = [];
  39669. for (var i = 0; i < matricesIndicesData.length; i++) {
  39670. var index = matricesIndicesData[i];
  39671. floatIndices.push(index & 0x000000FF);
  39672. floatIndices.push((index & 0x0000FF00) >> 8);
  39673. floatIndices.push((index & 0x00FF0000) >> 16);
  39674. floatIndices.push(index >> 24);
  39675. }
  39676. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39677. }
  39678. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39679. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39680. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39681. }
  39682. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39683. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39684. mesh.setIndices(indicesData, null);
  39685. }
  39686. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39687. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39688. mesh.subMeshes = [];
  39689. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39690. var materialIndex = subMeshesData[(i * 5) + 0];
  39691. var verticesStart = subMeshesData[(i * 5) + 1];
  39692. var verticesCount = subMeshesData[(i * 5) + 2];
  39693. var indexStart = subMeshesData[(i * 5) + 3];
  39694. var indexCount = subMeshesData[(i * 5) + 4];
  39695. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39696. }
  39697. }
  39698. }
  39699. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39700. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39701. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39702. if (parsedGeometry.tangents) {
  39703. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39704. }
  39705. if (parsedGeometry.uvs) {
  39706. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39707. }
  39708. if (parsedGeometry.uvs2) {
  39709. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39710. }
  39711. if (parsedGeometry.uvs3) {
  39712. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39713. }
  39714. if (parsedGeometry.uvs4) {
  39715. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39716. }
  39717. if (parsedGeometry.uvs5) {
  39718. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39719. }
  39720. if (parsedGeometry.uvs6) {
  39721. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39722. }
  39723. if (parsedGeometry.colors) {
  39724. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39725. }
  39726. if (parsedGeometry.matricesIndices) {
  39727. if (!parsedGeometry.matricesIndices._isExpanded) {
  39728. var floatIndices = [];
  39729. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39730. var matricesIndex = parsedGeometry.matricesIndices[i];
  39731. floatIndices.push(matricesIndex & 0x000000FF);
  39732. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39733. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39734. floatIndices.push(matricesIndex >> 24);
  39735. }
  39736. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39737. }
  39738. else {
  39739. delete parsedGeometry.matricesIndices._isExpanded;
  39740. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39741. }
  39742. }
  39743. if (parsedGeometry.matricesIndicesExtra) {
  39744. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39745. var floatIndices = [];
  39746. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39747. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39748. floatIndices.push(matricesIndex & 0x000000FF);
  39749. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39750. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39751. floatIndices.push(matricesIndex >> 24);
  39752. }
  39753. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39754. }
  39755. else {
  39756. delete parsedGeometry.matricesIndices._isExpanded;
  39757. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39758. }
  39759. }
  39760. if (parsedGeometry.matricesWeights) {
  39761. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39762. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39763. }
  39764. if (parsedGeometry.matricesWeightsExtra) {
  39765. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39766. }
  39767. mesh.setIndices(parsedGeometry.indices, null);
  39768. }
  39769. // SubMeshes
  39770. if (parsedGeometry.subMeshes) {
  39771. mesh.subMeshes = [];
  39772. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39773. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39774. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39775. }
  39776. }
  39777. // Flat shading
  39778. if (mesh._shouldGenerateFlatShading) {
  39779. mesh.convertToFlatShadedMesh();
  39780. delete mesh._shouldGenerateFlatShading;
  39781. }
  39782. // Update
  39783. mesh.computeWorldMatrix(true);
  39784. // Octree
  39785. var sceneOctree = scene.selectionOctree;
  39786. if (sceneOctree !== undefined && sceneOctree !== null) {
  39787. sceneOctree.addMesh(mesh);
  39788. }
  39789. };
  39790. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39791. var epsilon = 1e-3;
  39792. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39793. return;
  39794. }
  39795. var noInfluenceBoneIndex = 0.0;
  39796. if (parsedGeometry.skeletonId > -1) {
  39797. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39798. if (!skeleton) {
  39799. return;
  39800. }
  39801. noInfluenceBoneIndex = skeleton.bones.length;
  39802. }
  39803. else {
  39804. return;
  39805. }
  39806. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39807. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39808. var matricesWeights = parsedGeometry.matricesWeights;
  39809. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39810. var influencers = parsedGeometry.numBoneInfluencer;
  39811. var size = matricesWeights.length;
  39812. for (var i = 0; i < size; i += 4) {
  39813. var weight = 0.0;
  39814. var firstZeroWeight = -1;
  39815. for (var j = 0; j < 4; j++) {
  39816. var w = matricesWeights[i + j];
  39817. weight += w;
  39818. if (w < epsilon && firstZeroWeight < 0) {
  39819. firstZeroWeight = j;
  39820. }
  39821. }
  39822. if (matricesWeightsExtra) {
  39823. for (var j = 0; j < 4; j++) {
  39824. var w = matricesWeightsExtra[i + j];
  39825. weight += w;
  39826. if (w < epsilon && firstZeroWeight < 0) {
  39827. firstZeroWeight = j + 4;
  39828. }
  39829. }
  39830. }
  39831. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39832. firstZeroWeight = influencers - 1;
  39833. }
  39834. if (weight > epsilon) {
  39835. var mweight = 1.0 / weight;
  39836. for (var j = 0; j < 4; j++) {
  39837. matricesWeights[i + j] *= mweight;
  39838. }
  39839. if (matricesWeightsExtra) {
  39840. for (var j = 0; j < 4; j++) {
  39841. matricesWeightsExtra[i + j] *= mweight;
  39842. }
  39843. }
  39844. }
  39845. else {
  39846. if (firstZeroWeight >= 4) {
  39847. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39848. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39849. }
  39850. else {
  39851. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39852. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39853. }
  39854. }
  39855. }
  39856. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39857. if (parsedGeometry.matricesWeightsExtra) {
  39858. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39859. }
  39860. };
  39861. /**
  39862. * Create a new geometry from persisted data (Using .babylon file format)
  39863. * @param parsedVertexData defines the persisted data
  39864. * @param scene defines the hosting scene
  39865. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39866. * @returns the new geometry object
  39867. */
  39868. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39869. if (scene.getGeometryByID(parsedVertexData.id)) {
  39870. return null; // null since geometry could be something else than a box...
  39871. }
  39872. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39873. if (BABYLON.Tags) {
  39874. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39875. }
  39876. if (parsedVertexData.delayLoadingFile) {
  39877. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39878. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39879. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39880. geometry._delayInfo = [];
  39881. if (parsedVertexData.hasUVs) {
  39882. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39883. }
  39884. if (parsedVertexData.hasUVs2) {
  39885. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39886. }
  39887. if (parsedVertexData.hasUVs3) {
  39888. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39889. }
  39890. if (parsedVertexData.hasUVs4) {
  39891. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39892. }
  39893. if (parsedVertexData.hasUVs5) {
  39894. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39895. }
  39896. if (parsedVertexData.hasUVs6) {
  39897. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39898. }
  39899. if (parsedVertexData.hasColors) {
  39900. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39901. }
  39902. if (parsedVertexData.hasMatricesIndices) {
  39903. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39904. }
  39905. if (parsedVertexData.hasMatricesWeights) {
  39906. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39907. }
  39908. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39909. }
  39910. else {
  39911. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39912. }
  39913. scene.pushGeometry(geometry, true);
  39914. return geometry;
  39915. };
  39916. return Geometry;
  39917. }());
  39918. BABYLON.Geometry = Geometry;
  39919. // Primitives
  39920. /// Abstract class
  39921. /**
  39922. * Abstract class used to provide common services for all typed geometries
  39923. * @hidden
  39924. */
  39925. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39926. __extends(_PrimitiveGeometry, _super);
  39927. /**
  39928. * Creates a new typed geometry
  39929. * @param id defines the unique ID of the geometry
  39930. * @param scene defines the hosting scene
  39931. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39932. * @param mesh defines the hosting mesh (can be null)
  39933. */
  39934. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39935. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39936. if (mesh === void 0) { mesh = null; }
  39937. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39938. _this._canBeRegenerated = _canBeRegenerated;
  39939. _this._beingRegenerated = true;
  39940. _this.regenerate();
  39941. _this._beingRegenerated = false;
  39942. return _this;
  39943. }
  39944. /**
  39945. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39946. * @returns true if the geometry can be regenerated
  39947. */
  39948. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39949. return this._canBeRegenerated;
  39950. };
  39951. /**
  39952. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39953. */
  39954. _PrimitiveGeometry.prototype.regenerate = function () {
  39955. if (!this._canBeRegenerated) {
  39956. return;
  39957. }
  39958. this._beingRegenerated = true;
  39959. this.setAllVerticesData(this._regenerateVertexData(), false);
  39960. this._beingRegenerated = false;
  39961. };
  39962. /**
  39963. * Clone the geometry
  39964. * @param id defines the unique ID of the new geometry
  39965. * @returns the new geometry
  39966. */
  39967. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39968. return _super.prototype.copy.call(this, id);
  39969. };
  39970. // overrides
  39971. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39972. if (!this._beingRegenerated) {
  39973. return;
  39974. }
  39975. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39976. };
  39977. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39978. if (!this._beingRegenerated) {
  39979. return;
  39980. }
  39981. _super.prototype.setVerticesData.call(this, kind, data, false);
  39982. };
  39983. // to override
  39984. /** @hidden */
  39985. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39986. throw new Error("Abstract method");
  39987. };
  39988. _PrimitiveGeometry.prototype.copy = function (id) {
  39989. throw new Error("Must be overriden in sub-classes.");
  39990. };
  39991. _PrimitiveGeometry.prototype.serialize = function () {
  39992. var serializationObject = _super.prototype.serialize.call(this);
  39993. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39994. return serializationObject;
  39995. };
  39996. return _PrimitiveGeometry;
  39997. }(Geometry));
  39998. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39999. /**
  40000. * Creates a ribbon geometry
  40001. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40002. */
  40003. var RibbonGeometry = /** @class */ (function (_super) {
  40004. __extends(RibbonGeometry, _super);
  40005. /**
  40006. * Creates a ribbon geometry
  40007. * @param id defines the unique ID of the geometry
  40008. * @param scene defines the hosting scene
  40009. * @param pathArray defines the array of paths to use
  40010. * @param closeArray defines if the last path and the first path must be joined
  40011. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40012. * @param offset defines the offset between points
  40013. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40014. * @param mesh defines the hosting mesh (can be null)
  40015. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40016. */
  40017. function RibbonGeometry(id, scene,
  40018. /**
  40019. * Defines the array of paths to use
  40020. */
  40021. pathArray,
  40022. /**
  40023. * Defines if the last and first points of each path in your pathArray must be joined
  40024. */
  40025. closeArray,
  40026. /**
  40027. * Defines if the last and first points of each path in your pathArray must be joined
  40028. */
  40029. closePath,
  40030. /**
  40031. * Defines the offset between points
  40032. */
  40033. offset, canBeRegenerated, mesh,
  40034. /**
  40035. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40036. */
  40037. side) {
  40038. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40039. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40040. _this.pathArray = pathArray;
  40041. _this.closeArray = closeArray;
  40042. _this.closePath = closePath;
  40043. _this.offset = offset;
  40044. _this.side = side;
  40045. return _this;
  40046. }
  40047. /** @hidden */
  40048. RibbonGeometry.prototype._regenerateVertexData = function () {
  40049. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40050. };
  40051. RibbonGeometry.prototype.copy = function (id) {
  40052. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40053. };
  40054. return RibbonGeometry;
  40055. }(_PrimitiveGeometry));
  40056. BABYLON.RibbonGeometry = RibbonGeometry;
  40057. /**
  40058. * Creates a box geometry
  40059. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40060. */
  40061. var BoxGeometry = /** @class */ (function (_super) {
  40062. __extends(BoxGeometry, _super);
  40063. /**
  40064. * Creates a box geometry
  40065. * @param id defines the unique ID of the geometry
  40066. * @param scene defines the hosting scene
  40067. * @param size defines the zise of the box (width, height and depth are the same)
  40068. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40069. * @param mesh defines the hosting mesh (can be null)
  40070. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40071. */
  40072. function BoxGeometry(id, scene,
  40073. /**
  40074. * Defines the zise of the box (width, height and depth are the same)
  40075. */
  40076. size, canBeRegenerated, mesh,
  40077. /**
  40078. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40079. */
  40080. side) {
  40081. if (mesh === void 0) { mesh = null; }
  40082. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40083. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40084. _this.size = size;
  40085. _this.side = side;
  40086. return _this;
  40087. }
  40088. /** @hidden */
  40089. BoxGeometry.prototype._regenerateVertexData = function () {
  40090. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40091. };
  40092. BoxGeometry.prototype.copy = function (id) {
  40093. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40094. };
  40095. BoxGeometry.prototype.serialize = function () {
  40096. var serializationObject = _super.prototype.serialize.call(this);
  40097. serializationObject.size = this.size;
  40098. return serializationObject;
  40099. };
  40100. BoxGeometry.Parse = function (parsedBox, scene) {
  40101. if (scene.getGeometryByID(parsedBox.id)) {
  40102. return null; // null since geometry could be something else than a box...
  40103. }
  40104. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40105. if (BABYLON.Tags) {
  40106. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40107. }
  40108. scene.pushGeometry(box, true);
  40109. return box;
  40110. };
  40111. return BoxGeometry;
  40112. }(_PrimitiveGeometry));
  40113. BABYLON.BoxGeometry = BoxGeometry;
  40114. /**
  40115. * Creates a sphere geometry
  40116. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40117. */
  40118. var SphereGeometry = /** @class */ (function (_super) {
  40119. __extends(SphereGeometry, _super);
  40120. /**
  40121. * Create a new sphere geometry
  40122. * @param id defines the unique ID of the geometry
  40123. * @param scene defines the hosting scene
  40124. * @param segments defines the number of segments to use to create the sphere
  40125. * @param diameter defines the diameter of the sphere
  40126. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40127. * @param mesh defines the hosting mesh (can be null)
  40128. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40129. */
  40130. function SphereGeometry(id, scene,
  40131. /**
  40132. * Defines the number of segments to use to create the sphere
  40133. */
  40134. segments,
  40135. /**
  40136. * Defines the diameter of the sphere
  40137. */
  40138. diameter, canBeRegenerated, mesh,
  40139. /**
  40140. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40141. */
  40142. side) {
  40143. if (mesh === void 0) { mesh = null; }
  40144. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40145. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40146. _this.segments = segments;
  40147. _this.diameter = diameter;
  40148. _this.side = side;
  40149. return _this;
  40150. }
  40151. /** @hidden */
  40152. SphereGeometry.prototype._regenerateVertexData = function () {
  40153. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40154. };
  40155. SphereGeometry.prototype.copy = function (id) {
  40156. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40157. };
  40158. SphereGeometry.prototype.serialize = function () {
  40159. var serializationObject = _super.prototype.serialize.call(this);
  40160. serializationObject.segments = this.segments;
  40161. serializationObject.diameter = this.diameter;
  40162. return serializationObject;
  40163. };
  40164. SphereGeometry.Parse = function (parsedSphere, scene) {
  40165. if (scene.getGeometryByID(parsedSphere.id)) {
  40166. return null; // null since geometry could be something else than a sphere...
  40167. }
  40168. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40169. if (BABYLON.Tags) {
  40170. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40171. }
  40172. scene.pushGeometry(sphere, true);
  40173. return sphere;
  40174. };
  40175. return SphereGeometry;
  40176. }(_PrimitiveGeometry));
  40177. BABYLON.SphereGeometry = SphereGeometry;
  40178. /**
  40179. * Creates a disc geometry
  40180. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40181. */
  40182. var DiscGeometry = /** @class */ (function (_super) {
  40183. __extends(DiscGeometry, _super);
  40184. /**
  40185. * Creates a new disc geometry
  40186. * @param id defines the unique ID of the geometry
  40187. * @param scene defines the hosting scene
  40188. * @param radius defines the radius of the disc
  40189. * @param tessellation defines the tesselation factor to apply to the disc
  40190. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40191. * @param mesh defines the hosting mesh (can be null)
  40192. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40193. */
  40194. function DiscGeometry(id, scene,
  40195. /**
  40196. * Defines the radius of the disc
  40197. */
  40198. radius,
  40199. /**
  40200. * Defines the tesselation factor to apply to the disc
  40201. */
  40202. tessellation, canBeRegenerated, mesh,
  40203. /**
  40204. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40205. */
  40206. side) {
  40207. if (mesh === void 0) { mesh = null; }
  40208. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40209. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40210. _this.radius = radius;
  40211. _this.tessellation = tessellation;
  40212. _this.side = side;
  40213. return _this;
  40214. }
  40215. /** @hidden */
  40216. DiscGeometry.prototype._regenerateVertexData = function () {
  40217. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40218. };
  40219. DiscGeometry.prototype.copy = function (id) {
  40220. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40221. };
  40222. return DiscGeometry;
  40223. }(_PrimitiveGeometry));
  40224. BABYLON.DiscGeometry = DiscGeometry;
  40225. /**
  40226. * Creates a new cylinder geometry
  40227. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40228. */
  40229. var CylinderGeometry = /** @class */ (function (_super) {
  40230. __extends(CylinderGeometry, _super);
  40231. /**
  40232. * Creates a new cylinder geometry
  40233. * @param id defines the unique ID of the geometry
  40234. * @param scene defines the hosting scene
  40235. * @param height defines the height of the cylinder
  40236. * @param diameterTop defines the diameter of the cylinder's top cap
  40237. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40238. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40239. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40240. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40241. * @param mesh defines the hosting mesh (can be null)
  40242. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40243. */
  40244. function CylinderGeometry(id, scene,
  40245. /**
  40246. * Defines the height of the cylinder
  40247. */
  40248. height,
  40249. /**
  40250. * Defines the diameter of the cylinder's top cap
  40251. */
  40252. diameterTop,
  40253. /**
  40254. * Defines the diameter of the cylinder's bottom cap
  40255. */
  40256. diameterBottom,
  40257. /**
  40258. * Defines the tessellation factor to apply to the cylinder
  40259. */
  40260. tessellation,
  40261. /**
  40262. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40263. */
  40264. subdivisions, canBeRegenerated, mesh,
  40265. /**
  40266. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40267. */
  40268. side) {
  40269. if (subdivisions === void 0) { subdivisions = 1; }
  40270. if (mesh === void 0) { mesh = null; }
  40271. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40272. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40273. _this.height = height;
  40274. _this.diameterTop = diameterTop;
  40275. _this.diameterBottom = diameterBottom;
  40276. _this.tessellation = tessellation;
  40277. _this.subdivisions = subdivisions;
  40278. _this.side = side;
  40279. return _this;
  40280. }
  40281. /** @hidden */
  40282. CylinderGeometry.prototype._regenerateVertexData = function () {
  40283. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40284. };
  40285. CylinderGeometry.prototype.copy = function (id) {
  40286. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40287. };
  40288. CylinderGeometry.prototype.serialize = function () {
  40289. var serializationObject = _super.prototype.serialize.call(this);
  40290. serializationObject.height = this.height;
  40291. serializationObject.diameterTop = this.diameterTop;
  40292. serializationObject.diameterBottom = this.diameterBottom;
  40293. serializationObject.tessellation = this.tessellation;
  40294. return serializationObject;
  40295. };
  40296. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40297. if (scene.getGeometryByID(parsedCylinder.id)) {
  40298. return null; // null since geometry could be something else than a cylinder...
  40299. }
  40300. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40301. if (BABYLON.Tags) {
  40302. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40303. }
  40304. scene.pushGeometry(cylinder, true);
  40305. return cylinder;
  40306. };
  40307. return CylinderGeometry;
  40308. }(_PrimitiveGeometry));
  40309. BABYLON.CylinderGeometry = CylinderGeometry;
  40310. /**
  40311. * Creates a new torus geometry
  40312. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40313. */
  40314. var TorusGeometry = /** @class */ (function (_super) {
  40315. __extends(TorusGeometry, _super);
  40316. /**
  40317. * Creates a new torus geometry
  40318. * @param id defines the unique ID of the geometry
  40319. * @param scene defines the hosting scene
  40320. * @param diameter defines the diameter of the torus
  40321. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40322. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40323. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40324. * @param mesh defines the hosting mesh (can be null)
  40325. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40326. */
  40327. function TorusGeometry(id, scene,
  40328. /**
  40329. * Defines the diameter of the torus
  40330. */
  40331. diameter,
  40332. /**
  40333. * Defines the thickness of the torus (ie. internal diameter)
  40334. */
  40335. thickness,
  40336. /**
  40337. * Defines the tesselation factor to apply to the torus
  40338. */
  40339. tessellation, canBeRegenerated, mesh,
  40340. /**
  40341. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40342. */
  40343. side) {
  40344. if (mesh === void 0) { mesh = null; }
  40345. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40346. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40347. _this.diameter = diameter;
  40348. _this.thickness = thickness;
  40349. _this.tessellation = tessellation;
  40350. _this.side = side;
  40351. return _this;
  40352. }
  40353. /** @hidden */
  40354. TorusGeometry.prototype._regenerateVertexData = function () {
  40355. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40356. };
  40357. TorusGeometry.prototype.copy = function (id) {
  40358. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40359. };
  40360. TorusGeometry.prototype.serialize = function () {
  40361. var serializationObject = _super.prototype.serialize.call(this);
  40362. serializationObject.diameter = this.diameter;
  40363. serializationObject.thickness = this.thickness;
  40364. serializationObject.tessellation = this.tessellation;
  40365. return serializationObject;
  40366. };
  40367. TorusGeometry.Parse = function (parsedTorus, scene) {
  40368. if (scene.getGeometryByID(parsedTorus.id)) {
  40369. return null; // null since geometry could be something else than a torus...
  40370. }
  40371. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40372. if (BABYLON.Tags) {
  40373. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40374. }
  40375. scene.pushGeometry(torus, true);
  40376. return torus;
  40377. };
  40378. return TorusGeometry;
  40379. }(_PrimitiveGeometry));
  40380. BABYLON.TorusGeometry = TorusGeometry;
  40381. /**
  40382. * Creates a new ground geometry
  40383. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40384. */
  40385. var GroundGeometry = /** @class */ (function (_super) {
  40386. __extends(GroundGeometry, _super);
  40387. /**
  40388. * Creates a new ground geometry
  40389. * @param id defines the unique ID of the geometry
  40390. * @param scene defines the hosting scene
  40391. * @param width defines the width of the ground
  40392. * @param height defines the height of the ground
  40393. * @param subdivisions defines the subdivisions to apply to the ground
  40394. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40395. * @param mesh defines the hosting mesh (can be null)
  40396. */
  40397. function GroundGeometry(id, scene,
  40398. /**
  40399. * Defines the width of the ground
  40400. */
  40401. width,
  40402. /**
  40403. * Defines the height of the ground
  40404. */
  40405. height,
  40406. /**
  40407. * Defines the subdivisions to apply to the ground
  40408. */
  40409. subdivisions, canBeRegenerated, mesh) {
  40410. if (mesh === void 0) { mesh = null; }
  40411. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40412. _this.width = width;
  40413. _this.height = height;
  40414. _this.subdivisions = subdivisions;
  40415. return _this;
  40416. }
  40417. /** @hidden */
  40418. GroundGeometry.prototype._regenerateVertexData = function () {
  40419. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40420. };
  40421. GroundGeometry.prototype.copy = function (id) {
  40422. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40423. };
  40424. GroundGeometry.prototype.serialize = function () {
  40425. var serializationObject = _super.prototype.serialize.call(this);
  40426. serializationObject.width = this.width;
  40427. serializationObject.height = this.height;
  40428. serializationObject.subdivisions = this.subdivisions;
  40429. return serializationObject;
  40430. };
  40431. GroundGeometry.Parse = function (parsedGround, scene) {
  40432. if (scene.getGeometryByID(parsedGround.id)) {
  40433. return null; // null since geometry could be something else than a ground...
  40434. }
  40435. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40436. if (BABYLON.Tags) {
  40437. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40438. }
  40439. scene.pushGeometry(ground, true);
  40440. return ground;
  40441. };
  40442. return GroundGeometry;
  40443. }(_PrimitiveGeometry));
  40444. BABYLON.GroundGeometry = GroundGeometry;
  40445. /**
  40446. * Creates a tiled ground geometry
  40447. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40448. */
  40449. var TiledGroundGeometry = /** @class */ (function (_super) {
  40450. __extends(TiledGroundGeometry, _super);
  40451. /**
  40452. * Creates a tiled ground geometry
  40453. * @param id defines the unique ID of the geometry
  40454. * @param scene defines the hosting scene
  40455. * @param xmin defines the minimum value on X axis
  40456. * @param zmin defines the minimum value on Z axis
  40457. * @param xmax defines the maximum value on X axis
  40458. * @param zmax defines the maximum value on Z axis
  40459. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40460. * @param precision defines the precision to use when computing the tiles
  40461. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40462. * @param mesh defines the hosting mesh (can be null)
  40463. */
  40464. function TiledGroundGeometry(id, scene,
  40465. /**
  40466. * Defines the minimum value on X axis
  40467. */
  40468. xmin,
  40469. /**
  40470. * Defines the minimum value on Z axis
  40471. */
  40472. zmin,
  40473. /**
  40474. * Defines the maximum value on X axis
  40475. */
  40476. xmax,
  40477. /**
  40478. * Defines the maximum value on Z axis
  40479. */
  40480. zmax,
  40481. /**
  40482. * Defines the subdivisions to apply to the ground
  40483. */
  40484. subdivisions,
  40485. /**
  40486. * Defines the precision to use when computing the tiles
  40487. */
  40488. precision, canBeRegenerated, mesh) {
  40489. if (mesh === void 0) { mesh = null; }
  40490. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40491. _this.xmin = xmin;
  40492. _this.zmin = zmin;
  40493. _this.xmax = xmax;
  40494. _this.zmax = zmax;
  40495. _this.subdivisions = subdivisions;
  40496. _this.precision = precision;
  40497. return _this;
  40498. }
  40499. /** @hidden */
  40500. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40501. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40502. };
  40503. TiledGroundGeometry.prototype.copy = function (id) {
  40504. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40505. };
  40506. return TiledGroundGeometry;
  40507. }(_PrimitiveGeometry));
  40508. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40509. /**
  40510. * Creates a plane geometry
  40511. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40512. */
  40513. var PlaneGeometry = /** @class */ (function (_super) {
  40514. __extends(PlaneGeometry, _super);
  40515. /**
  40516. * Creates a plane geometry
  40517. * @param id defines the unique ID of the geometry
  40518. * @param scene defines the hosting scene
  40519. * @param size defines the size of the plane (width === height)
  40520. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40521. * @param mesh defines the hosting mesh (can be null)
  40522. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40523. */
  40524. function PlaneGeometry(id, scene,
  40525. /**
  40526. * Defines the size of the plane (width === height)
  40527. */
  40528. size, canBeRegenerated, mesh,
  40529. /**
  40530. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40531. */
  40532. side) {
  40533. if (mesh === void 0) { mesh = null; }
  40534. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40535. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40536. _this.size = size;
  40537. _this.side = side;
  40538. return _this;
  40539. }
  40540. /** @hidden */
  40541. PlaneGeometry.prototype._regenerateVertexData = function () {
  40542. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40543. };
  40544. PlaneGeometry.prototype.copy = function (id) {
  40545. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40546. };
  40547. PlaneGeometry.prototype.serialize = function () {
  40548. var serializationObject = _super.prototype.serialize.call(this);
  40549. serializationObject.size = this.size;
  40550. return serializationObject;
  40551. };
  40552. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40553. if (scene.getGeometryByID(parsedPlane.id)) {
  40554. return null; // null since geometry could be something else than a ground...
  40555. }
  40556. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40557. if (BABYLON.Tags) {
  40558. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40559. }
  40560. scene.pushGeometry(plane, true);
  40561. return plane;
  40562. };
  40563. return PlaneGeometry;
  40564. }(_PrimitiveGeometry));
  40565. BABYLON.PlaneGeometry = PlaneGeometry;
  40566. /**
  40567. * Creates a torus knot geometry
  40568. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40569. */
  40570. var TorusKnotGeometry = /** @class */ (function (_super) {
  40571. __extends(TorusKnotGeometry, _super);
  40572. /**
  40573. * Creates a torus knot geometry
  40574. * @param id defines the unique ID of the geometry
  40575. * @param scene defines the hosting scene
  40576. * @param radius defines the radius of the torus knot
  40577. * @param tube defines the thickness of the torus knot tube
  40578. * @param radialSegments defines the number of radial segments
  40579. * @param tubularSegments defines the number of tubular segments
  40580. * @param p defines the first number of windings
  40581. * @param q defines the second number of windings
  40582. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40583. * @param mesh defines the hosting mesh (can be null)
  40584. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40585. */
  40586. function TorusKnotGeometry(id, scene,
  40587. /**
  40588. * Defines the radius of the torus knot
  40589. */
  40590. radius,
  40591. /**
  40592. * Defines the thickness of the torus knot tube
  40593. */
  40594. tube,
  40595. /**
  40596. * Defines the number of radial segments
  40597. */
  40598. radialSegments,
  40599. /**
  40600. * Defines the number of tubular segments
  40601. */
  40602. tubularSegments,
  40603. /**
  40604. * Defines the first number of windings
  40605. */
  40606. p,
  40607. /**
  40608. * Defines the second number of windings
  40609. */
  40610. q, canBeRegenerated, mesh,
  40611. /**
  40612. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40613. */
  40614. side) {
  40615. if (mesh === void 0) { mesh = null; }
  40616. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40617. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40618. _this.radius = radius;
  40619. _this.tube = tube;
  40620. _this.radialSegments = radialSegments;
  40621. _this.tubularSegments = tubularSegments;
  40622. _this.p = p;
  40623. _this.q = q;
  40624. _this.side = side;
  40625. return _this;
  40626. }
  40627. /** @hidden */
  40628. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40629. 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 });
  40630. };
  40631. TorusKnotGeometry.prototype.copy = function (id) {
  40632. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40633. };
  40634. TorusKnotGeometry.prototype.serialize = function () {
  40635. var serializationObject = _super.prototype.serialize.call(this);
  40636. serializationObject.radius = this.radius;
  40637. serializationObject.tube = this.tube;
  40638. serializationObject.radialSegments = this.radialSegments;
  40639. serializationObject.tubularSegments = this.tubularSegments;
  40640. serializationObject.p = this.p;
  40641. serializationObject.q = this.q;
  40642. return serializationObject;
  40643. };
  40644. ;
  40645. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40646. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40647. return null; // null since geometry could be something else than a ground...
  40648. }
  40649. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40650. if (BABYLON.Tags) {
  40651. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40652. }
  40653. scene.pushGeometry(torusKnot, true);
  40654. return torusKnot;
  40655. };
  40656. return TorusKnotGeometry;
  40657. }(_PrimitiveGeometry));
  40658. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40659. //}
  40660. })(BABYLON || (BABYLON = {}));
  40661. //# sourceMappingURL=babylon.geometry.js.map
  40662. var BABYLON;
  40663. (function (BABYLON) {
  40664. /**
  40665. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40666. */
  40667. var PerformanceMonitor = /** @class */ (function () {
  40668. /**
  40669. * constructor
  40670. * @param frameSampleSize The number of samples required to saturate the sliding window
  40671. */
  40672. function PerformanceMonitor(frameSampleSize) {
  40673. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40674. this._enabled = true;
  40675. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40676. }
  40677. /**
  40678. * Samples current frame
  40679. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40680. */
  40681. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40682. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40683. if (!this._enabled)
  40684. return;
  40685. if (this._lastFrameTimeMs != null) {
  40686. var dt = timeMs - this._lastFrameTimeMs;
  40687. this._rollingFrameTime.add(dt);
  40688. }
  40689. this._lastFrameTimeMs = timeMs;
  40690. };
  40691. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40692. /**
  40693. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40694. * @return Average frame time in milliseconds
  40695. */
  40696. get: function () {
  40697. return this._rollingFrameTime.average;
  40698. },
  40699. enumerable: true,
  40700. configurable: true
  40701. });
  40702. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40703. /**
  40704. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40705. * @return Frame time variance in milliseconds squared
  40706. */
  40707. get: function () {
  40708. return this._rollingFrameTime.variance;
  40709. },
  40710. enumerable: true,
  40711. configurable: true
  40712. });
  40713. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40714. /**
  40715. * Returns the frame time of the most recent frame
  40716. * @return Frame time in milliseconds
  40717. */
  40718. get: function () {
  40719. return this._rollingFrameTime.history(0);
  40720. },
  40721. enumerable: true,
  40722. configurable: true
  40723. });
  40724. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40725. /**
  40726. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40727. * @return Framerate in frames per second
  40728. */
  40729. get: function () {
  40730. return 1000.0 / this._rollingFrameTime.average;
  40731. },
  40732. enumerable: true,
  40733. configurable: true
  40734. });
  40735. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40736. /**
  40737. * Returns the average framerate in frames per second using the most recent frame time
  40738. * @return Framerate in frames per second
  40739. */
  40740. get: function () {
  40741. var history = this._rollingFrameTime.history(0);
  40742. if (history === 0) {
  40743. return 0;
  40744. }
  40745. return 1000.0 / history;
  40746. },
  40747. enumerable: true,
  40748. configurable: true
  40749. });
  40750. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40751. /**
  40752. * Returns true if enough samples have been taken to completely fill the sliding window
  40753. * @return true if saturated
  40754. */
  40755. get: function () {
  40756. return this._rollingFrameTime.isSaturated();
  40757. },
  40758. enumerable: true,
  40759. configurable: true
  40760. });
  40761. /**
  40762. * Enables contributions to the sliding window sample set
  40763. */
  40764. PerformanceMonitor.prototype.enable = function () {
  40765. this._enabled = true;
  40766. };
  40767. /**
  40768. * Disables contributions to the sliding window sample set
  40769. * Samples will not be interpolated over the disabled period
  40770. */
  40771. PerformanceMonitor.prototype.disable = function () {
  40772. this._enabled = false;
  40773. //clear last sample to avoid interpolating over the disabled period when next enabled
  40774. this._lastFrameTimeMs = null;
  40775. };
  40776. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40777. /**
  40778. * Returns true if sampling is enabled
  40779. * @return true if enabled
  40780. */
  40781. get: function () {
  40782. return this._enabled;
  40783. },
  40784. enumerable: true,
  40785. configurable: true
  40786. });
  40787. /**
  40788. * Resets performance monitor
  40789. */
  40790. PerformanceMonitor.prototype.reset = function () {
  40791. //clear last sample to avoid interpolating over the disabled period when next enabled
  40792. this._lastFrameTimeMs = null;
  40793. //wipe record
  40794. this._rollingFrameTime.reset();
  40795. };
  40796. return PerformanceMonitor;
  40797. }());
  40798. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40799. /**
  40800. * RollingAverage
  40801. *
  40802. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40803. */
  40804. var RollingAverage = /** @class */ (function () {
  40805. /**
  40806. * constructor
  40807. * @param length The number of samples required to saturate the sliding window
  40808. */
  40809. function RollingAverage(length) {
  40810. this._samples = new Array(length);
  40811. this.reset();
  40812. }
  40813. /**
  40814. * Adds a sample to the sample set
  40815. * @param v The sample value
  40816. */
  40817. RollingAverage.prototype.add = function (v) {
  40818. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40819. var delta;
  40820. //we need to check if we've already wrapped round
  40821. if (this.isSaturated()) {
  40822. //remove bottom of stack from mean
  40823. var bottomValue = this._samples[this._pos];
  40824. delta = bottomValue - this.average;
  40825. this.average -= delta / (this._sampleCount - 1);
  40826. this._m2 -= delta * (bottomValue - this.average);
  40827. }
  40828. else {
  40829. this._sampleCount++;
  40830. }
  40831. //add new value to mean
  40832. delta = v - this.average;
  40833. this.average += delta / (this._sampleCount);
  40834. this._m2 += delta * (v - this.average);
  40835. //set the new variance
  40836. this.variance = this._m2 / (this._sampleCount - 1);
  40837. this._samples[this._pos] = v;
  40838. this._pos++;
  40839. this._pos %= this._samples.length; //positive wrap around
  40840. };
  40841. /**
  40842. * Returns previously added values or null if outside of history or outside the sliding window domain
  40843. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40844. * @return Value previously recorded with add() or null if outside of range
  40845. */
  40846. RollingAverage.prototype.history = function (i) {
  40847. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40848. return 0;
  40849. }
  40850. var i0 = this._wrapPosition(this._pos - 1.0);
  40851. return this._samples[this._wrapPosition(i0 - i)];
  40852. };
  40853. /**
  40854. * Returns true if enough samples have been taken to completely fill the sliding window
  40855. * @return true if sample-set saturated
  40856. */
  40857. RollingAverage.prototype.isSaturated = function () {
  40858. return this._sampleCount >= this._samples.length;
  40859. };
  40860. /**
  40861. * Resets the rolling average (equivalent to 0 samples taken so far)
  40862. */
  40863. RollingAverage.prototype.reset = function () {
  40864. this.average = 0;
  40865. this.variance = 0;
  40866. this._sampleCount = 0;
  40867. this._pos = 0;
  40868. this._m2 = 0;
  40869. };
  40870. /**
  40871. * Wraps a value around the sample range boundaries
  40872. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40873. * @return Wrapped position in sample range
  40874. */
  40875. RollingAverage.prototype._wrapPosition = function (i) {
  40876. var max = this._samples.length;
  40877. return ((i % max) + max) % max;
  40878. };
  40879. return RollingAverage;
  40880. }());
  40881. BABYLON.RollingAverage = RollingAverage;
  40882. })(BABYLON || (BABYLON = {}));
  40883. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40884. var BABYLON;
  40885. (function (BABYLON) {
  40886. /**
  40887. * "Static Class" containing the most commonly used helper while dealing with material for
  40888. * rendering purpose.
  40889. *
  40890. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40891. *
  40892. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40893. */
  40894. var MaterialHelper = /** @class */ (function () {
  40895. function MaterialHelper() {
  40896. }
  40897. /**
  40898. * Bind the current view position to an effect.
  40899. * @param effect The effect to be bound
  40900. * @param scene The scene the eyes position is used from
  40901. */
  40902. MaterialHelper.BindEyePosition = function (effect, scene) {
  40903. if (scene._forcedViewPosition) {
  40904. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40905. return;
  40906. }
  40907. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40908. };
  40909. /**
  40910. * Helps preparing the defines values about the UVs in used in the effect.
  40911. * UVs are shared as much as we can accross chanels in the shaders.
  40912. * @param texture The texture we are preparing the UVs for
  40913. * @param defines The defines to update
  40914. * @param key The chanel key "diffuse", "specular"... used in the shader
  40915. */
  40916. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40917. defines._needUVs = true;
  40918. defines[key] = true;
  40919. if (texture.getTextureMatrix().isIdentity(true)) {
  40920. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40921. if (texture.coordinatesIndex === 0) {
  40922. defines["MAINUV1"] = true;
  40923. }
  40924. else {
  40925. defines["MAINUV2"] = true;
  40926. }
  40927. }
  40928. else {
  40929. defines[key + "DIRECTUV"] = 0;
  40930. }
  40931. };
  40932. /**
  40933. * Binds a texture matrix value to its corrsponding uniform
  40934. * @param texture The texture to bind the matrix for
  40935. * @param uniformBuffer The uniform buffer receivin the data
  40936. * @param key The chanel key "diffuse", "specular"... used in the shader
  40937. */
  40938. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40939. var matrix = texture.getTextureMatrix();
  40940. if (!matrix.isIdentity(true)) {
  40941. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40942. }
  40943. };
  40944. /**
  40945. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40946. * @param mesh defines the current mesh
  40947. * @param scene defines the current scene
  40948. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40949. * @param pointsCloud defines if point cloud rendering has to be turned on
  40950. * @param fogEnabled defines if fog has to be turned on
  40951. * @param alphaTest defines if alpha testing has to be turned on
  40952. * @param defines defines the current list of defines
  40953. */
  40954. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40955. if (defines._areMiscDirty) {
  40956. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40957. defines["POINTSIZE"] = pointsCloud;
  40958. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40959. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40960. defines["ALPHATEST"] = alphaTest;
  40961. }
  40962. };
  40963. /**
  40964. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40965. * @param scene defines the current scene
  40966. * @param engine defines the current engine
  40967. * @param defines specifies the list of active defines
  40968. * @param useInstances defines if instances have to be turned on
  40969. * @param useClipPlane defines if clip plane have to be turned on
  40970. */
  40971. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40972. if (useClipPlane === void 0) { useClipPlane = null; }
  40973. var changed = false;
  40974. var useClipPlane1 = false;
  40975. var useClipPlane2 = false;
  40976. var useClipPlane3 = false;
  40977. var useClipPlane4 = false;
  40978. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  40979. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  40980. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  40981. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  40982. if (defines["CLIPPLANE"] !== useClipPlane1) {
  40983. defines["CLIPPLANE"] = useClipPlane1;
  40984. changed = true;
  40985. }
  40986. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  40987. defines["CLIPPLANE2"] = useClipPlane2;
  40988. changed = true;
  40989. }
  40990. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  40991. defines["CLIPPLANE3"] = useClipPlane3;
  40992. changed = true;
  40993. }
  40994. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  40995. defines["CLIPPLANE4"] = useClipPlane4;
  40996. changed = true;
  40997. }
  40998. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40999. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41000. changed = true;
  41001. }
  41002. if (defines["INSTANCES"] !== useInstances) {
  41003. defines["INSTANCES"] = useInstances;
  41004. changed = true;
  41005. }
  41006. if (changed) {
  41007. defines.markAsUnprocessed();
  41008. }
  41009. };
  41010. /**
  41011. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41012. * @param mesh The mesh containing the geometry data we will draw
  41013. * @param defines The defines to update
  41014. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41015. * @param useBones Precise whether bones should be used or not (override mesh info)
  41016. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41017. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41018. * @returns false if defines are considered not dirty and have not been checked
  41019. */
  41020. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41021. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41022. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41023. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41024. return false;
  41025. }
  41026. defines._normals = defines._needNormals;
  41027. defines._uvs = defines._needUVs;
  41028. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41029. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41030. defines["TANGENT"] = true;
  41031. }
  41032. if (defines._needUVs) {
  41033. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41034. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41035. }
  41036. else {
  41037. defines["UV1"] = false;
  41038. defines["UV2"] = false;
  41039. }
  41040. if (useVertexColor) {
  41041. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41042. defines["VERTEXCOLOR"] = hasVertexColors;
  41043. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41044. }
  41045. if (useBones) {
  41046. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41047. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41048. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41049. }
  41050. else {
  41051. defines["NUM_BONE_INFLUENCERS"] = 0;
  41052. defines["BonesPerMesh"] = 0;
  41053. }
  41054. }
  41055. if (useMorphTargets) {
  41056. var manager = mesh.morphTargetManager;
  41057. if (manager) {
  41058. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41059. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41060. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41061. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41062. }
  41063. else {
  41064. defines["MORPHTARGETS_TANGENT"] = false;
  41065. defines["MORPHTARGETS_NORMAL"] = false;
  41066. defines["MORPHTARGETS"] = false;
  41067. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41068. }
  41069. }
  41070. return true;
  41071. };
  41072. /**
  41073. * Prepares the defines related to the light information passed in parameter
  41074. * @param scene The scene we are intending to draw
  41075. * @param mesh The mesh the effect is compiling for
  41076. * @param defines The defines to update
  41077. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41078. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41079. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41080. * @returns true if normals will be required for the rest of the effect
  41081. */
  41082. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41083. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41084. if (disableLighting === void 0) { disableLighting = false; }
  41085. if (!defines._areLightsDirty) {
  41086. return defines._needNormals;
  41087. }
  41088. var lightIndex = 0;
  41089. var needNormals = false;
  41090. var needRebuild = false;
  41091. var lightmapMode = false;
  41092. var shadowEnabled = false;
  41093. var specularEnabled = false;
  41094. if (scene.lightsEnabled && !disableLighting) {
  41095. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41096. var light = _a[_i];
  41097. needNormals = true;
  41098. if (defines["LIGHT" + lightIndex] === undefined) {
  41099. needRebuild = true;
  41100. }
  41101. defines["LIGHT" + lightIndex] = true;
  41102. defines["SPOTLIGHT" + lightIndex] = false;
  41103. defines["HEMILIGHT" + lightIndex] = false;
  41104. defines["POINTLIGHT" + lightIndex] = false;
  41105. defines["DIRLIGHT" + lightIndex] = false;
  41106. light.prepareLightSpecificDefines(defines, lightIndex);
  41107. // FallOff.
  41108. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41109. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41110. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41111. switch (light.falloffType) {
  41112. case BABYLON.Light.FALLOFF_GLTF:
  41113. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41114. break;
  41115. case BABYLON.Light.FALLOFF_PHYSICAL:
  41116. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41117. break;
  41118. case BABYLON.Light.FALLOFF_STANDARD:
  41119. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41120. break;
  41121. }
  41122. // Specular
  41123. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41124. specularEnabled = true;
  41125. }
  41126. // Shadows
  41127. defines["SHADOW" + lightIndex] = false;
  41128. defines["SHADOWPCF" + lightIndex] = false;
  41129. defines["SHADOWPCSS" + lightIndex] = false;
  41130. defines["SHADOWPOISSON" + lightIndex] = false;
  41131. defines["SHADOWESM" + lightIndex] = false;
  41132. defines["SHADOWCUBE" + lightIndex] = false;
  41133. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41134. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41135. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41136. var shadowGenerator = light.getShadowGenerator();
  41137. if (shadowGenerator) {
  41138. var shadowMap = shadowGenerator.getShadowMap();
  41139. if (shadowMap) {
  41140. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41141. shadowEnabled = true;
  41142. shadowGenerator.prepareDefines(defines, lightIndex);
  41143. }
  41144. }
  41145. }
  41146. }
  41147. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41148. lightmapMode = true;
  41149. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41150. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41151. }
  41152. else {
  41153. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41154. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41155. }
  41156. lightIndex++;
  41157. if (lightIndex === maxSimultaneousLights)
  41158. break;
  41159. }
  41160. }
  41161. defines["SPECULARTERM"] = specularEnabled;
  41162. defines["SHADOWS"] = shadowEnabled;
  41163. // Resetting all other lights if any
  41164. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41165. if (defines["LIGHT" + index] !== undefined) {
  41166. defines["LIGHT" + index] = false;
  41167. defines["HEMILIGHT" + lightIndex] = false;
  41168. defines["POINTLIGHT" + lightIndex] = false;
  41169. defines["DIRLIGHT" + lightIndex] = false;
  41170. defines["SPOTLIGHT" + lightIndex] = false;
  41171. defines["SHADOW" + lightIndex] = false;
  41172. }
  41173. }
  41174. var caps = scene.getEngine().getCaps();
  41175. if (defines["SHADOWFLOAT"] === undefined) {
  41176. needRebuild = true;
  41177. }
  41178. defines["SHADOWFLOAT"] = shadowEnabled &&
  41179. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41180. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41181. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41182. if (needRebuild) {
  41183. defines.rebuild();
  41184. }
  41185. return needNormals;
  41186. };
  41187. /**
  41188. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41189. * that won t be acctive due to defines being turned off.
  41190. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41191. * @param samplersList The samplers list
  41192. * @param defines The defines helping in the list generation
  41193. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41194. */
  41195. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41196. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41197. var uniformsList;
  41198. var uniformBuffersList = null;
  41199. if (uniformsListOrOptions.uniformsNames) {
  41200. var options = uniformsListOrOptions;
  41201. uniformsList = options.uniformsNames;
  41202. uniformBuffersList = options.uniformBuffersNames;
  41203. samplersList = options.samplers;
  41204. defines = options.defines;
  41205. maxSimultaneousLights = options.maxSimultaneousLights;
  41206. }
  41207. else {
  41208. uniformsList = uniformsListOrOptions;
  41209. if (!samplersList) {
  41210. samplersList = [];
  41211. }
  41212. }
  41213. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41214. if (!defines["LIGHT" + lightIndex]) {
  41215. break;
  41216. }
  41217. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41218. if (uniformBuffersList) {
  41219. uniformBuffersList.push("Light" + lightIndex);
  41220. }
  41221. samplersList.push("shadowSampler" + lightIndex);
  41222. samplersList.push("depthSampler" + lightIndex);
  41223. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41224. samplersList.push("projectionLightSampler" + lightIndex);
  41225. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41226. }
  41227. }
  41228. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41229. uniformsList.push("morphTargetInfluences");
  41230. }
  41231. };
  41232. /**
  41233. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41234. * @param defines The defines to update while falling back
  41235. * @param fallbacks The authorized effect fallbacks
  41236. * @param maxSimultaneousLights The maximum number of lights allowed
  41237. * @param rank the current rank of the Effect
  41238. * @returns The newly affected rank
  41239. */
  41240. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41241. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41242. if (rank === void 0) { rank = 0; }
  41243. var lightFallbackRank = 0;
  41244. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41245. if (!defines["LIGHT" + lightIndex]) {
  41246. break;
  41247. }
  41248. if (lightIndex > 0) {
  41249. lightFallbackRank = rank + lightIndex;
  41250. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41251. }
  41252. if (!defines["SHADOWS"]) {
  41253. if (defines["SHADOW" + lightIndex]) {
  41254. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41255. }
  41256. if (defines["SHADOWPCF" + lightIndex]) {
  41257. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41258. }
  41259. if (defines["SHADOWPCSS" + lightIndex]) {
  41260. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41261. }
  41262. if (defines["SHADOWPOISSON" + lightIndex]) {
  41263. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41264. }
  41265. if (defines["SHADOWESM" + lightIndex]) {
  41266. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41267. }
  41268. }
  41269. }
  41270. return lightFallbackRank++;
  41271. };
  41272. /**
  41273. * Prepares the list of attributes required for morph targets according to the effect defines.
  41274. * @param attribs The current list of supported attribs
  41275. * @param mesh The mesh to prepare the morph targets attributes for
  41276. * @param defines The current Defines of the effect
  41277. */
  41278. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41279. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41280. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41281. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41282. var manager = mesh.morphTargetManager;
  41283. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41284. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41285. for (var index = 0; index < influencers; index++) {
  41286. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41287. if (normal) {
  41288. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41289. }
  41290. if (tangent) {
  41291. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41292. }
  41293. if (attribs.length > maxAttributesCount) {
  41294. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41295. }
  41296. }
  41297. }
  41298. };
  41299. /**
  41300. * Prepares the list of attributes required for bones according to the effect defines.
  41301. * @param attribs The current list of supported attribs
  41302. * @param mesh The mesh to prepare the bones attributes for
  41303. * @param defines The current Defines of the effect
  41304. * @param fallbacks The current efffect fallback strategy
  41305. */
  41306. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41307. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41308. fallbacks.addCPUSkinningFallback(0, mesh);
  41309. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41310. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41311. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41312. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41313. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41314. }
  41315. }
  41316. };
  41317. /**
  41318. * Prepares the list of attributes required for instances according to the effect defines.
  41319. * @param attribs The current list of supported attribs
  41320. * @param defines The current Defines of the effect
  41321. */
  41322. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41323. if (defines["INSTANCES"]) {
  41324. attribs.push("world0");
  41325. attribs.push("world1");
  41326. attribs.push("world2");
  41327. attribs.push("world3");
  41328. }
  41329. };
  41330. /**
  41331. * Binds the light shadow information to the effect for the given mesh.
  41332. * @param light The light containing the generator
  41333. * @param scene The scene the lights belongs to
  41334. * @param mesh The mesh we are binding the information to render
  41335. * @param lightIndex The light index in the effect used to render the mesh
  41336. * @param effect The effect we are binding the data to
  41337. */
  41338. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41339. if (light.shadowEnabled && mesh.receiveShadows) {
  41340. var shadowGenerator = light.getShadowGenerator();
  41341. if (shadowGenerator) {
  41342. shadowGenerator.bindShadowLight(lightIndex, effect);
  41343. }
  41344. }
  41345. };
  41346. /**
  41347. * Binds the light information to the effect.
  41348. * @param light The light containing the generator
  41349. * @param effect The effect we are binding the data to
  41350. * @param lightIndex The light index in the effect used to render
  41351. */
  41352. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41353. light.transferToEffect(effect, lightIndex + "");
  41354. };
  41355. /**
  41356. * Binds the lights information from the scene to the effect for the given mesh.
  41357. * @param scene The scene the lights belongs to
  41358. * @param mesh The mesh we are binding the information to render
  41359. * @param effect The effect we are binding the data to
  41360. * @param defines The generated defines for the effect
  41361. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41362. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41363. */
  41364. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41365. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41366. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41367. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41368. for (var i = 0; i < len; i++) {
  41369. var light = mesh._lightSources[i];
  41370. var iAsString = i.toString();
  41371. var scaledIntensity = light.getScaledIntensity();
  41372. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41373. MaterialHelper.BindLightProperties(light, effect, i);
  41374. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41375. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41376. if (defines["SPECULARTERM"]) {
  41377. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41378. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41379. }
  41380. // Shadows
  41381. if (scene.shadowsEnabled) {
  41382. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41383. }
  41384. light._uniformBuffer.update();
  41385. }
  41386. };
  41387. /**
  41388. * Binds the fog information from the scene to the effect for the given mesh.
  41389. * @param scene The scene the lights belongs to
  41390. * @param mesh The mesh we are binding the information to render
  41391. * @param effect The effect we are binding the data to
  41392. */
  41393. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41394. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41395. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41396. effect.setColor3("vFogColor", scene.fogColor);
  41397. }
  41398. };
  41399. /**
  41400. * Binds the bones information from the mesh to the effect.
  41401. * @param mesh The mesh we are binding the information to render
  41402. * @param effect The effect we are binding the data to
  41403. */
  41404. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41405. if (!effect || !mesh) {
  41406. return;
  41407. }
  41408. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41409. mesh.computeBonesUsingShaders = false;
  41410. }
  41411. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41412. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41413. if (matrices) {
  41414. effect.setMatrices("mBones", matrices);
  41415. }
  41416. }
  41417. };
  41418. /**
  41419. * Binds the morph targets information from the mesh to the effect.
  41420. * @param abstractMesh The mesh we are binding the information to render
  41421. * @param effect The effect we are binding the data to
  41422. */
  41423. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41424. var manager = abstractMesh.morphTargetManager;
  41425. if (!abstractMesh || !manager) {
  41426. return;
  41427. }
  41428. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41429. };
  41430. /**
  41431. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41432. * @param defines The generated defines used in the effect
  41433. * @param effect The effect we are binding the data to
  41434. * @param scene The scene we are willing to render with logarithmic scale for
  41435. */
  41436. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41437. if (defines["LOGARITHMICDEPTH"]) {
  41438. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41439. }
  41440. };
  41441. /**
  41442. * Binds the clip plane information from the scene to the effect.
  41443. * @param scene The scene the clip plane information are extracted from
  41444. * @param effect The effect we are binding the data to
  41445. */
  41446. MaterialHelper.BindClipPlane = function (effect, scene) {
  41447. if (scene.clipPlane) {
  41448. var clipPlane = scene.clipPlane;
  41449. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41450. }
  41451. if (scene.clipPlane2) {
  41452. var clipPlane = scene.clipPlane2;
  41453. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41454. }
  41455. if (scene.clipPlane3) {
  41456. var clipPlane = scene.clipPlane3;
  41457. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41458. }
  41459. if (scene.clipPlane4) {
  41460. var clipPlane = scene.clipPlane4;
  41461. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41462. }
  41463. };
  41464. return MaterialHelper;
  41465. }());
  41466. BABYLON.MaterialHelper = MaterialHelper;
  41467. })(BABYLON || (BABYLON = {}));
  41468. //# sourceMappingURL=babylon.materialHelper.js.map
  41469. var BABYLON;
  41470. (function (BABYLON) {
  41471. var PushMaterial = /** @class */ (function (_super) {
  41472. __extends(PushMaterial, _super);
  41473. function PushMaterial(name, scene) {
  41474. var _this = _super.call(this, name, scene) || this;
  41475. _this._normalMatrix = new BABYLON.Matrix();
  41476. _this.storeEffectOnSubMeshes = true;
  41477. return _this;
  41478. }
  41479. PushMaterial.prototype.getEffect = function () {
  41480. return this._activeEffect;
  41481. };
  41482. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41483. if (!mesh) {
  41484. return false;
  41485. }
  41486. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41487. return true;
  41488. }
  41489. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41490. };
  41491. /**
  41492. * Binds the given world matrix to the active effect
  41493. *
  41494. * @param world the matrix to bind
  41495. */
  41496. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41497. this._activeEffect.setMatrix("world", world);
  41498. };
  41499. /**
  41500. * Binds the given normal matrix to the active effect
  41501. *
  41502. * @param normalMatrix the matrix to bind
  41503. */
  41504. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41505. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41506. };
  41507. PushMaterial.prototype.bind = function (world, mesh) {
  41508. if (!mesh) {
  41509. return;
  41510. }
  41511. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41512. };
  41513. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41514. if (effect === void 0) { effect = null; }
  41515. _super.prototype._afterBind.call(this, mesh);
  41516. this.getScene()._cachedEffect = effect;
  41517. };
  41518. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41519. if (visibility === void 0) { visibility = 1; }
  41520. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41521. };
  41522. return PushMaterial;
  41523. }(BABYLON.Material));
  41524. BABYLON.PushMaterial = PushMaterial;
  41525. })(BABYLON || (BABYLON = {}));
  41526. //# sourceMappingURL=babylon.pushMaterial.js.map
  41527. var BABYLON;
  41528. (function (BABYLON) {
  41529. /** @hidden */
  41530. var StandardMaterialDefines = /** @class */ (function (_super) {
  41531. __extends(StandardMaterialDefines, _super);
  41532. function StandardMaterialDefines() {
  41533. var _this = _super.call(this) || this;
  41534. _this.MAINUV1 = false;
  41535. _this.MAINUV2 = false;
  41536. _this.DIFFUSE = false;
  41537. _this.DIFFUSEDIRECTUV = 0;
  41538. _this.AMBIENT = false;
  41539. _this.AMBIENTDIRECTUV = 0;
  41540. _this.OPACITY = false;
  41541. _this.OPACITYDIRECTUV = 0;
  41542. _this.OPACITYRGB = false;
  41543. _this.REFLECTION = false;
  41544. _this.EMISSIVE = false;
  41545. _this.EMISSIVEDIRECTUV = 0;
  41546. _this.SPECULAR = false;
  41547. _this.SPECULARDIRECTUV = 0;
  41548. _this.BUMP = false;
  41549. _this.BUMPDIRECTUV = 0;
  41550. _this.PARALLAX = false;
  41551. _this.PARALLAXOCCLUSION = false;
  41552. _this.SPECULAROVERALPHA = false;
  41553. _this.CLIPPLANE = false;
  41554. _this.CLIPPLANE2 = false;
  41555. _this.CLIPPLANE3 = false;
  41556. _this.CLIPPLANE4 = false;
  41557. _this.ALPHATEST = false;
  41558. _this.DEPTHPREPASS = false;
  41559. _this.ALPHAFROMDIFFUSE = false;
  41560. _this.POINTSIZE = false;
  41561. _this.FOG = false;
  41562. _this.SPECULARTERM = false;
  41563. _this.DIFFUSEFRESNEL = false;
  41564. _this.OPACITYFRESNEL = false;
  41565. _this.REFLECTIONFRESNEL = false;
  41566. _this.REFRACTIONFRESNEL = false;
  41567. _this.EMISSIVEFRESNEL = false;
  41568. _this.FRESNEL = false;
  41569. _this.NORMAL = false;
  41570. _this.UV1 = false;
  41571. _this.UV2 = false;
  41572. _this.VERTEXCOLOR = false;
  41573. _this.VERTEXALPHA = false;
  41574. _this.NUM_BONE_INFLUENCERS = 0;
  41575. _this.BonesPerMesh = 0;
  41576. _this.INSTANCES = false;
  41577. _this.GLOSSINESS = false;
  41578. _this.ROUGHNESS = false;
  41579. _this.EMISSIVEASILLUMINATION = false;
  41580. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41581. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41582. _this.LIGHTMAP = false;
  41583. _this.LIGHTMAPDIRECTUV = 0;
  41584. _this.OBJECTSPACE_NORMALMAP = false;
  41585. _this.USELIGHTMAPASSHADOWMAP = false;
  41586. _this.REFLECTIONMAP_3D = false;
  41587. _this.REFLECTIONMAP_SPHERICAL = false;
  41588. _this.REFLECTIONMAP_PLANAR = false;
  41589. _this.REFLECTIONMAP_CUBIC = false;
  41590. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41591. _this.REFLECTIONMAP_PROJECTION = false;
  41592. _this.REFLECTIONMAP_SKYBOX = false;
  41593. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41594. _this.REFLECTIONMAP_EXPLICIT = false;
  41595. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41596. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41597. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41598. _this.INVERTCUBICMAP = false;
  41599. _this.LOGARITHMICDEPTH = false;
  41600. _this.REFRACTION = false;
  41601. _this.REFRACTIONMAP_3D = false;
  41602. _this.REFLECTIONOVERALPHA = false;
  41603. _this.TWOSIDEDLIGHTING = false;
  41604. _this.SHADOWFLOAT = false;
  41605. _this.MORPHTARGETS = false;
  41606. _this.MORPHTARGETS_NORMAL = false;
  41607. _this.MORPHTARGETS_TANGENT = false;
  41608. _this.NUM_MORPH_INFLUENCERS = 0;
  41609. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41610. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41611. _this.IMAGEPROCESSING = false;
  41612. _this.VIGNETTE = false;
  41613. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41614. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41615. _this.TONEMAPPING = false;
  41616. _this.TONEMAPPING_ACES = false;
  41617. _this.CONTRAST = false;
  41618. _this.COLORCURVES = false;
  41619. _this.COLORGRADING = false;
  41620. _this.COLORGRADING3D = false;
  41621. _this.SAMPLER3DGREENDEPTH = false;
  41622. _this.SAMPLER3DBGRMAP = false;
  41623. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41624. /**
  41625. * If the reflection texture on this material is in linear color space
  41626. * @hidden
  41627. */
  41628. _this.IS_REFLECTION_LINEAR = false;
  41629. /**
  41630. * If the refraction texture on this material is in linear color space
  41631. * @hidden
  41632. */
  41633. _this.IS_REFRACTION_LINEAR = false;
  41634. _this.EXPOSURE = false;
  41635. _this.rebuild();
  41636. return _this;
  41637. }
  41638. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41639. var modes = [
  41640. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41641. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41642. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41643. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41644. ];
  41645. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41646. var mode = modes_1[_i];
  41647. this[mode] = (mode === modeToEnable);
  41648. }
  41649. };
  41650. return StandardMaterialDefines;
  41651. }(BABYLON.MaterialDefines));
  41652. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41653. var StandardMaterial = /** @class */ (function (_super) {
  41654. __extends(StandardMaterial, _super);
  41655. function StandardMaterial(name, scene) {
  41656. var _this = _super.call(this, name, scene) || this;
  41657. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41658. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41659. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41660. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41661. _this.specularPower = 64;
  41662. _this._useAlphaFromDiffuseTexture = false;
  41663. _this._useEmissiveAsIllumination = false;
  41664. _this._linkEmissiveWithDiffuse = false;
  41665. _this._useSpecularOverAlpha = false;
  41666. _this._useReflectionOverAlpha = false;
  41667. _this._disableLighting = false;
  41668. _this._useObjectSpaceNormalMap = false;
  41669. _this._useParallax = false;
  41670. _this._useParallaxOcclusion = false;
  41671. _this.parallaxScaleBias = 0.05;
  41672. _this._roughness = 0;
  41673. _this.indexOfRefraction = 0.98;
  41674. _this.invertRefractionY = true;
  41675. /**
  41676. * Defines the alpha limits in alpha test mode
  41677. */
  41678. _this.alphaCutOff = 0.4;
  41679. _this._useLightmapAsShadowmap = false;
  41680. _this._useReflectionFresnelFromSpecular = false;
  41681. _this._useGlossinessFromSpecularMapAlpha = false;
  41682. _this._maxSimultaneousLights = 4;
  41683. /**
  41684. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41685. */
  41686. _this._invertNormalMapX = false;
  41687. /**
  41688. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41689. */
  41690. _this._invertNormalMapY = false;
  41691. /**
  41692. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41693. */
  41694. _this._twoSidedLighting = false;
  41695. _this._renderTargets = new BABYLON.SmartArray(16);
  41696. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41697. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41698. // Setup the default processing configuration to the scene.
  41699. _this._attachImageProcessingConfiguration(null);
  41700. _this.getRenderTargetTextures = function () {
  41701. _this._renderTargets.reset();
  41702. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41703. _this._renderTargets.push(_this._reflectionTexture);
  41704. }
  41705. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41706. _this._renderTargets.push(_this._refractionTexture);
  41707. }
  41708. return _this._renderTargets;
  41709. };
  41710. return _this;
  41711. }
  41712. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41713. /**
  41714. * Gets the image processing configuration used either in this material.
  41715. */
  41716. get: function () {
  41717. return this._imageProcessingConfiguration;
  41718. },
  41719. /**
  41720. * Sets the Default image processing configuration used either in the this material.
  41721. *
  41722. * If sets to null, the scene one is in use.
  41723. */
  41724. set: function (value) {
  41725. this._attachImageProcessingConfiguration(value);
  41726. // Ensure the effect will be rebuilt.
  41727. this._markAllSubMeshesAsTexturesDirty();
  41728. },
  41729. enumerable: true,
  41730. configurable: true
  41731. });
  41732. /**
  41733. * Attaches a new image processing configuration to the Standard Material.
  41734. * @param configuration
  41735. */
  41736. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41737. var _this = this;
  41738. if (configuration === this._imageProcessingConfiguration) {
  41739. return;
  41740. }
  41741. // Detaches observer.
  41742. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41743. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41744. }
  41745. // Pick the scene configuration if needed.
  41746. if (!configuration) {
  41747. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41748. }
  41749. else {
  41750. this._imageProcessingConfiguration = configuration;
  41751. }
  41752. // Attaches observer.
  41753. if (this._imageProcessingConfiguration) {
  41754. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41755. _this._markAllSubMeshesAsImageProcessingDirty();
  41756. });
  41757. }
  41758. };
  41759. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41760. /**
  41761. * Gets wether the color curves effect is enabled.
  41762. */
  41763. get: function () {
  41764. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41765. },
  41766. /**
  41767. * Sets wether the color curves effect is enabled.
  41768. */
  41769. set: function (value) {
  41770. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41771. },
  41772. enumerable: true,
  41773. configurable: true
  41774. });
  41775. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41776. /**
  41777. * Gets wether the color grading effect is enabled.
  41778. */
  41779. get: function () {
  41780. return this.imageProcessingConfiguration.colorGradingEnabled;
  41781. },
  41782. /**
  41783. * Gets wether the color grading effect is enabled.
  41784. */
  41785. set: function (value) {
  41786. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41787. },
  41788. enumerable: true,
  41789. configurable: true
  41790. });
  41791. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41792. /**
  41793. * Gets wether tonemapping is enabled or not.
  41794. */
  41795. get: function () {
  41796. return this._imageProcessingConfiguration.toneMappingEnabled;
  41797. },
  41798. /**
  41799. * Sets wether tonemapping is enabled or not
  41800. */
  41801. set: function (value) {
  41802. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41803. },
  41804. enumerable: true,
  41805. configurable: true
  41806. });
  41807. ;
  41808. ;
  41809. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41810. /**
  41811. * The camera exposure used on this material.
  41812. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41813. * This corresponds to a photographic exposure.
  41814. */
  41815. get: function () {
  41816. return this._imageProcessingConfiguration.exposure;
  41817. },
  41818. /**
  41819. * The camera exposure used on this material.
  41820. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41821. * This corresponds to a photographic exposure.
  41822. */
  41823. set: function (value) {
  41824. this._imageProcessingConfiguration.exposure = value;
  41825. },
  41826. enumerable: true,
  41827. configurable: true
  41828. });
  41829. ;
  41830. ;
  41831. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41832. /**
  41833. * Gets The camera contrast used on this material.
  41834. */
  41835. get: function () {
  41836. return this._imageProcessingConfiguration.contrast;
  41837. },
  41838. /**
  41839. * Sets The camera contrast used on this material.
  41840. */
  41841. set: function (value) {
  41842. this._imageProcessingConfiguration.contrast = value;
  41843. },
  41844. enumerable: true,
  41845. configurable: true
  41846. });
  41847. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41848. /**
  41849. * Gets the Color Grading 2D Lookup Texture.
  41850. */
  41851. get: function () {
  41852. return this._imageProcessingConfiguration.colorGradingTexture;
  41853. },
  41854. /**
  41855. * Sets the Color Grading 2D Lookup Texture.
  41856. */
  41857. set: function (value) {
  41858. this._imageProcessingConfiguration.colorGradingTexture = value;
  41859. },
  41860. enumerable: true,
  41861. configurable: true
  41862. });
  41863. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41864. /**
  41865. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41866. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41867. * 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;
  41868. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41869. */
  41870. get: function () {
  41871. return this._imageProcessingConfiguration.colorCurves;
  41872. },
  41873. /**
  41874. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41875. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41876. * 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;
  41877. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41878. */
  41879. set: function (value) {
  41880. this._imageProcessingConfiguration.colorCurves = value;
  41881. },
  41882. enumerable: true,
  41883. configurable: true
  41884. });
  41885. StandardMaterial.prototype.getClassName = function () {
  41886. return "StandardMaterial";
  41887. };
  41888. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41889. get: function () {
  41890. return this._useLogarithmicDepth;
  41891. },
  41892. set: function (value) {
  41893. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41894. this._markAllSubMeshesAsMiscDirty();
  41895. },
  41896. enumerable: true,
  41897. configurable: true
  41898. });
  41899. StandardMaterial.prototype.needAlphaBlending = function () {
  41900. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41901. };
  41902. StandardMaterial.prototype.needAlphaTesting = function () {
  41903. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41904. };
  41905. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41906. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41907. };
  41908. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41909. return this._diffuseTexture;
  41910. };
  41911. /**
  41912. * Child classes can use it to update shaders
  41913. */
  41914. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41915. if (useInstances === void 0) { useInstances = false; }
  41916. if (subMesh.effect && this.isFrozen) {
  41917. if (this._wasPreviouslyReady) {
  41918. return true;
  41919. }
  41920. }
  41921. if (!subMesh._materialDefines) {
  41922. subMesh._materialDefines = new StandardMaterialDefines();
  41923. }
  41924. var scene = this.getScene();
  41925. var defines = subMesh._materialDefines;
  41926. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41927. if (defines._renderId === scene.getRenderId()) {
  41928. return true;
  41929. }
  41930. }
  41931. var engine = scene.getEngine();
  41932. // Lights
  41933. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41934. // Textures
  41935. if (defines._areTexturesDirty) {
  41936. defines._needUVs = false;
  41937. defines.MAINUV1 = false;
  41938. defines.MAINUV2 = false;
  41939. if (scene.texturesEnabled) {
  41940. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41941. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41942. return false;
  41943. }
  41944. else {
  41945. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41946. }
  41947. }
  41948. else {
  41949. defines.DIFFUSE = false;
  41950. }
  41951. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41952. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41953. return false;
  41954. }
  41955. else {
  41956. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41957. }
  41958. }
  41959. else {
  41960. defines.AMBIENT = false;
  41961. }
  41962. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41963. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41964. return false;
  41965. }
  41966. else {
  41967. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41968. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41969. }
  41970. }
  41971. else {
  41972. defines.OPACITY = false;
  41973. }
  41974. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41975. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41976. return false;
  41977. }
  41978. else {
  41979. defines._needNormals = true;
  41980. defines.REFLECTION = true;
  41981. defines.ROUGHNESS = (this._roughness > 0);
  41982. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41983. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41984. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41985. switch (this._reflectionTexture.coordinatesMode) {
  41986. case BABYLON.Texture.EXPLICIT_MODE:
  41987. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41988. break;
  41989. case BABYLON.Texture.PLANAR_MODE:
  41990. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41991. break;
  41992. case BABYLON.Texture.PROJECTION_MODE:
  41993. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41994. break;
  41995. case BABYLON.Texture.SKYBOX_MODE:
  41996. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41997. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  41998. break;
  41999. case BABYLON.Texture.SPHERICAL_MODE:
  42000. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42001. break;
  42002. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42003. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42004. break;
  42005. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42006. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42007. break;
  42008. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42009. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42010. break;
  42011. case BABYLON.Texture.CUBIC_MODE:
  42012. case BABYLON.Texture.INVCUBIC_MODE:
  42013. default:
  42014. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42015. break;
  42016. }
  42017. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42018. }
  42019. }
  42020. else {
  42021. defines.REFLECTION = false;
  42022. }
  42023. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42024. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42025. return false;
  42026. }
  42027. else {
  42028. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42029. }
  42030. }
  42031. else {
  42032. defines.EMISSIVE = false;
  42033. }
  42034. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42035. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42036. return false;
  42037. }
  42038. else {
  42039. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42040. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42041. }
  42042. }
  42043. else {
  42044. defines.LIGHTMAP = false;
  42045. }
  42046. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42047. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42048. return false;
  42049. }
  42050. else {
  42051. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42052. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42053. }
  42054. }
  42055. else {
  42056. defines.SPECULAR = false;
  42057. }
  42058. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42059. // Bump texure can not be not blocking.
  42060. if (!this._bumpTexture.isReady()) {
  42061. return false;
  42062. }
  42063. else {
  42064. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42065. defines.PARALLAX = this._useParallax;
  42066. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42067. }
  42068. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42069. }
  42070. else {
  42071. defines.BUMP = false;
  42072. }
  42073. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42074. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42075. return false;
  42076. }
  42077. else {
  42078. defines._needUVs = true;
  42079. defines.REFRACTION = true;
  42080. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42081. }
  42082. }
  42083. else {
  42084. defines.REFRACTION = false;
  42085. }
  42086. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42087. }
  42088. else {
  42089. defines.DIFFUSE = false;
  42090. defines.AMBIENT = false;
  42091. defines.OPACITY = false;
  42092. defines.REFLECTION = false;
  42093. defines.EMISSIVE = false;
  42094. defines.LIGHTMAP = false;
  42095. defines.BUMP = false;
  42096. defines.REFRACTION = false;
  42097. }
  42098. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42099. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42100. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42101. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42102. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42103. }
  42104. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42105. if (!this._imageProcessingConfiguration.isReady()) {
  42106. return false;
  42107. }
  42108. this._imageProcessingConfiguration.prepareDefines(defines);
  42109. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42110. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42111. }
  42112. if (defines._areFresnelDirty) {
  42113. if (StandardMaterial.FresnelEnabled) {
  42114. // Fresnel
  42115. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42116. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42117. this._reflectionFresnelParameters) {
  42118. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42119. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42120. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42121. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42122. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42123. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42124. defines._needNormals = true;
  42125. defines.FRESNEL = true;
  42126. }
  42127. }
  42128. else {
  42129. defines.FRESNEL = false;
  42130. }
  42131. }
  42132. // Misc.
  42133. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42134. // Attribs
  42135. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42136. // Values that need to be evaluated on every frame
  42137. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42138. // Get correct effect
  42139. if (defines.isDirty) {
  42140. defines.markAsProcessed();
  42141. scene.resetCachedMaterial();
  42142. // Fallbacks
  42143. var fallbacks = new BABYLON.EffectFallbacks();
  42144. if (defines.REFLECTION) {
  42145. fallbacks.addFallback(0, "REFLECTION");
  42146. }
  42147. if (defines.SPECULAR) {
  42148. fallbacks.addFallback(0, "SPECULAR");
  42149. }
  42150. if (defines.BUMP) {
  42151. fallbacks.addFallback(0, "BUMP");
  42152. }
  42153. if (defines.PARALLAX) {
  42154. fallbacks.addFallback(1, "PARALLAX");
  42155. }
  42156. if (defines.PARALLAXOCCLUSION) {
  42157. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42158. }
  42159. if (defines.SPECULAROVERALPHA) {
  42160. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42161. }
  42162. if (defines.FOG) {
  42163. fallbacks.addFallback(1, "FOG");
  42164. }
  42165. if (defines.POINTSIZE) {
  42166. fallbacks.addFallback(0, "POINTSIZE");
  42167. }
  42168. if (defines.LOGARITHMICDEPTH) {
  42169. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42170. }
  42171. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42172. if (defines.SPECULARTERM) {
  42173. fallbacks.addFallback(0, "SPECULARTERM");
  42174. }
  42175. if (defines.DIFFUSEFRESNEL) {
  42176. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42177. }
  42178. if (defines.OPACITYFRESNEL) {
  42179. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42180. }
  42181. if (defines.REFLECTIONFRESNEL) {
  42182. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42183. }
  42184. if (defines.EMISSIVEFRESNEL) {
  42185. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42186. }
  42187. if (defines.FRESNEL) {
  42188. fallbacks.addFallback(4, "FRESNEL");
  42189. }
  42190. //Attributes
  42191. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42192. if (defines.NORMAL) {
  42193. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42194. }
  42195. if (defines.UV1) {
  42196. attribs.push(BABYLON.VertexBuffer.UVKind);
  42197. }
  42198. if (defines.UV2) {
  42199. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42200. }
  42201. if (defines.VERTEXCOLOR) {
  42202. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42203. }
  42204. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42205. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42206. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42207. var shaderName = "default";
  42208. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42209. "vFogInfos", "vFogColor", "pointSize",
  42210. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42211. "mBones",
  42212. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42213. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42214. "vReflectionPosition", "vReflectionSize",
  42215. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42216. ];
  42217. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42218. var uniformBuffers = ["Material", "Scene"];
  42219. if (BABYLON.ImageProcessingConfiguration) {
  42220. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42221. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42222. }
  42223. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42224. uniformsNames: uniforms,
  42225. uniformBuffersNames: uniformBuffers,
  42226. samplers: samplers,
  42227. defines: defines,
  42228. maxSimultaneousLights: this._maxSimultaneousLights
  42229. });
  42230. if (this.customShaderNameResolve) {
  42231. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42232. }
  42233. var join = defines.toString();
  42234. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42235. attributes: attribs,
  42236. uniformsNames: uniforms,
  42237. uniformBuffersNames: uniformBuffers,
  42238. samplers: samplers,
  42239. defines: join,
  42240. fallbacks: fallbacks,
  42241. onCompiled: this.onCompiled,
  42242. onError: this.onError,
  42243. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42244. }, engine), defines);
  42245. this.buildUniformLayout();
  42246. }
  42247. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42248. return false;
  42249. }
  42250. defines._renderId = scene.getRenderId();
  42251. this._wasPreviouslyReady = true;
  42252. return true;
  42253. };
  42254. StandardMaterial.prototype.buildUniformLayout = function () {
  42255. // Order is important !
  42256. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42257. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42258. this._uniformBuffer.addUniform("opacityParts", 4);
  42259. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42260. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42261. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42262. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42263. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42264. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42265. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42266. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42267. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42268. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42269. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42270. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42271. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42272. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42273. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42274. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42275. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42276. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42277. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42278. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42279. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42280. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42281. this._uniformBuffer.addUniform("specularMatrix", 16);
  42282. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42283. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42284. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42285. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42286. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42287. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42288. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42289. this._uniformBuffer.addUniform("pointSize", 1);
  42290. this._uniformBuffer.create();
  42291. };
  42292. StandardMaterial.prototype.unbind = function () {
  42293. if (this._activeEffect) {
  42294. var needFlag = false;
  42295. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42296. this._activeEffect.setTexture("reflection2DSampler", null);
  42297. needFlag = true;
  42298. }
  42299. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42300. this._activeEffect.setTexture("refraction2DSampler", null);
  42301. needFlag = true;
  42302. }
  42303. if (needFlag) {
  42304. this._markAllSubMeshesAsTexturesDirty();
  42305. }
  42306. }
  42307. _super.prototype.unbind.call(this);
  42308. };
  42309. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42310. var scene = this.getScene();
  42311. var defines = subMesh._materialDefines;
  42312. if (!defines) {
  42313. return;
  42314. }
  42315. var effect = subMesh.effect;
  42316. if (!effect) {
  42317. return;
  42318. }
  42319. this._activeEffect = effect;
  42320. // Matrices
  42321. this.bindOnlyWorldMatrix(world);
  42322. // Normal Matrix
  42323. if (defines.OBJECTSPACE_NORMALMAP) {
  42324. world.toNormalMatrix(this._normalMatrix);
  42325. this.bindOnlyNormalMatrix(this._normalMatrix);
  42326. }
  42327. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42328. // Bones
  42329. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42330. if (mustRebind) {
  42331. this._uniformBuffer.bindToEffect(effect, "Material");
  42332. this.bindViewProjection(effect);
  42333. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42334. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42335. // Fresnel
  42336. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42337. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42338. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42339. }
  42340. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42341. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42342. }
  42343. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42344. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42345. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42346. }
  42347. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42348. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42349. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42350. }
  42351. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42352. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42353. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42354. }
  42355. }
  42356. // Textures
  42357. if (scene.texturesEnabled) {
  42358. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42359. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42360. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42361. if (this._diffuseTexture.hasAlpha) {
  42362. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42363. }
  42364. }
  42365. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42366. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42367. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42368. }
  42369. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42370. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42371. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42372. }
  42373. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42374. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42375. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42376. if (this._reflectionTexture.boundingBoxSize) {
  42377. var cubeTexture = this._reflectionTexture;
  42378. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42379. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42380. }
  42381. }
  42382. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42383. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42384. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42385. }
  42386. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42387. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42388. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42389. }
  42390. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42391. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42392. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42393. }
  42394. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42395. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42396. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42397. if (scene._mirroredCameraPosition) {
  42398. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42399. }
  42400. else {
  42401. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42402. }
  42403. }
  42404. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42405. var depth = 1.0;
  42406. if (!this._refractionTexture.isCube) {
  42407. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42408. if (this._refractionTexture.depth) {
  42409. depth = this._refractionTexture.depth;
  42410. }
  42411. }
  42412. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42413. }
  42414. }
  42415. // Point size
  42416. if (this.pointsCloud) {
  42417. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42418. }
  42419. if (defines.SPECULARTERM) {
  42420. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42421. }
  42422. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42423. // Diffuse
  42424. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42425. }
  42426. // Textures
  42427. if (scene.texturesEnabled) {
  42428. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42429. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42430. }
  42431. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42432. effect.setTexture("ambientSampler", this._ambientTexture);
  42433. }
  42434. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42435. effect.setTexture("opacitySampler", this._opacityTexture);
  42436. }
  42437. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42438. if (this._reflectionTexture.isCube) {
  42439. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42440. }
  42441. else {
  42442. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42443. }
  42444. }
  42445. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42446. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42447. }
  42448. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42449. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42450. }
  42451. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42452. effect.setTexture("specularSampler", this._specularTexture);
  42453. }
  42454. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42455. effect.setTexture("bumpSampler", this._bumpTexture);
  42456. }
  42457. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42458. var depth = 1.0;
  42459. if (this._refractionTexture.isCube) {
  42460. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42461. }
  42462. else {
  42463. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42464. }
  42465. }
  42466. }
  42467. // Clip plane
  42468. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42469. // Colors
  42470. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42471. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42472. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42473. }
  42474. if (mustRebind || !this.isFrozen) {
  42475. // Lights
  42476. if (scene.lightsEnabled && !this._disableLighting) {
  42477. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42478. }
  42479. // View
  42480. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42481. this.bindView(effect);
  42482. }
  42483. // Fog
  42484. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42485. // Morph targets
  42486. if (defines.NUM_MORPH_INFLUENCERS) {
  42487. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42488. }
  42489. // Log. depth
  42490. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42491. // image processing
  42492. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42493. this._imageProcessingConfiguration.bind(this._activeEffect);
  42494. }
  42495. }
  42496. this._uniformBuffer.update();
  42497. this._afterBind(mesh, this._activeEffect);
  42498. };
  42499. StandardMaterial.prototype.getAnimatables = function () {
  42500. var results = [];
  42501. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42502. results.push(this._diffuseTexture);
  42503. }
  42504. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42505. results.push(this._ambientTexture);
  42506. }
  42507. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42508. results.push(this._opacityTexture);
  42509. }
  42510. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42511. results.push(this._reflectionTexture);
  42512. }
  42513. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42514. results.push(this._emissiveTexture);
  42515. }
  42516. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42517. results.push(this._specularTexture);
  42518. }
  42519. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42520. results.push(this._bumpTexture);
  42521. }
  42522. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42523. results.push(this._lightmapTexture);
  42524. }
  42525. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42526. results.push(this._refractionTexture);
  42527. }
  42528. return results;
  42529. };
  42530. StandardMaterial.prototype.getActiveTextures = function () {
  42531. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42532. if (this._diffuseTexture) {
  42533. activeTextures.push(this._diffuseTexture);
  42534. }
  42535. if (this._ambientTexture) {
  42536. activeTextures.push(this._ambientTexture);
  42537. }
  42538. if (this._opacityTexture) {
  42539. activeTextures.push(this._opacityTexture);
  42540. }
  42541. if (this._reflectionTexture) {
  42542. activeTextures.push(this._reflectionTexture);
  42543. }
  42544. if (this._emissiveTexture) {
  42545. activeTextures.push(this._emissiveTexture);
  42546. }
  42547. if (this._specularTexture) {
  42548. activeTextures.push(this._specularTexture);
  42549. }
  42550. if (this._bumpTexture) {
  42551. activeTextures.push(this._bumpTexture);
  42552. }
  42553. if (this._lightmapTexture) {
  42554. activeTextures.push(this._lightmapTexture);
  42555. }
  42556. if (this._refractionTexture) {
  42557. activeTextures.push(this._refractionTexture);
  42558. }
  42559. return activeTextures;
  42560. };
  42561. StandardMaterial.prototype.hasTexture = function (texture) {
  42562. if (_super.prototype.hasTexture.call(this, texture)) {
  42563. return true;
  42564. }
  42565. if (this._diffuseTexture === texture) {
  42566. return true;
  42567. }
  42568. if (this._ambientTexture === texture) {
  42569. return true;
  42570. }
  42571. if (this._opacityTexture === texture) {
  42572. return true;
  42573. }
  42574. if (this._reflectionTexture === texture) {
  42575. return true;
  42576. }
  42577. if (this._emissiveTexture === texture) {
  42578. return true;
  42579. }
  42580. if (this._specularTexture === texture) {
  42581. return true;
  42582. }
  42583. if (this._bumpTexture === texture) {
  42584. return true;
  42585. }
  42586. if (this._lightmapTexture === texture) {
  42587. return true;
  42588. }
  42589. if (this._refractionTexture === texture) {
  42590. return true;
  42591. }
  42592. return false;
  42593. };
  42594. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42595. if (forceDisposeTextures) {
  42596. if (this._diffuseTexture) {
  42597. this._diffuseTexture.dispose();
  42598. }
  42599. if (this._ambientTexture) {
  42600. this._ambientTexture.dispose();
  42601. }
  42602. if (this._opacityTexture) {
  42603. this._opacityTexture.dispose();
  42604. }
  42605. if (this._reflectionTexture) {
  42606. this._reflectionTexture.dispose();
  42607. }
  42608. if (this._emissiveTexture) {
  42609. this._emissiveTexture.dispose();
  42610. }
  42611. if (this._specularTexture) {
  42612. this._specularTexture.dispose();
  42613. }
  42614. if (this._bumpTexture) {
  42615. this._bumpTexture.dispose();
  42616. }
  42617. if (this._lightmapTexture) {
  42618. this._lightmapTexture.dispose();
  42619. }
  42620. if (this._refractionTexture) {
  42621. this._refractionTexture.dispose();
  42622. }
  42623. }
  42624. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42625. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42626. }
  42627. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42628. };
  42629. StandardMaterial.prototype.clone = function (name) {
  42630. var _this = this;
  42631. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42632. result.name = name;
  42633. result.id = name;
  42634. return result;
  42635. };
  42636. StandardMaterial.prototype.serialize = function () {
  42637. return BABYLON.SerializationHelper.Serialize(this);
  42638. };
  42639. // Statics
  42640. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42641. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42642. };
  42643. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42644. get: function () {
  42645. return StandardMaterial._DiffuseTextureEnabled;
  42646. },
  42647. set: function (value) {
  42648. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42649. return;
  42650. }
  42651. StandardMaterial._DiffuseTextureEnabled = value;
  42652. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42653. },
  42654. enumerable: true,
  42655. configurable: true
  42656. });
  42657. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42658. get: function () {
  42659. return StandardMaterial._AmbientTextureEnabled;
  42660. },
  42661. set: function (value) {
  42662. if (StandardMaterial._AmbientTextureEnabled === value) {
  42663. return;
  42664. }
  42665. StandardMaterial._AmbientTextureEnabled = value;
  42666. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42667. },
  42668. enumerable: true,
  42669. configurable: true
  42670. });
  42671. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42672. get: function () {
  42673. return StandardMaterial._OpacityTextureEnabled;
  42674. },
  42675. set: function (value) {
  42676. if (StandardMaterial._OpacityTextureEnabled === value) {
  42677. return;
  42678. }
  42679. StandardMaterial._OpacityTextureEnabled = value;
  42680. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42681. },
  42682. enumerable: true,
  42683. configurable: true
  42684. });
  42685. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42686. get: function () {
  42687. return StandardMaterial._ReflectionTextureEnabled;
  42688. },
  42689. set: function (value) {
  42690. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42691. return;
  42692. }
  42693. StandardMaterial._ReflectionTextureEnabled = value;
  42694. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42695. },
  42696. enumerable: true,
  42697. configurable: true
  42698. });
  42699. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42700. get: function () {
  42701. return StandardMaterial._EmissiveTextureEnabled;
  42702. },
  42703. set: function (value) {
  42704. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42705. return;
  42706. }
  42707. StandardMaterial._EmissiveTextureEnabled = value;
  42708. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42709. },
  42710. enumerable: true,
  42711. configurable: true
  42712. });
  42713. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42714. get: function () {
  42715. return StandardMaterial._SpecularTextureEnabled;
  42716. },
  42717. set: function (value) {
  42718. if (StandardMaterial._SpecularTextureEnabled === value) {
  42719. return;
  42720. }
  42721. StandardMaterial._SpecularTextureEnabled = value;
  42722. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42723. },
  42724. enumerable: true,
  42725. configurable: true
  42726. });
  42727. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42728. get: function () {
  42729. return StandardMaterial._BumpTextureEnabled;
  42730. },
  42731. set: function (value) {
  42732. if (StandardMaterial._BumpTextureEnabled === value) {
  42733. return;
  42734. }
  42735. StandardMaterial._BumpTextureEnabled = value;
  42736. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42737. },
  42738. enumerable: true,
  42739. configurable: true
  42740. });
  42741. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42742. get: function () {
  42743. return StandardMaterial._LightmapTextureEnabled;
  42744. },
  42745. set: function (value) {
  42746. if (StandardMaterial._LightmapTextureEnabled === value) {
  42747. return;
  42748. }
  42749. StandardMaterial._LightmapTextureEnabled = value;
  42750. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42751. },
  42752. enumerable: true,
  42753. configurable: true
  42754. });
  42755. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42756. get: function () {
  42757. return StandardMaterial._RefractionTextureEnabled;
  42758. },
  42759. set: function (value) {
  42760. if (StandardMaterial._RefractionTextureEnabled === value) {
  42761. return;
  42762. }
  42763. StandardMaterial._RefractionTextureEnabled = value;
  42764. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42765. },
  42766. enumerable: true,
  42767. configurable: true
  42768. });
  42769. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42770. get: function () {
  42771. return StandardMaterial._ColorGradingTextureEnabled;
  42772. },
  42773. set: function (value) {
  42774. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42775. return;
  42776. }
  42777. StandardMaterial._ColorGradingTextureEnabled = value;
  42778. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42779. },
  42780. enumerable: true,
  42781. configurable: true
  42782. });
  42783. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42784. get: function () {
  42785. return StandardMaterial._FresnelEnabled;
  42786. },
  42787. set: function (value) {
  42788. if (StandardMaterial._FresnelEnabled === value) {
  42789. return;
  42790. }
  42791. StandardMaterial._FresnelEnabled = value;
  42792. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42793. },
  42794. enumerable: true,
  42795. configurable: true
  42796. });
  42797. // Flags used to enable or disable a type of texture for all Standard Materials
  42798. StandardMaterial._DiffuseTextureEnabled = true;
  42799. StandardMaterial._AmbientTextureEnabled = true;
  42800. StandardMaterial._OpacityTextureEnabled = true;
  42801. StandardMaterial._ReflectionTextureEnabled = true;
  42802. StandardMaterial._EmissiveTextureEnabled = true;
  42803. StandardMaterial._SpecularTextureEnabled = true;
  42804. StandardMaterial._BumpTextureEnabled = true;
  42805. StandardMaterial._LightmapTextureEnabled = true;
  42806. StandardMaterial._RefractionTextureEnabled = true;
  42807. StandardMaterial._ColorGradingTextureEnabled = true;
  42808. StandardMaterial._FresnelEnabled = true;
  42809. __decorate([
  42810. BABYLON.serializeAsTexture("diffuseTexture")
  42811. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42812. __decorate([
  42813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42814. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42815. __decorate([
  42816. BABYLON.serializeAsTexture("ambientTexture")
  42817. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42818. __decorate([
  42819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42820. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42821. __decorate([
  42822. BABYLON.serializeAsTexture("opacityTexture")
  42823. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42824. __decorate([
  42825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42826. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42827. __decorate([
  42828. BABYLON.serializeAsTexture("reflectionTexture")
  42829. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42830. __decorate([
  42831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42832. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42833. __decorate([
  42834. BABYLON.serializeAsTexture("emissiveTexture")
  42835. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42836. __decorate([
  42837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42838. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42839. __decorate([
  42840. BABYLON.serializeAsTexture("specularTexture")
  42841. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42842. __decorate([
  42843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42844. ], StandardMaterial.prototype, "specularTexture", void 0);
  42845. __decorate([
  42846. BABYLON.serializeAsTexture("bumpTexture")
  42847. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42848. __decorate([
  42849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42850. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42851. __decorate([
  42852. BABYLON.serializeAsTexture("lightmapTexture")
  42853. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42854. __decorate([
  42855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42856. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42857. __decorate([
  42858. BABYLON.serializeAsTexture("refractionTexture")
  42859. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42860. __decorate([
  42861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42862. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42863. __decorate([
  42864. BABYLON.serializeAsColor3("ambient")
  42865. ], StandardMaterial.prototype, "ambientColor", void 0);
  42866. __decorate([
  42867. BABYLON.serializeAsColor3("diffuse")
  42868. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42869. __decorate([
  42870. BABYLON.serializeAsColor3("specular")
  42871. ], StandardMaterial.prototype, "specularColor", void 0);
  42872. __decorate([
  42873. BABYLON.serializeAsColor3("emissive")
  42874. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42875. __decorate([
  42876. BABYLON.serialize()
  42877. ], StandardMaterial.prototype, "specularPower", void 0);
  42878. __decorate([
  42879. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42880. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42881. __decorate([
  42882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42883. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42884. __decorate([
  42885. BABYLON.serialize("useEmissiveAsIllumination")
  42886. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42887. __decorate([
  42888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42889. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42890. __decorate([
  42891. BABYLON.serialize("linkEmissiveWithDiffuse")
  42892. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42893. __decorate([
  42894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42895. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42896. __decorate([
  42897. BABYLON.serialize("useSpecularOverAlpha")
  42898. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42899. __decorate([
  42900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42901. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42902. __decorate([
  42903. BABYLON.serialize("useReflectionOverAlpha")
  42904. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42905. __decorate([
  42906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42907. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42908. __decorate([
  42909. BABYLON.serialize("disableLighting")
  42910. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42911. __decorate([
  42912. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42913. ], StandardMaterial.prototype, "disableLighting", void 0);
  42914. __decorate([
  42915. BABYLON.serialize("useObjectSpaceNormalMap")
  42916. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42917. __decorate([
  42918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42919. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42920. __decorate([
  42921. BABYLON.serialize("useParallax")
  42922. ], StandardMaterial.prototype, "_useParallax", void 0);
  42923. __decorate([
  42924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42925. ], StandardMaterial.prototype, "useParallax", void 0);
  42926. __decorate([
  42927. BABYLON.serialize("useParallaxOcclusion")
  42928. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42929. __decorate([
  42930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42931. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42932. __decorate([
  42933. BABYLON.serialize()
  42934. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42935. __decorate([
  42936. BABYLON.serialize("roughness")
  42937. ], StandardMaterial.prototype, "_roughness", void 0);
  42938. __decorate([
  42939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42940. ], StandardMaterial.prototype, "roughness", void 0);
  42941. __decorate([
  42942. BABYLON.serialize()
  42943. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42944. __decorate([
  42945. BABYLON.serialize()
  42946. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42947. __decorate([
  42948. BABYLON.serialize()
  42949. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42950. __decorate([
  42951. BABYLON.serialize("useLightmapAsShadowmap")
  42952. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42953. __decorate([
  42954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42955. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42956. __decorate([
  42957. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42958. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42959. __decorate([
  42960. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42961. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42962. __decorate([
  42963. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42964. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42965. __decorate([
  42966. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42967. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42968. __decorate([
  42969. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42970. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42971. __decorate([
  42972. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42973. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42974. __decorate([
  42975. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42976. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42977. __decorate([
  42978. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42979. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42980. __decorate([
  42981. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42982. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42983. __decorate([
  42984. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42985. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42986. __decorate([
  42987. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42988. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42989. __decorate([
  42990. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42991. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42992. __decorate([
  42993. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42994. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42995. __decorate([
  42996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42997. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42998. __decorate([
  42999. BABYLON.serialize("maxSimultaneousLights")
  43000. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43001. __decorate([
  43002. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43003. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43004. __decorate([
  43005. BABYLON.serialize("invertNormalMapX")
  43006. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43007. __decorate([
  43008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43009. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43010. __decorate([
  43011. BABYLON.serialize("invertNormalMapY")
  43012. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43013. __decorate([
  43014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43015. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43016. __decorate([
  43017. BABYLON.serialize("twoSidedLighting")
  43018. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43019. __decorate([
  43020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43021. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43022. __decorate([
  43023. BABYLON.serialize()
  43024. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43025. return StandardMaterial;
  43026. }(BABYLON.PushMaterial));
  43027. BABYLON.StandardMaterial = StandardMaterial;
  43028. })(BABYLON || (BABYLON = {}));
  43029. //# sourceMappingURL=babylon.standardMaterial.js.map
  43030. var BABYLON;
  43031. (function (BABYLON) {
  43032. /**
  43033. * Class representing spherical polynomial coefficients to the 3rd degree
  43034. */
  43035. var SphericalPolynomial = /** @class */ (function () {
  43036. function SphericalPolynomial() {
  43037. /**
  43038. * The x coefficients of the spherical polynomial
  43039. */
  43040. this.x = BABYLON.Vector3.Zero();
  43041. /**
  43042. * The y coefficients of the spherical polynomial
  43043. */
  43044. this.y = BABYLON.Vector3.Zero();
  43045. /**
  43046. * The z coefficients of the spherical polynomial
  43047. */
  43048. this.z = BABYLON.Vector3.Zero();
  43049. /**
  43050. * The xx coefficients of the spherical polynomial
  43051. */
  43052. this.xx = BABYLON.Vector3.Zero();
  43053. /**
  43054. * The yy coefficients of the spherical polynomial
  43055. */
  43056. this.yy = BABYLON.Vector3.Zero();
  43057. /**
  43058. * The zz coefficients of the spherical polynomial
  43059. */
  43060. this.zz = BABYLON.Vector3.Zero();
  43061. /**
  43062. * The xy coefficients of the spherical polynomial
  43063. */
  43064. this.xy = BABYLON.Vector3.Zero();
  43065. /**
  43066. * The yz coefficients of the spherical polynomial
  43067. */
  43068. this.yz = BABYLON.Vector3.Zero();
  43069. /**
  43070. * The zx coefficients of the spherical polynomial
  43071. */
  43072. this.zx = BABYLON.Vector3.Zero();
  43073. }
  43074. /**
  43075. * Adds an ambient color to the spherical polynomial
  43076. * @param color the color to add
  43077. */
  43078. SphericalPolynomial.prototype.addAmbient = function (color) {
  43079. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43080. this.xx = this.xx.add(colorVector);
  43081. this.yy = this.yy.add(colorVector);
  43082. this.zz = this.zz.add(colorVector);
  43083. };
  43084. /**
  43085. * Scales the spherical polynomial by the given amount
  43086. * @param scale the amount to scale
  43087. */
  43088. SphericalPolynomial.prototype.scale = function (scale) {
  43089. this.x = this.x.scale(scale);
  43090. this.y = this.y.scale(scale);
  43091. this.z = this.z.scale(scale);
  43092. this.xx = this.xx.scale(scale);
  43093. this.yy = this.yy.scale(scale);
  43094. this.zz = this.zz.scale(scale);
  43095. this.yz = this.yz.scale(scale);
  43096. this.zx = this.zx.scale(scale);
  43097. this.xy = this.xy.scale(scale);
  43098. };
  43099. /**
  43100. * Gets the spherical polynomial from harmonics
  43101. * @param harmonics the spherical harmonics
  43102. * @returns the spherical polynomial
  43103. */
  43104. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43105. var result = new SphericalPolynomial();
  43106. result.x = harmonics.l11.scale(1.02333);
  43107. result.y = harmonics.l1_1.scale(1.02333);
  43108. result.z = harmonics.l10.scale(1.02333);
  43109. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43110. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43111. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43112. result.yz = harmonics.l2_1.scale(0.858086);
  43113. result.zx = harmonics.l21.scale(0.858086);
  43114. result.xy = harmonics.l2_2.scale(0.858086);
  43115. result.scale(1.0 / Math.PI);
  43116. return result;
  43117. };
  43118. /**
  43119. * Constructs a spherical polynomial from an array.
  43120. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43121. * @returns the spherical polynomial
  43122. */
  43123. SphericalPolynomial.FromArray = function (data) {
  43124. var sp = new SphericalPolynomial();
  43125. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43126. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43127. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43128. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43129. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43130. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43131. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43132. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43133. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43134. return sp;
  43135. };
  43136. return SphericalPolynomial;
  43137. }());
  43138. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43139. /**
  43140. * Class representing spherical harmonics coefficients to the 3rd degree
  43141. */
  43142. var SphericalHarmonics = /** @class */ (function () {
  43143. function SphericalHarmonics() {
  43144. /**
  43145. * The l0,0 coefficients of the spherical harmonics
  43146. */
  43147. this.l00 = BABYLON.Vector3.Zero();
  43148. /**
  43149. * The l1,-1 coefficients of the spherical harmonics
  43150. */
  43151. this.l1_1 = BABYLON.Vector3.Zero();
  43152. /**
  43153. * The l1,0 coefficients of the spherical harmonics
  43154. */
  43155. this.l10 = BABYLON.Vector3.Zero();
  43156. /**
  43157. * The l1,1 coefficients of the spherical harmonics
  43158. */
  43159. this.l11 = BABYLON.Vector3.Zero();
  43160. /**
  43161. * The l2,-2 coefficients of the spherical harmonics
  43162. */
  43163. this.l2_2 = BABYLON.Vector3.Zero();
  43164. /**
  43165. * The l2,-1 coefficients of the spherical harmonics
  43166. */
  43167. this.l2_1 = BABYLON.Vector3.Zero();
  43168. /**
  43169. * The l2,0 coefficients of the spherical harmonics
  43170. */
  43171. this.l20 = BABYLON.Vector3.Zero();
  43172. /**
  43173. * The l2,1 coefficients of the spherical harmonics
  43174. */
  43175. this.l21 = BABYLON.Vector3.Zero();
  43176. /**
  43177. * The l2,2 coefficients of the spherical harmonics
  43178. */
  43179. this.lL22 = BABYLON.Vector3.Zero();
  43180. }
  43181. /**
  43182. * Adds a light to the spherical harmonics
  43183. * @param direction the direction of the light
  43184. * @param color the color of the light
  43185. * @param deltaSolidAngle the delta solid angle of the light
  43186. */
  43187. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43188. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43189. var c = colorVector.scale(deltaSolidAngle);
  43190. this.l00 = this.l00.add(c.scale(0.282095));
  43191. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43192. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43193. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43194. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43195. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43196. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43197. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43198. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43199. };
  43200. /**
  43201. * Scales the spherical harmonics by the given amount
  43202. * @param scale the amount to scale
  43203. */
  43204. SphericalHarmonics.prototype.scale = function (scale) {
  43205. this.l00 = this.l00.scale(scale);
  43206. this.l1_1 = this.l1_1.scale(scale);
  43207. this.l10 = this.l10.scale(scale);
  43208. this.l11 = this.l11.scale(scale);
  43209. this.l2_2 = this.l2_2.scale(scale);
  43210. this.l2_1 = this.l2_1.scale(scale);
  43211. this.l20 = this.l20.scale(scale);
  43212. this.l21 = this.l21.scale(scale);
  43213. this.lL22 = this.lL22.scale(scale);
  43214. };
  43215. /**
  43216. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43217. *
  43218. * ```
  43219. * E_lm = A_l * L_lm
  43220. * ```
  43221. *
  43222. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43223. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43224. * the scaling factors are given in equation 9.
  43225. */
  43226. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43227. // Constant (Band 0)
  43228. this.l00 = this.l00.scale(3.141593);
  43229. // Linear (Band 1)
  43230. this.l1_1 = this.l1_1.scale(2.094395);
  43231. this.l10 = this.l10.scale(2.094395);
  43232. this.l11 = this.l11.scale(2.094395);
  43233. // Quadratic (Band 2)
  43234. this.l2_2 = this.l2_2.scale(0.785398);
  43235. this.l2_1 = this.l2_1.scale(0.785398);
  43236. this.l20 = this.l20.scale(0.785398);
  43237. this.l21 = this.l21.scale(0.785398);
  43238. this.lL22 = this.lL22.scale(0.785398);
  43239. };
  43240. /**
  43241. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43242. *
  43243. * ```
  43244. * L = (1/pi) * E * rho
  43245. * ```
  43246. *
  43247. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43248. */
  43249. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43250. this.scale(1.0 / Math.PI);
  43251. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43252. // (The pixel shader must apply albedo after texture fetches, etc).
  43253. };
  43254. /**
  43255. * Gets the spherical harmonics from polynomial
  43256. * @param polynomial the spherical polynomial
  43257. * @returns the spherical harmonics
  43258. */
  43259. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43260. var result = new SphericalHarmonics();
  43261. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43262. result.l1_1 = polynomial.y.scale(0.977204);
  43263. result.l10 = polynomial.z.scale(0.977204);
  43264. result.l11 = polynomial.x.scale(0.977204);
  43265. result.l2_2 = polynomial.xy.scale(1.16538);
  43266. result.l2_1 = polynomial.yz.scale(1.16538);
  43267. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43268. result.l21 = polynomial.zx.scale(1.16538);
  43269. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43270. result.scale(Math.PI);
  43271. return result;
  43272. };
  43273. /**
  43274. * Constructs a spherical harmonics from an array.
  43275. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43276. * @returns the spherical harmonics
  43277. */
  43278. SphericalHarmonics.FromArray = function (data) {
  43279. var sh = new SphericalHarmonics();
  43280. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43281. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43282. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43283. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43284. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43285. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43286. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43287. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43288. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43289. return sh;
  43290. };
  43291. return SphericalHarmonics;
  43292. }());
  43293. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43294. })(BABYLON || (BABYLON = {}));
  43295. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43296. var BABYLON;
  43297. (function (BABYLON) {
  43298. var FileFaceOrientation = /** @class */ (function () {
  43299. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43300. this.name = name;
  43301. this.worldAxisForNormal = worldAxisForNormal;
  43302. this.worldAxisForFileX = worldAxisForFileX;
  43303. this.worldAxisForFileY = worldAxisForFileY;
  43304. }
  43305. return FileFaceOrientation;
  43306. }());
  43307. ;
  43308. /**
  43309. * Helper class dealing with the extraction of spherical polynomial dataArray
  43310. * from a cube map.
  43311. */
  43312. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43313. function CubeMapToSphericalPolynomialTools() {
  43314. }
  43315. /**
  43316. * Converts a texture to the according Spherical Polynomial data.
  43317. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43318. *
  43319. * @param texture The texture to extract the information from.
  43320. * @return The Spherical Polynomial data.
  43321. */
  43322. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43323. if (!texture.isCube) {
  43324. // Only supports cube Textures currently.
  43325. return null;
  43326. }
  43327. var size = texture.getSize().width;
  43328. var right = texture.readPixels(0);
  43329. var left = texture.readPixels(1);
  43330. var up;
  43331. var down;
  43332. if (texture.isRenderTarget) {
  43333. up = texture.readPixels(3);
  43334. down = texture.readPixels(2);
  43335. }
  43336. else {
  43337. up = texture.readPixels(2);
  43338. down = texture.readPixels(3);
  43339. }
  43340. var front = texture.readPixels(4);
  43341. var back = texture.readPixels(5);
  43342. var gammaSpace = texture.gammaSpace;
  43343. // Always read as RGBA.
  43344. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43345. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43346. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43347. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43348. }
  43349. var cubeInfo = {
  43350. size: size,
  43351. right: right,
  43352. left: left,
  43353. up: up,
  43354. down: down,
  43355. front: front,
  43356. back: back,
  43357. format: format,
  43358. type: type,
  43359. gammaSpace: gammaSpace,
  43360. };
  43361. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43362. };
  43363. /**
  43364. * Converts a cubemap to the according Spherical Polynomial data.
  43365. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43366. *
  43367. * @param cubeInfo The Cube map to extract the information from.
  43368. * @return The Spherical Polynomial data.
  43369. */
  43370. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43371. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43372. var totalSolidAngle = 0.0;
  43373. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43374. var du = 2.0 / cubeInfo.size;
  43375. var dv = du;
  43376. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43377. var minUV = du * 0.5 - 1.0;
  43378. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43379. var fileFace = this.FileFaces[faceIndex];
  43380. var dataArray = cubeInfo[fileFace.name];
  43381. var v = minUV;
  43382. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43383. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43384. // Because SP is still linear, so summation is fine in that basis.
  43385. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43386. for (var y = 0; y < cubeInfo.size; y++) {
  43387. var u = minUV;
  43388. for (var x = 0; x < cubeInfo.size; x++) {
  43389. // World direction (not normalised)
  43390. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43391. worldDirection.normalize();
  43392. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43393. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43394. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43395. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43396. // Handle Integer types.
  43397. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43398. r /= 255;
  43399. g /= 255;
  43400. b /= 255;
  43401. }
  43402. // Handle Gamma space textures.
  43403. if (cubeInfo.gammaSpace) {
  43404. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43405. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43406. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43407. }
  43408. var color = new BABYLON.Color3(r, g, b);
  43409. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43410. totalSolidAngle += deltaSolidAngle;
  43411. u += du;
  43412. }
  43413. v += dv;
  43414. }
  43415. }
  43416. // Solid angle for entire sphere is 4*pi
  43417. var sphereSolidAngle = 4.0 * Math.PI;
  43418. // Adjust the solid angle to allow for how many faces we processed.
  43419. var facesProcessed = 6.0;
  43420. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43421. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43422. // This is needed because the numerical integration over the cube uses a
  43423. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43424. // and also to compensate for accumulative error due to float precision in the summation.
  43425. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43426. sphericalHarmonics.scale(correctionFactor);
  43427. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43428. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43429. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43430. };
  43431. CubeMapToSphericalPolynomialTools.FileFaces = [
  43432. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43433. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43434. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43435. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43436. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43437. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43438. ];
  43439. return CubeMapToSphericalPolynomialTools;
  43440. }());
  43441. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43442. })(BABYLON || (BABYLON = {}));
  43443. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43444. var BABYLON;
  43445. (function (BABYLON) {
  43446. /**
  43447. * Manages the defines for the PBR Material.
  43448. * @hiddenChildren
  43449. */
  43450. var PBRMaterialDefines = /** @class */ (function (_super) {
  43451. __extends(PBRMaterialDefines, _super);
  43452. /**
  43453. * Initializes the PBR Material defines.
  43454. */
  43455. function PBRMaterialDefines() {
  43456. var _this = _super.call(this) || this;
  43457. _this.PBR = true;
  43458. _this.MAINUV1 = false;
  43459. _this.MAINUV2 = false;
  43460. _this.UV1 = false;
  43461. _this.UV2 = false;
  43462. _this.ALBEDO = false;
  43463. _this.ALBEDODIRECTUV = 0;
  43464. _this.VERTEXCOLOR = false;
  43465. _this.AMBIENT = false;
  43466. _this.AMBIENTDIRECTUV = 0;
  43467. _this.AMBIENTINGRAYSCALE = false;
  43468. _this.OPACITY = false;
  43469. _this.VERTEXALPHA = false;
  43470. _this.OPACITYDIRECTUV = 0;
  43471. _this.OPACITYRGB = false;
  43472. _this.ALPHATEST = false;
  43473. _this.DEPTHPREPASS = false;
  43474. _this.ALPHABLEND = false;
  43475. _this.ALPHAFROMALBEDO = false;
  43476. _this.ALPHATESTVALUE = "0.5";
  43477. _this.SPECULAROVERALPHA = false;
  43478. _this.RADIANCEOVERALPHA = false;
  43479. _this.ALPHAFRESNEL = false;
  43480. _this.LINEARALPHAFRESNEL = false;
  43481. _this.PREMULTIPLYALPHA = false;
  43482. _this.EMISSIVE = false;
  43483. _this.EMISSIVEDIRECTUV = 0;
  43484. _this.REFLECTIVITY = false;
  43485. _this.REFLECTIVITYDIRECTUV = 0;
  43486. _this.SPECULARTERM = false;
  43487. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43488. _this.MICROSURFACEAUTOMATIC = false;
  43489. _this.LODBASEDMICROSFURACE = false;
  43490. _this.MICROSURFACEMAP = false;
  43491. _this.MICROSURFACEMAPDIRECTUV = 0;
  43492. _this.METALLICWORKFLOW = false;
  43493. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43494. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43495. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43496. _this.AOSTOREINMETALMAPRED = false;
  43497. _this.ENVIRONMENTBRDF = false;
  43498. _this.NORMAL = false;
  43499. _this.TANGENT = false;
  43500. _this.BUMP = false;
  43501. _this.BUMPDIRECTUV = 0;
  43502. _this.OBJECTSPACE_NORMALMAP = false;
  43503. _this.PARALLAX = false;
  43504. _this.PARALLAXOCCLUSION = false;
  43505. _this.NORMALXYSCALE = true;
  43506. _this.LIGHTMAP = false;
  43507. _this.LIGHTMAPDIRECTUV = 0;
  43508. _this.USELIGHTMAPASSHADOWMAP = false;
  43509. _this.GAMMALIGHTMAP = false;
  43510. _this.REFLECTION = false;
  43511. _this.REFLECTIONMAP_3D = false;
  43512. _this.REFLECTIONMAP_SPHERICAL = false;
  43513. _this.REFLECTIONMAP_PLANAR = false;
  43514. _this.REFLECTIONMAP_CUBIC = false;
  43515. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43516. _this.REFLECTIONMAP_PROJECTION = false;
  43517. _this.REFLECTIONMAP_SKYBOX = false;
  43518. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43519. _this.REFLECTIONMAP_EXPLICIT = false;
  43520. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43521. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43522. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43523. _this.INVERTCUBICMAP = false;
  43524. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43525. _this.USESPHERICALINVERTEX = false;
  43526. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43527. _this.LODINREFLECTIONALPHA = false;
  43528. _this.GAMMAREFLECTION = false;
  43529. _this.RGBDREFLECTION = false;
  43530. _this.RADIANCEOCCLUSION = false;
  43531. _this.HORIZONOCCLUSION = false;
  43532. _this.REFRACTION = false;
  43533. _this.REFRACTIONMAP_3D = false;
  43534. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43535. _this.LODINREFRACTIONALPHA = false;
  43536. _this.GAMMAREFRACTION = false;
  43537. _this.RGBDREFRACTION = false;
  43538. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43539. _this.INSTANCES = false;
  43540. _this.NUM_BONE_INFLUENCERS = 0;
  43541. _this.BonesPerMesh = 0;
  43542. _this.NONUNIFORMSCALING = false;
  43543. _this.MORPHTARGETS = false;
  43544. _this.MORPHTARGETS_NORMAL = false;
  43545. _this.MORPHTARGETS_TANGENT = false;
  43546. _this.NUM_MORPH_INFLUENCERS = 0;
  43547. _this.IMAGEPROCESSING = false;
  43548. _this.VIGNETTE = false;
  43549. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43550. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43551. _this.TONEMAPPING = false;
  43552. _this.TONEMAPPING_ACES = false;
  43553. _this.CONTRAST = false;
  43554. _this.COLORCURVES = false;
  43555. _this.COLORGRADING = false;
  43556. _this.COLORGRADING3D = false;
  43557. _this.SAMPLER3DGREENDEPTH = false;
  43558. _this.SAMPLER3DBGRMAP = false;
  43559. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43560. _this.EXPOSURE = false;
  43561. _this.USEPHYSICALLIGHTFALLOFF = false;
  43562. _this.USEGLTFLIGHTFALLOFF = false;
  43563. _this.TWOSIDEDLIGHTING = false;
  43564. _this.SHADOWFLOAT = false;
  43565. _this.CLIPPLANE = false;
  43566. _this.CLIPPLANE2 = false;
  43567. _this.CLIPPLANE3 = false;
  43568. _this.CLIPPLANE4 = false;
  43569. _this.POINTSIZE = false;
  43570. _this.FOG = false;
  43571. _this.LOGARITHMICDEPTH = false;
  43572. _this.FORCENORMALFORWARD = false;
  43573. _this.SPECULARAA = false;
  43574. _this.UNLIT = false;
  43575. _this.rebuild();
  43576. return _this;
  43577. }
  43578. /**
  43579. * Resets the PBR Material defines.
  43580. */
  43581. PBRMaterialDefines.prototype.reset = function () {
  43582. _super.prototype.reset.call(this);
  43583. this.ALPHATESTVALUE = "0.5";
  43584. this.PBR = true;
  43585. };
  43586. return PBRMaterialDefines;
  43587. }(BABYLON.MaterialDefines));
  43588. /**
  43589. * The Physically based material base class of BJS.
  43590. *
  43591. * This offers the main features of a standard PBR material.
  43592. * For more information, please refer to the documentation :
  43593. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43594. */
  43595. var PBRBaseMaterial = /** @class */ (function (_super) {
  43596. __extends(PBRBaseMaterial, _super);
  43597. /**
  43598. * Instantiates a new PBRMaterial instance.
  43599. *
  43600. * @param name The material name
  43601. * @param scene The scene the material will be use in.
  43602. */
  43603. function PBRBaseMaterial(name, scene) {
  43604. var _this = _super.call(this, name, scene) || this;
  43605. /**
  43606. * Intensity of the direct lights e.g. the four lights available in your scene.
  43607. * This impacts both the direct diffuse and specular highlights.
  43608. */
  43609. _this._directIntensity = 1.0;
  43610. /**
  43611. * Intensity of the emissive part of the material.
  43612. * This helps controlling the emissive effect without modifying the emissive color.
  43613. */
  43614. _this._emissiveIntensity = 1.0;
  43615. /**
  43616. * Intensity of the environment e.g. how much the environment will light the object
  43617. * either through harmonics for rough material or through the refelction for shiny ones.
  43618. */
  43619. _this._environmentIntensity = 1.0;
  43620. /**
  43621. * This is a special control allowing the reduction of the specular highlights coming from the
  43622. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43623. */
  43624. _this._specularIntensity = 1.0;
  43625. /**
  43626. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43627. */
  43628. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43629. /**
  43630. * Debug Control allowing disabling the bump map on this material.
  43631. */
  43632. _this._disableBumpMap = false;
  43633. /**
  43634. * AKA Occlusion Texture Intensity in other nomenclature.
  43635. */
  43636. _this._ambientTextureStrength = 1.0;
  43637. /**
  43638. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43639. * 1 means it completely occludes it
  43640. * 0 mean it has no impact
  43641. */
  43642. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43643. /**
  43644. * The color of a material in ambient lighting.
  43645. */
  43646. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43647. /**
  43648. * AKA Diffuse Color in other nomenclature.
  43649. */
  43650. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43651. /**
  43652. * AKA Specular Color in other nomenclature.
  43653. */
  43654. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43655. /**
  43656. * The color applied when light is reflected from a material.
  43657. */
  43658. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43659. /**
  43660. * The color applied when light is emitted from a material.
  43661. */
  43662. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43663. /**
  43664. * AKA Glossiness in other nomenclature.
  43665. */
  43666. _this._microSurface = 0.9;
  43667. /**
  43668. * source material index of refraction (IOR)' / 'destination material IOR.
  43669. */
  43670. _this._indexOfRefraction = 0.66;
  43671. /**
  43672. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43673. */
  43674. _this._invertRefractionY = false;
  43675. /**
  43676. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43677. * Materials half opaque for instance using refraction could benefit from this control.
  43678. */
  43679. _this._linkRefractionWithTransparency = false;
  43680. /**
  43681. * Specifies that the material will use the light map as a show map.
  43682. */
  43683. _this._useLightmapAsShadowmap = false;
  43684. /**
  43685. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43686. * makes the reflect vector face the model (under horizon).
  43687. */
  43688. _this._useHorizonOcclusion = true;
  43689. /**
  43690. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43691. * too much the area relying on ambient texture to define their ambient occlusion.
  43692. */
  43693. _this._useRadianceOcclusion = true;
  43694. /**
  43695. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43696. */
  43697. _this._useAlphaFromAlbedoTexture = false;
  43698. /**
  43699. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43700. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43701. */
  43702. _this._useSpecularOverAlpha = true;
  43703. /**
  43704. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43705. */
  43706. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43707. /**
  43708. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43709. */
  43710. _this._useRoughnessFromMetallicTextureAlpha = true;
  43711. /**
  43712. * Specifies if the metallic texture contains the roughness information in its green channel.
  43713. */
  43714. _this._useRoughnessFromMetallicTextureGreen = false;
  43715. /**
  43716. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43717. */
  43718. _this._useMetallnessFromMetallicTextureBlue = false;
  43719. /**
  43720. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43721. */
  43722. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43723. /**
  43724. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43725. */
  43726. _this._useAmbientInGrayScale = false;
  43727. /**
  43728. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43729. * The material will try to infer what glossiness each pixel should be.
  43730. */
  43731. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43732. /**
  43733. * Defines the falloff type used in this material.
  43734. * It by default is Physical.
  43735. */
  43736. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43737. /**
  43738. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43739. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43740. */
  43741. _this._useRadianceOverAlpha = true;
  43742. /**
  43743. * Allows using an object space normal map (instead of tangent space).
  43744. */
  43745. _this._useObjectSpaceNormalMap = false;
  43746. /**
  43747. * Allows using the bump map in parallax mode.
  43748. */
  43749. _this._useParallax = false;
  43750. /**
  43751. * Allows using the bump map in parallax occlusion mode.
  43752. */
  43753. _this._useParallaxOcclusion = false;
  43754. /**
  43755. * Controls the scale bias of the parallax mode.
  43756. */
  43757. _this._parallaxScaleBias = 0.05;
  43758. /**
  43759. * If sets to true, disables all the lights affecting the material.
  43760. */
  43761. _this._disableLighting = false;
  43762. /**
  43763. * Number of Simultaneous lights allowed on the material.
  43764. */
  43765. _this._maxSimultaneousLights = 4;
  43766. /**
  43767. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43768. */
  43769. _this._invertNormalMapX = false;
  43770. /**
  43771. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43772. */
  43773. _this._invertNormalMapY = false;
  43774. /**
  43775. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43776. */
  43777. _this._twoSidedLighting = false;
  43778. /**
  43779. * Defines the alpha limits in alpha test mode.
  43780. */
  43781. _this._alphaCutOff = 0.4;
  43782. /**
  43783. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43784. */
  43785. _this._forceAlphaTest = false;
  43786. /**
  43787. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43788. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43789. */
  43790. _this._useAlphaFresnel = false;
  43791. /**
  43792. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43793. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43794. */
  43795. _this._useLinearAlphaFresnel = false;
  43796. /**
  43797. * The transparency mode of the material.
  43798. */
  43799. _this._transparencyMode = null;
  43800. /**
  43801. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43802. * from cos thetav and roughness:
  43803. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43804. */
  43805. _this._environmentBRDFTexture = null;
  43806. /**
  43807. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43808. */
  43809. _this._forceIrradianceInFragment = false;
  43810. /**
  43811. * Force normal to face away from face.
  43812. */
  43813. _this._forceNormalForward = false;
  43814. /**
  43815. * Enables specular anti aliasing in the PBR shader.
  43816. * It will both interacts on the Geometry for analytical and IBL lighting.
  43817. * It also prefilter the roughness map based on the bump values.
  43818. */
  43819. _this._enableSpecularAntiAliasing = false;
  43820. /**
  43821. * Stores the available render targets.
  43822. */
  43823. _this._renderTargets = new BABYLON.SmartArray(16);
  43824. /**
  43825. * Sets the global ambient color for the material used in lighting calculations.
  43826. */
  43827. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43828. /**
  43829. * If set to true, no lighting calculations will be applied.
  43830. */
  43831. _this._unlit = false;
  43832. // Setup the default processing configuration to the scene.
  43833. _this._attachImageProcessingConfiguration(null);
  43834. _this.getRenderTargetTextures = function () {
  43835. _this._renderTargets.reset();
  43836. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43837. _this._renderTargets.push(_this._reflectionTexture);
  43838. }
  43839. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43840. _this._renderTargets.push(_this._refractionTexture);
  43841. }
  43842. return _this._renderTargets;
  43843. };
  43844. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43845. return _this;
  43846. }
  43847. /**
  43848. * Attaches a new image processing configuration to the PBR Material.
  43849. * @param configuration
  43850. */
  43851. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43852. var _this = this;
  43853. if (configuration === this._imageProcessingConfiguration) {
  43854. return;
  43855. }
  43856. // Detaches observer.
  43857. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43858. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43859. }
  43860. // Pick the scene configuration if needed.
  43861. if (!configuration) {
  43862. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43863. }
  43864. else {
  43865. this._imageProcessingConfiguration = configuration;
  43866. }
  43867. // Attaches observer.
  43868. if (this._imageProcessingConfiguration) {
  43869. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43870. _this._markAllSubMeshesAsImageProcessingDirty();
  43871. });
  43872. }
  43873. };
  43874. /**
  43875. * Gets the name of the material class.
  43876. */
  43877. PBRBaseMaterial.prototype.getClassName = function () {
  43878. return "PBRBaseMaterial";
  43879. };
  43880. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43881. /**
  43882. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43883. */
  43884. get: function () {
  43885. return this._useLogarithmicDepth;
  43886. },
  43887. /**
  43888. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43889. */
  43890. set: function (value) {
  43891. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43892. },
  43893. enumerable: true,
  43894. configurable: true
  43895. });
  43896. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43897. /**
  43898. * Gets the current transparency mode.
  43899. */
  43900. get: function () {
  43901. return this._transparencyMode;
  43902. },
  43903. /**
  43904. * Sets the transparency mode of the material.
  43905. *
  43906. * | Value | Type | Description |
  43907. * | ----- | ----------------------------------- | ----------- |
  43908. * | 0 | OPAQUE | |
  43909. * | 1 | ALPHATEST | |
  43910. * | 2 | ALPHABLEND | |
  43911. * | 3 | ALPHATESTANDBLEND | |
  43912. *
  43913. */
  43914. set: function (value) {
  43915. if (this._transparencyMode === value) {
  43916. return;
  43917. }
  43918. this._transparencyMode = value;
  43919. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43920. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43921. },
  43922. enumerable: true,
  43923. configurable: true
  43924. });
  43925. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43926. /**
  43927. * Returns true if alpha blending should be disabled.
  43928. */
  43929. get: function () {
  43930. return (this._linkRefractionWithTransparency ||
  43931. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43932. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43933. },
  43934. enumerable: true,
  43935. configurable: true
  43936. });
  43937. /**
  43938. * Specifies whether or not this material should be rendered in alpha blend mode.
  43939. */
  43940. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43941. if (this._disableAlphaBlending) {
  43942. return false;
  43943. }
  43944. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43945. };
  43946. /**
  43947. * Specifies if the mesh will require alpha blending.
  43948. * @param mesh - BJS mesh.
  43949. */
  43950. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43951. if (this._disableAlphaBlending) {
  43952. return false;
  43953. }
  43954. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43955. };
  43956. /**
  43957. * Specifies whether or not this material should be rendered in alpha test mode.
  43958. */
  43959. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43960. if (this._forceAlphaTest) {
  43961. return true;
  43962. }
  43963. if (this._linkRefractionWithTransparency) {
  43964. return false;
  43965. }
  43966. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43967. };
  43968. /**
  43969. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43970. */
  43971. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43972. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43973. };
  43974. /**
  43975. * Gets the texture used for the alpha test.
  43976. */
  43977. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43978. return this._albedoTexture;
  43979. };
  43980. /**
  43981. * Specifies that the submesh is ready to be used.
  43982. * @param mesh - BJS mesh.
  43983. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43984. * @param useInstances - Specifies that instances should be used.
  43985. * @returns - boolean indicating that the submesh is ready or not.
  43986. */
  43987. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43988. if (subMesh.effect && this.isFrozen) {
  43989. if (this._wasPreviouslyReady) {
  43990. return true;
  43991. }
  43992. }
  43993. if (!subMesh._materialDefines) {
  43994. subMesh._materialDefines = new PBRMaterialDefines();
  43995. }
  43996. var defines = subMesh._materialDefines;
  43997. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43998. if (defines._renderId === this.getScene().getRenderId()) {
  43999. return true;
  44000. }
  44001. }
  44002. var scene = this.getScene();
  44003. var engine = scene.getEngine();
  44004. if (defines._areTexturesDirty) {
  44005. if (scene.texturesEnabled) {
  44006. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44007. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44008. return false;
  44009. }
  44010. }
  44011. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44012. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44013. return false;
  44014. }
  44015. }
  44016. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44017. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44018. return false;
  44019. }
  44020. }
  44021. var reflectionTexture = this._getReflectionTexture();
  44022. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44023. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44024. return false;
  44025. }
  44026. }
  44027. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44028. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44029. return false;
  44030. }
  44031. }
  44032. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44033. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44034. return false;
  44035. }
  44036. }
  44037. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44038. if (this._metallicTexture) {
  44039. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44040. return false;
  44041. }
  44042. }
  44043. else if (this._reflectivityTexture) {
  44044. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44045. return false;
  44046. }
  44047. }
  44048. if (this._microSurfaceTexture) {
  44049. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44050. return false;
  44051. }
  44052. }
  44053. }
  44054. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44055. // Bump texture cannot be not blocking.
  44056. if (!this._bumpTexture.isReady()) {
  44057. return false;
  44058. }
  44059. }
  44060. var refractionTexture = this._getRefractionTexture();
  44061. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44062. if (!refractionTexture.isReadyOrNotBlocking()) {
  44063. return false;
  44064. }
  44065. }
  44066. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44067. // This is blocking.
  44068. if (!this._environmentBRDFTexture.isReady()) {
  44069. return false;
  44070. }
  44071. }
  44072. }
  44073. }
  44074. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44075. if (!this._imageProcessingConfiguration.isReady()) {
  44076. return false;
  44077. }
  44078. }
  44079. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44080. mesh.createNormals(true);
  44081. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44082. }
  44083. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44084. if (effect) {
  44085. scene.resetCachedMaterial();
  44086. subMesh.setEffect(effect, defines);
  44087. this.buildUniformLayout();
  44088. }
  44089. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44090. return false;
  44091. }
  44092. defines._renderId = scene.getRenderId();
  44093. this._wasPreviouslyReady = true;
  44094. return true;
  44095. };
  44096. /**
  44097. * Specifies if the material uses metallic roughness workflow.
  44098. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44099. */
  44100. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44101. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44102. return true;
  44103. }
  44104. return false;
  44105. };
  44106. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44107. if (onCompiled === void 0) { onCompiled = null; }
  44108. if (onError === void 0) { onError = null; }
  44109. if (useInstances === void 0) { useInstances = null; }
  44110. if (useClipPlane === void 0) { useClipPlane = null; }
  44111. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44112. if (!defines.isDirty) {
  44113. return null;
  44114. }
  44115. defines.markAsProcessed();
  44116. var scene = this.getScene();
  44117. var engine = scene.getEngine();
  44118. // Fallbacks
  44119. var fallbacks = new BABYLON.EffectFallbacks();
  44120. var fallbackRank = 0;
  44121. if (defines.USESPHERICALINVERTEX) {
  44122. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44123. }
  44124. if (defines.FOG) {
  44125. fallbacks.addFallback(fallbackRank, "FOG");
  44126. }
  44127. if (defines.SPECULARAA) {
  44128. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44129. }
  44130. if (defines.POINTSIZE) {
  44131. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44132. }
  44133. if (defines.LOGARITHMICDEPTH) {
  44134. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44135. }
  44136. if (defines.PARALLAX) {
  44137. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44138. }
  44139. if (defines.PARALLAXOCCLUSION) {
  44140. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44141. }
  44142. if (defines.ENVIRONMENTBRDF) {
  44143. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44144. }
  44145. if (defines.TANGENT) {
  44146. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44147. }
  44148. if (defines.BUMP) {
  44149. fallbacks.addFallback(fallbackRank++, "BUMP");
  44150. }
  44151. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44152. if (defines.SPECULARTERM) {
  44153. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44154. }
  44155. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44156. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44157. }
  44158. if (defines.LIGHTMAP) {
  44159. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44160. }
  44161. if (defines.NORMAL) {
  44162. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44163. }
  44164. if (defines.AMBIENT) {
  44165. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44166. }
  44167. if (defines.EMISSIVE) {
  44168. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44169. }
  44170. if (defines.VERTEXCOLOR) {
  44171. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44172. }
  44173. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44174. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44175. }
  44176. if (defines.MORPHTARGETS) {
  44177. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44178. }
  44179. //Attributes
  44180. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44181. if (defines.NORMAL) {
  44182. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44183. }
  44184. if (defines.TANGENT) {
  44185. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44186. }
  44187. if (defines.UV1) {
  44188. attribs.push(BABYLON.VertexBuffer.UVKind);
  44189. }
  44190. if (defines.UV2) {
  44191. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44192. }
  44193. if (defines.VERTEXCOLOR) {
  44194. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44195. }
  44196. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44197. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44198. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44199. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44200. "vFogInfos", "vFogColor", "pointSize",
  44201. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44202. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44203. "mBones",
  44204. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44205. "vLightingIntensity",
  44206. "logarithmicDepthConstant",
  44207. "vSphericalX", "vSphericalY", "vSphericalZ",
  44208. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44209. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44210. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44211. "vTangentSpaceParams"
  44212. ];
  44213. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44214. "bumpSampler", "lightmapSampler", "opacitySampler",
  44215. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44216. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44217. "microSurfaceSampler", "environmentBrdfSampler"];
  44218. var uniformBuffers = ["Material", "Scene"];
  44219. if (BABYLON.ImageProcessingConfiguration) {
  44220. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44221. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44222. }
  44223. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44224. uniformsNames: uniforms,
  44225. uniformBuffersNames: uniformBuffers,
  44226. samplers: samplers,
  44227. defines: defines,
  44228. maxSimultaneousLights: this._maxSimultaneousLights
  44229. });
  44230. var join = defines.toString();
  44231. return engine.createEffect("pbr", {
  44232. attributes: attribs,
  44233. uniformsNames: uniforms,
  44234. uniformBuffersNames: uniformBuffers,
  44235. samplers: samplers,
  44236. defines: join,
  44237. fallbacks: fallbacks,
  44238. onCompiled: onCompiled,
  44239. onError: onError,
  44240. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44241. }, engine);
  44242. };
  44243. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44244. if (useInstances === void 0) { useInstances = null; }
  44245. if (useClipPlane === void 0) { useClipPlane = null; }
  44246. var scene = this.getScene();
  44247. var engine = scene.getEngine();
  44248. // Lights
  44249. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44250. defines._needNormals = true;
  44251. // Textures
  44252. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44253. if (defines._areTexturesDirty) {
  44254. defines._needUVs = false;
  44255. if (scene.texturesEnabled) {
  44256. if (scene.getEngine().getCaps().textureLOD) {
  44257. defines.LODBASEDMICROSFURACE = true;
  44258. }
  44259. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44260. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44261. }
  44262. else {
  44263. defines.ALBEDO = false;
  44264. }
  44265. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44266. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44267. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44268. }
  44269. else {
  44270. defines.AMBIENT = false;
  44271. }
  44272. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44273. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44274. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44275. }
  44276. else {
  44277. defines.OPACITY = false;
  44278. }
  44279. var reflectionTexture = this._getReflectionTexture();
  44280. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44281. defines.REFLECTION = true;
  44282. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44283. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44284. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44285. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44286. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44287. defines.INVERTCUBICMAP = true;
  44288. }
  44289. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44290. switch (reflectionTexture.coordinatesMode) {
  44291. case BABYLON.Texture.EXPLICIT_MODE:
  44292. defines.REFLECTIONMAP_EXPLICIT = true;
  44293. break;
  44294. case BABYLON.Texture.PLANAR_MODE:
  44295. defines.REFLECTIONMAP_PLANAR = true;
  44296. break;
  44297. case BABYLON.Texture.PROJECTION_MODE:
  44298. defines.REFLECTIONMAP_PROJECTION = true;
  44299. break;
  44300. case BABYLON.Texture.SKYBOX_MODE:
  44301. defines.REFLECTIONMAP_SKYBOX = true;
  44302. break;
  44303. case BABYLON.Texture.SPHERICAL_MODE:
  44304. defines.REFLECTIONMAP_SPHERICAL = true;
  44305. break;
  44306. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44307. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44308. break;
  44309. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44310. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44311. break;
  44312. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44313. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44314. break;
  44315. case BABYLON.Texture.CUBIC_MODE:
  44316. case BABYLON.Texture.INVCUBIC_MODE:
  44317. default:
  44318. defines.REFLECTIONMAP_CUBIC = true;
  44319. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44320. break;
  44321. }
  44322. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44323. if (reflectionTexture.sphericalPolynomial) {
  44324. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44325. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44326. defines.USESPHERICALINVERTEX = false;
  44327. }
  44328. else {
  44329. defines.USESPHERICALINVERTEX = true;
  44330. }
  44331. }
  44332. }
  44333. else {
  44334. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44335. }
  44336. }
  44337. else {
  44338. defines.REFLECTION = false;
  44339. defines.REFLECTIONMAP_3D = false;
  44340. defines.REFLECTIONMAP_SPHERICAL = false;
  44341. defines.REFLECTIONMAP_PLANAR = false;
  44342. defines.REFLECTIONMAP_CUBIC = false;
  44343. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44344. defines.REFLECTIONMAP_PROJECTION = false;
  44345. defines.REFLECTIONMAP_SKYBOX = false;
  44346. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44347. defines.REFLECTIONMAP_EXPLICIT = false;
  44348. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44349. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44350. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44351. defines.INVERTCUBICMAP = false;
  44352. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44353. defines.USESPHERICALINVERTEX = false;
  44354. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44355. defines.LODINREFLECTIONALPHA = false;
  44356. defines.GAMMAREFLECTION = false;
  44357. defines.RGBDREFLECTION = false;
  44358. }
  44359. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44360. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44361. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44362. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44363. }
  44364. else {
  44365. defines.LIGHTMAP = false;
  44366. }
  44367. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44368. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44369. }
  44370. else {
  44371. defines.EMISSIVE = false;
  44372. }
  44373. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44374. if (this._metallicTexture) {
  44375. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44376. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44377. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44378. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44379. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44380. }
  44381. else if (this._reflectivityTexture) {
  44382. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44383. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44384. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44385. }
  44386. else {
  44387. defines.REFLECTIVITY = false;
  44388. }
  44389. if (this._microSurfaceTexture) {
  44390. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44391. }
  44392. else {
  44393. defines.MICROSURFACEMAP = false;
  44394. }
  44395. }
  44396. else {
  44397. defines.REFLECTIVITY = false;
  44398. defines.MICROSURFACEMAP = false;
  44399. }
  44400. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44401. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44402. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44403. defines.PARALLAX = true;
  44404. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44405. }
  44406. else {
  44407. defines.PARALLAX = false;
  44408. }
  44409. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44410. }
  44411. else {
  44412. defines.BUMP = false;
  44413. }
  44414. var refractionTexture = this._getRefractionTexture();
  44415. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44416. defines.REFRACTION = true;
  44417. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44418. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44419. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44420. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44421. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44422. if (this._linkRefractionWithTransparency) {
  44423. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44424. }
  44425. }
  44426. else {
  44427. defines.REFRACTION = false;
  44428. }
  44429. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44430. defines.ENVIRONMENTBRDF = true;
  44431. }
  44432. else {
  44433. defines.ENVIRONMENTBRDF = false;
  44434. }
  44435. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44436. defines.ALPHAFROMALBEDO = true;
  44437. }
  44438. else {
  44439. defines.ALPHAFROMALBEDO = false;
  44440. }
  44441. }
  44442. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44443. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44444. defines.USEPHYSICALLIGHTFALLOFF = false;
  44445. defines.USEGLTFLIGHTFALLOFF = false;
  44446. }
  44447. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44448. defines.USEPHYSICALLIGHTFALLOFF = false;
  44449. defines.USEGLTFLIGHTFALLOFF = true;
  44450. }
  44451. else {
  44452. defines.USEPHYSICALLIGHTFALLOFF = true;
  44453. defines.USEGLTFLIGHTFALLOFF = false;
  44454. }
  44455. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44456. if (!this.backFaceCulling && this._twoSidedLighting) {
  44457. defines.TWOSIDEDLIGHTING = true;
  44458. }
  44459. else {
  44460. defines.TWOSIDEDLIGHTING = false;
  44461. }
  44462. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44463. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44464. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44465. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44466. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44467. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44468. }
  44469. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44470. this._imageProcessingConfiguration.prepareDefines(defines);
  44471. }
  44472. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44473. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44474. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44475. // Misc.
  44476. if (defines._areMiscDirty) {
  44477. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44478. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44479. }
  44480. // Values that need to be evaluated on every frame
  44481. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44482. // Attribs
  44483. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44484. };
  44485. /**
  44486. * Force shader compilation
  44487. */
  44488. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44489. var _this = this;
  44490. var localOptions = __assign({ clipPlane: false }, options);
  44491. var defines = new PBRMaterialDefines();
  44492. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44493. if (effect.isReady()) {
  44494. if (onCompiled) {
  44495. onCompiled(this);
  44496. }
  44497. }
  44498. else {
  44499. effect.onCompileObservable.add(function () {
  44500. if (onCompiled) {
  44501. onCompiled(_this);
  44502. }
  44503. });
  44504. }
  44505. };
  44506. /**
  44507. * Initializes the uniform buffer layout for the shader.
  44508. */
  44509. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44510. // Order is important !
  44511. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44512. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44513. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44514. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44515. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44516. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44517. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44518. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44519. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44520. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44521. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44522. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44523. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44524. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44525. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44526. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44527. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44528. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44529. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44530. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44531. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44532. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44533. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44534. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44535. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44536. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44537. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44538. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44539. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44540. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44541. this._uniformBuffer.addUniform("pointSize", 1);
  44542. this._uniformBuffer.create();
  44543. };
  44544. /**
  44545. * Unbinds the textures.
  44546. */
  44547. PBRBaseMaterial.prototype.unbind = function () {
  44548. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44549. this._uniformBuffer.setTexture("reflectionSampler", null);
  44550. }
  44551. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44552. this._uniformBuffer.setTexture("refractionSampler", null);
  44553. }
  44554. _super.prototype.unbind.call(this);
  44555. };
  44556. /**
  44557. * Binds the submesh data.
  44558. * @param world - The world matrix.
  44559. * @param mesh - The BJS mesh.
  44560. * @param subMesh - A submesh of the BJS mesh.
  44561. */
  44562. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44563. var scene = this.getScene();
  44564. var defines = subMesh._materialDefines;
  44565. if (!defines) {
  44566. return;
  44567. }
  44568. var effect = subMesh.effect;
  44569. if (!effect) {
  44570. return;
  44571. }
  44572. this._activeEffect = effect;
  44573. // Matrices
  44574. this.bindOnlyWorldMatrix(world);
  44575. // Normal Matrix
  44576. if (defines.OBJECTSPACE_NORMALMAP) {
  44577. world.toNormalMatrix(this._normalMatrix);
  44578. this.bindOnlyNormalMatrix(this._normalMatrix);
  44579. }
  44580. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44581. // Bones
  44582. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44583. var reflectionTexture = null;
  44584. if (mustRebind) {
  44585. this._uniformBuffer.bindToEffect(effect, "Material");
  44586. this.bindViewProjection(effect);
  44587. reflectionTexture = this._getReflectionTexture();
  44588. var refractionTexture = this._getRefractionTexture();
  44589. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44590. // Texture uniforms
  44591. if (scene.texturesEnabled) {
  44592. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44593. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44594. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44595. }
  44596. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44597. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44598. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44599. }
  44600. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44601. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44602. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44603. }
  44604. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44605. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44606. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44607. if (reflectionTexture.boundingBoxSize) {
  44608. var cubeTexture = reflectionTexture;
  44609. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44610. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44611. }
  44612. var polynomials = reflectionTexture.sphericalPolynomial;
  44613. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44614. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44615. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44616. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44617. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44618. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44619. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44620. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44621. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44622. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44623. }
  44624. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44625. }
  44626. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44627. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44628. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44629. }
  44630. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44631. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44632. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44633. }
  44634. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44635. if (this._metallicTexture) {
  44636. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44637. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44638. }
  44639. else if (this._reflectivityTexture) {
  44640. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44641. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44642. }
  44643. if (this._microSurfaceTexture) {
  44644. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44645. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44646. }
  44647. }
  44648. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44649. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44650. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44651. if (scene._mirroredCameraPosition) {
  44652. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44653. }
  44654. else {
  44655. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44656. }
  44657. }
  44658. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44659. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44660. var depth = 1.0;
  44661. if (!refractionTexture.isCube) {
  44662. if (refractionTexture.depth) {
  44663. depth = refractionTexture.depth;
  44664. }
  44665. }
  44666. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44667. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44668. }
  44669. }
  44670. // Point size
  44671. if (this.pointsCloud) {
  44672. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44673. }
  44674. // Colors
  44675. if (defines.METALLICWORKFLOW) {
  44676. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44677. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44678. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44679. }
  44680. else {
  44681. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44682. }
  44683. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44684. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44685. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44686. // Misc
  44687. this._lightingInfos.x = this._directIntensity;
  44688. this._lightingInfos.y = this._emissiveIntensity;
  44689. this._lightingInfos.z = this._environmentIntensity;
  44690. this._lightingInfos.w = this._specularIntensity;
  44691. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44692. }
  44693. // Textures
  44694. if (scene.texturesEnabled) {
  44695. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44696. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44697. }
  44698. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44699. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44700. }
  44701. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44702. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44703. }
  44704. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44705. if (defines.LODBASEDMICROSFURACE) {
  44706. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44707. }
  44708. else {
  44709. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44710. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44711. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44712. }
  44713. }
  44714. if (defines.ENVIRONMENTBRDF) {
  44715. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44716. }
  44717. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44718. if (defines.LODBASEDMICROSFURACE) {
  44719. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44720. }
  44721. else {
  44722. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44723. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44724. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44725. }
  44726. }
  44727. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44728. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44729. }
  44730. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44731. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44732. }
  44733. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44734. if (this._metallicTexture) {
  44735. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44736. }
  44737. else if (this._reflectivityTexture) {
  44738. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44739. }
  44740. if (this._microSurfaceTexture) {
  44741. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44742. }
  44743. }
  44744. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44745. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44746. }
  44747. }
  44748. // Clip plane
  44749. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44750. // Colors
  44751. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44752. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44753. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44754. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44755. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44756. }
  44757. if (mustRebind || !this.isFrozen) {
  44758. // Lights
  44759. if (scene.lightsEnabled && !this._disableLighting) {
  44760. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44761. }
  44762. // View
  44763. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44764. this.bindView(effect);
  44765. }
  44766. // Fog
  44767. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44768. // Morph targets
  44769. if (defines.NUM_MORPH_INFLUENCERS) {
  44770. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44771. }
  44772. // image processing
  44773. this._imageProcessingConfiguration.bind(this._activeEffect);
  44774. // Log. depth
  44775. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44776. }
  44777. this._uniformBuffer.update();
  44778. this._afterBind(mesh, this._activeEffect);
  44779. };
  44780. /**
  44781. * Returns the animatable textures.
  44782. * @returns - Array of animatable textures.
  44783. */
  44784. PBRBaseMaterial.prototype.getAnimatables = function () {
  44785. var results = [];
  44786. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44787. results.push(this._albedoTexture);
  44788. }
  44789. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44790. results.push(this._ambientTexture);
  44791. }
  44792. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44793. results.push(this._opacityTexture);
  44794. }
  44795. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44796. results.push(this._reflectionTexture);
  44797. }
  44798. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44799. results.push(this._emissiveTexture);
  44800. }
  44801. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44802. results.push(this._metallicTexture);
  44803. }
  44804. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44805. results.push(this._reflectivityTexture);
  44806. }
  44807. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44808. results.push(this._bumpTexture);
  44809. }
  44810. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44811. results.push(this._lightmapTexture);
  44812. }
  44813. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44814. results.push(this._refractionTexture);
  44815. }
  44816. return results;
  44817. };
  44818. /**
  44819. * Returns the texture used for reflections.
  44820. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44821. */
  44822. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44823. if (this._reflectionTexture) {
  44824. return this._reflectionTexture;
  44825. }
  44826. return this.getScene().environmentTexture;
  44827. };
  44828. /**
  44829. * Returns the texture used for refraction or null if none is used.
  44830. * @returns - Refection texture if present. If no refraction texture and refraction
  44831. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44832. */
  44833. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44834. if (this._refractionTexture) {
  44835. return this._refractionTexture;
  44836. }
  44837. if (this._linkRefractionWithTransparency) {
  44838. return this.getScene().environmentTexture;
  44839. }
  44840. return null;
  44841. };
  44842. /**
  44843. * Disposes the resources of the material.
  44844. * @param forceDisposeEffect - Forces the disposal of effects.
  44845. * @param forceDisposeTextures - Forces the disposal of all textures.
  44846. */
  44847. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44848. if (forceDisposeTextures) {
  44849. if (this._albedoTexture) {
  44850. this._albedoTexture.dispose();
  44851. }
  44852. if (this._ambientTexture) {
  44853. this._ambientTexture.dispose();
  44854. }
  44855. if (this._opacityTexture) {
  44856. this._opacityTexture.dispose();
  44857. }
  44858. if (this._reflectionTexture) {
  44859. this._reflectionTexture.dispose();
  44860. }
  44861. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44862. this._environmentBRDFTexture.dispose();
  44863. }
  44864. if (this._emissiveTexture) {
  44865. this._emissiveTexture.dispose();
  44866. }
  44867. if (this._metallicTexture) {
  44868. this._metallicTexture.dispose();
  44869. }
  44870. if (this._reflectivityTexture) {
  44871. this._reflectivityTexture.dispose();
  44872. }
  44873. if (this._bumpTexture) {
  44874. this._bumpTexture.dispose();
  44875. }
  44876. if (this._lightmapTexture) {
  44877. this._lightmapTexture.dispose();
  44878. }
  44879. if (this._refractionTexture) {
  44880. this._refractionTexture.dispose();
  44881. }
  44882. }
  44883. this._renderTargets.dispose();
  44884. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44885. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44886. }
  44887. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44888. };
  44889. /**
  44890. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44891. */
  44892. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44893. /**
  44894. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44895. * to enhance interoperability with other engines.
  44896. */
  44897. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44898. /**
  44899. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44900. * to enhance interoperability with other materials.
  44901. */
  44902. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44903. /**
  44904. * Stores the reflectivity values based on metallic roughness workflow.
  44905. */
  44906. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44907. __decorate([
  44908. BABYLON.serializeAsImageProcessingConfiguration()
  44909. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44910. __decorate([
  44911. BABYLON.serialize()
  44912. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44913. __decorate([
  44914. BABYLON.serialize()
  44915. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44916. return PBRBaseMaterial;
  44917. }(BABYLON.PushMaterial));
  44918. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44919. })(BABYLON || (BABYLON = {}));
  44920. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44921. var BABYLON;
  44922. (function (BABYLON) {
  44923. /**
  44924. * The Physically based simple base material of BJS.
  44925. *
  44926. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44927. * It is used as the base class for both the specGloss and metalRough conventions.
  44928. */
  44929. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44930. __extends(PBRBaseSimpleMaterial, _super);
  44931. /**
  44932. * Instantiates a new PBRMaterial instance.
  44933. *
  44934. * @param name The material name
  44935. * @param scene The scene the material will be use in.
  44936. */
  44937. function PBRBaseSimpleMaterial(name, scene) {
  44938. var _this = _super.call(this, name, scene) || this;
  44939. /**
  44940. * Number of Simultaneous lights allowed on the material.
  44941. */
  44942. _this.maxSimultaneousLights = 4;
  44943. /**
  44944. * If sets to true, disables all the lights affecting the material.
  44945. */
  44946. _this.disableLighting = false;
  44947. /**
  44948. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44949. */
  44950. _this.invertNormalMapX = false;
  44951. /**
  44952. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44953. */
  44954. _this.invertNormalMapY = false;
  44955. /**
  44956. * Emissivie color used to self-illuminate the model.
  44957. */
  44958. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44959. /**
  44960. * Occlusion Channel Strenght.
  44961. */
  44962. _this.occlusionStrength = 1.0;
  44963. _this.useLightmapAsShadowmap = false;
  44964. _this._useAlphaFromAlbedoTexture = true;
  44965. _this._useAmbientInGrayScale = true;
  44966. return _this;
  44967. }
  44968. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44969. /**
  44970. * Gets the current double sided mode.
  44971. */
  44972. get: function () {
  44973. return this._twoSidedLighting;
  44974. },
  44975. /**
  44976. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44977. */
  44978. set: function (value) {
  44979. if (this._twoSidedLighting === value) {
  44980. return;
  44981. }
  44982. this._twoSidedLighting = value;
  44983. this.backFaceCulling = !value;
  44984. this._markAllSubMeshesAsTexturesDirty();
  44985. },
  44986. enumerable: true,
  44987. configurable: true
  44988. });
  44989. /**
  44990. * Return the active textures of the material.
  44991. */
  44992. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44993. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44994. if (this.environmentTexture) {
  44995. activeTextures.push(this.environmentTexture);
  44996. }
  44997. if (this.normalTexture) {
  44998. activeTextures.push(this.normalTexture);
  44999. }
  45000. if (this.emissiveTexture) {
  45001. activeTextures.push(this.emissiveTexture);
  45002. }
  45003. if (this.occlusionTexture) {
  45004. activeTextures.push(this.occlusionTexture);
  45005. }
  45006. if (this.lightmapTexture) {
  45007. activeTextures.push(this.lightmapTexture);
  45008. }
  45009. return activeTextures;
  45010. };
  45011. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45012. if (_super.prototype.hasTexture.call(this, texture)) {
  45013. return true;
  45014. }
  45015. if (this.lightmapTexture === texture) {
  45016. return true;
  45017. }
  45018. return false;
  45019. };
  45020. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45021. return "PBRBaseSimpleMaterial";
  45022. };
  45023. __decorate([
  45024. BABYLON.serialize(),
  45025. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45026. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45027. __decorate([
  45028. BABYLON.serialize(),
  45029. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45030. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45031. __decorate([
  45032. BABYLON.serializeAsTexture(),
  45033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45034. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45035. __decorate([
  45036. BABYLON.serialize(),
  45037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45038. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45039. __decorate([
  45040. BABYLON.serialize(),
  45041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45042. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45043. __decorate([
  45044. BABYLON.serializeAsTexture(),
  45045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45046. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45047. __decorate([
  45048. BABYLON.serializeAsColor3("emissive"),
  45049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45050. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45051. __decorate([
  45052. BABYLON.serializeAsTexture(),
  45053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45054. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45055. __decorate([
  45056. BABYLON.serialize(),
  45057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45058. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45059. __decorate([
  45060. BABYLON.serializeAsTexture(),
  45061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45062. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45063. __decorate([
  45064. BABYLON.serialize(),
  45065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45066. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45067. __decorate([
  45068. BABYLON.serialize()
  45069. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45070. __decorate([
  45071. BABYLON.serializeAsTexture(),
  45072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45073. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45074. __decorate([
  45075. BABYLON.serialize(),
  45076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45077. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45078. return PBRBaseSimpleMaterial;
  45079. }(BABYLON.PBRBaseMaterial));
  45080. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45081. })(BABYLON || (BABYLON = {}));
  45082. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45083. var BABYLON;
  45084. (function (BABYLON) {
  45085. /**
  45086. * The Physically based material of BJS.
  45087. *
  45088. * This offers the main features of a standard PBR material.
  45089. * For more information, please refer to the documentation :
  45090. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45091. */
  45092. var PBRMaterial = /** @class */ (function (_super) {
  45093. __extends(PBRMaterial, _super);
  45094. /**
  45095. * Instantiates a new PBRMaterial instance.
  45096. *
  45097. * @param name The material name
  45098. * @param scene The scene the material will be use in.
  45099. */
  45100. function PBRMaterial(name, scene) {
  45101. var _this = _super.call(this, name, scene) || this;
  45102. /**
  45103. * Intensity of the direct lights e.g. the four lights available in your scene.
  45104. * This impacts both the direct diffuse and specular highlights.
  45105. */
  45106. _this.directIntensity = 1.0;
  45107. /**
  45108. * Intensity of the emissive part of the material.
  45109. * This helps controlling the emissive effect without modifying the emissive color.
  45110. */
  45111. _this.emissiveIntensity = 1.0;
  45112. /**
  45113. * Intensity of the environment e.g. how much the environment will light the object
  45114. * either through harmonics for rough material or through the refelction for shiny ones.
  45115. */
  45116. _this.environmentIntensity = 1.0;
  45117. /**
  45118. * This is a special control allowing the reduction of the specular highlights coming from the
  45119. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45120. */
  45121. _this.specularIntensity = 1.0;
  45122. /**
  45123. * Debug Control allowing disabling the bump map on this material.
  45124. */
  45125. _this.disableBumpMap = false;
  45126. /**
  45127. * AKA Occlusion Texture Intensity in other nomenclature.
  45128. */
  45129. _this.ambientTextureStrength = 1.0;
  45130. /**
  45131. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45132. * 1 means it completely occludes it
  45133. * 0 mean it has no impact
  45134. */
  45135. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45136. /**
  45137. * The color of a material in ambient lighting.
  45138. */
  45139. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45140. /**
  45141. * AKA Diffuse Color in other nomenclature.
  45142. */
  45143. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45144. /**
  45145. * AKA Specular Color in other nomenclature.
  45146. */
  45147. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45148. /**
  45149. * The color reflected from the material.
  45150. */
  45151. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45152. /**
  45153. * The color emitted from the material.
  45154. */
  45155. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45156. /**
  45157. * AKA Glossiness in other nomenclature.
  45158. */
  45159. _this.microSurface = 1.0;
  45160. /**
  45161. * source material index of refraction (IOR)' / 'destination material IOR.
  45162. */
  45163. _this.indexOfRefraction = 0.66;
  45164. /**
  45165. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45166. */
  45167. _this.invertRefractionY = false;
  45168. /**
  45169. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45170. * Materials half opaque for instance using refraction could benefit from this control.
  45171. */
  45172. _this.linkRefractionWithTransparency = false;
  45173. _this.useLightmapAsShadowmap = false;
  45174. /**
  45175. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45176. */
  45177. _this.useAlphaFromAlbedoTexture = false;
  45178. /**
  45179. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45180. */
  45181. _this.forceAlphaTest = false;
  45182. /**
  45183. * Defines the alpha limits in alpha test mode.
  45184. */
  45185. _this.alphaCutOff = 0.4;
  45186. /**
  45187. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45188. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45189. */
  45190. _this.useSpecularOverAlpha = true;
  45191. /**
  45192. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45193. */
  45194. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45195. /**
  45196. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45197. */
  45198. _this.useRoughnessFromMetallicTextureAlpha = true;
  45199. /**
  45200. * Specifies if the metallic texture contains the roughness information in its green channel.
  45201. */
  45202. _this.useRoughnessFromMetallicTextureGreen = false;
  45203. /**
  45204. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45205. */
  45206. _this.useMetallnessFromMetallicTextureBlue = false;
  45207. /**
  45208. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45209. */
  45210. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45211. /**
  45212. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45213. */
  45214. _this.useAmbientInGrayScale = false;
  45215. /**
  45216. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45217. * The material will try to infer what glossiness each pixel should be.
  45218. */
  45219. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45220. /**
  45221. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45222. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45223. */
  45224. _this.useRadianceOverAlpha = true;
  45225. /**
  45226. * Allows using an object space normal map (instead of tangent space).
  45227. */
  45228. _this.useObjectSpaceNormalMap = false;
  45229. /**
  45230. * Allows using the bump map in parallax mode.
  45231. */
  45232. _this.useParallax = false;
  45233. /**
  45234. * Allows using the bump map in parallax occlusion mode.
  45235. */
  45236. _this.useParallaxOcclusion = false;
  45237. /**
  45238. * Controls the scale bias of the parallax mode.
  45239. */
  45240. _this.parallaxScaleBias = 0.05;
  45241. /**
  45242. * If sets to true, disables all the lights affecting the material.
  45243. */
  45244. _this.disableLighting = false;
  45245. /**
  45246. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45247. */
  45248. _this.forceIrradianceInFragment = false;
  45249. /**
  45250. * Number of Simultaneous lights allowed on the material.
  45251. */
  45252. _this.maxSimultaneousLights = 4;
  45253. /**
  45254. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45255. */
  45256. _this.invertNormalMapX = false;
  45257. /**
  45258. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45259. */
  45260. _this.invertNormalMapY = false;
  45261. /**
  45262. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45263. */
  45264. _this.twoSidedLighting = false;
  45265. /**
  45266. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45267. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45268. */
  45269. _this.useAlphaFresnel = false;
  45270. /**
  45271. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45272. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45273. */
  45274. _this.useLinearAlphaFresnel = false;
  45275. /**
  45276. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45277. * And/Or occlude the blended part.
  45278. */
  45279. _this.environmentBRDFTexture = null;
  45280. /**
  45281. * Force normal to face away from face.
  45282. */
  45283. _this.forceNormalForward = false;
  45284. /**
  45285. * Enables specular anti aliasing in the PBR shader.
  45286. * It will both interacts on the Geometry for analytical and IBL lighting.
  45287. * It also prefilter the roughness map based on the bump values.
  45288. */
  45289. _this.enableSpecularAntiAliasing = false;
  45290. /**
  45291. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45292. * makes the reflect vector face the model (under horizon).
  45293. */
  45294. _this.useHorizonOcclusion = true;
  45295. /**
  45296. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45297. * too much the area relying on ambient texture to define their ambient occlusion.
  45298. */
  45299. _this.useRadianceOcclusion = true;
  45300. /**
  45301. * If set to true, no lighting calculations will be applied.
  45302. */
  45303. _this.unlit = false;
  45304. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45305. return _this;
  45306. }
  45307. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45308. /**
  45309. * BJS is using an harcoded light falloff based on a manually sets up range.
  45310. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45311. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45312. */
  45313. get: function () {
  45314. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45315. },
  45316. /**
  45317. * BJS is using an harcoded light falloff based on a manually sets up range.
  45318. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45319. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45320. */
  45321. set: function (value) {
  45322. if (value !== this.usePhysicalLightFalloff) {
  45323. // Ensure the effect will be rebuilt.
  45324. this._markAllSubMeshesAsTexturesDirty();
  45325. if (value) {
  45326. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45327. }
  45328. else {
  45329. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45330. }
  45331. }
  45332. },
  45333. enumerable: true,
  45334. configurable: true
  45335. });
  45336. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45337. /**
  45338. * In order to support the falloff compatibility with gltf, a special mode has been added
  45339. * to reproduce the gltf light falloff.
  45340. */
  45341. get: function () {
  45342. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45343. },
  45344. /**
  45345. * In order to support the falloff compatibility with gltf, a special mode has been added
  45346. * to reproduce the gltf light falloff.
  45347. */
  45348. set: function (value) {
  45349. if (value !== this.useGLTFLightFalloff) {
  45350. // Ensure the effect will be rebuilt.
  45351. this._markAllSubMeshesAsTexturesDirty();
  45352. if (value) {
  45353. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45354. }
  45355. else {
  45356. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45357. }
  45358. }
  45359. },
  45360. enumerable: true,
  45361. configurable: true
  45362. });
  45363. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45364. /**
  45365. * Gets the image processing configuration used either in this material.
  45366. */
  45367. get: function () {
  45368. return this._imageProcessingConfiguration;
  45369. },
  45370. /**
  45371. * Sets the Default image processing configuration used either in the this material.
  45372. *
  45373. * If sets to null, the scene one is in use.
  45374. */
  45375. set: function (value) {
  45376. this._attachImageProcessingConfiguration(value);
  45377. // Ensure the effect will be rebuilt.
  45378. this._markAllSubMeshesAsTexturesDirty();
  45379. },
  45380. enumerable: true,
  45381. configurable: true
  45382. });
  45383. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45384. /**
  45385. * Gets wether the color curves effect is enabled.
  45386. */
  45387. get: function () {
  45388. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45389. },
  45390. /**
  45391. * Sets wether the color curves effect is enabled.
  45392. */
  45393. set: function (value) {
  45394. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45395. },
  45396. enumerable: true,
  45397. configurable: true
  45398. });
  45399. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45400. /**
  45401. * Gets wether the color grading effect is enabled.
  45402. */
  45403. get: function () {
  45404. return this.imageProcessingConfiguration.colorGradingEnabled;
  45405. },
  45406. /**
  45407. * Gets wether the color grading effect is enabled.
  45408. */
  45409. set: function (value) {
  45410. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45411. },
  45412. enumerable: true,
  45413. configurable: true
  45414. });
  45415. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45416. /**
  45417. * Gets wether tonemapping is enabled or not.
  45418. */
  45419. get: function () {
  45420. return this._imageProcessingConfiguration.toneMappingEnabled;
  45421. },
  45422. /**
  45423. * Sets wether tonemapping is enabled or not
  45424. */
  45425. set: function (value) {
  45426. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45427. },
  45428. enumerable: true,
  45429. configurable: true
  45430. });
  45431. ;
  45432. ;
  45433. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45434. /**
  45435. * The camera exposure used on this material.
  45436. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45437. * This corresponds to a photographic exposure.
  45438. */
  45439. get: function () {
  45440. return this._imageProcessingConfiguration.exposure;
  45441. },
  45442. /**
  45443. * The camera exposure used on this material.
  45444. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45445. * This corresponds to a photographic exposure.
  45446. */
  45447. set: function (value) {
  45448. this._imageProcessingConfiguration.exposure = value;
  45449. },
  45450. enumerable: true,
  45451. configurable: true
  45452. });
  45453. ;
  45454. ;
  45455. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45456. /**
  45457. * Gets The camera contrast used on this material.
  45458. */
  45459. get: function () {
  45460. return this._imageProcessingConfiguration.contrast;
  45461. },
  45462. /**
  45463. * Sets The camera contrast used on this material.
  45464. */
  45465. set: function (value) {
  45466. this._imageProcessingConfiguration.contrast = value;
  45467. },
  45468. enumerable: true,
  45469. configurable: true
  45470. });
  45471. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45472. /**
  45473. * Gets the Color Grading 2D Lookup Texture.
  45474. */
  45475. get: function () {
  45476. return this._imageProcessingConfiguration.colorGradingTexture;
  45477. },
  45478. /**
  45479. * Sets the Color Grading 2D Lookup Texture.
  45480. */
  45481. set: function (value) {
  45482. this._imageProcessingConfiguration.colorGradingTexture = value;
  45483. },
  45484. enumerable: true,
  45485. configurable: true
  45486. });
  45487. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45488. /**
  45489. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45490. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45491. * 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;
  45492. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45493. */
  45494. get: function () {
  45495. return this._imageProcessingConfiguration.colorCurves;
  45496. },
  45497. /**
  45498. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45499. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45500. * 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;
  45501. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45502. */
  45503. set: function (value) {
  45504. this._imageProcessingConfiguration.colorCurves = value;
  45505. },
  45506. enumerable: true,
  45507. configurable: true
  45508. });
  45509. /**
  45510. * Returns the name of this material class.
  45511. */
  45512. PBRMaterial.prototype.getClassName = function () {
  45513. return "PBRMaterial";
  45514. };
  45515. /**
  45516. * Returns an array of the actively used textures.
  45517. * @returns - Array of BaseTextures
  45518. */
  45519. PBRMaterial.prototype.getActiveTextures = function () {
  45520. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45521. if (this._albedoTexture) {
  45522. activeTextures.push(this._albedoTexture);
  45523. }
  45524. if (this._ambientTexture) {
  45525. activeTextures.push(this._ambientTexture);
  45526. }
  45527. if (this._opacityTexture) {
  45528. activeTextures.push(this._opacityTexture);
  45529. }
  45530. if (this._reflectionTexture) {
  45531. activeTextures.push(this._reflectionTexture);
  45532. }
  45533. if (this._emissiveTexture) {
  45534. activeTextures.push(this._emissiveTexture);
  45535. }
  45536. if (this._reflectivityTexture) {
  45537. activeTextures.push(this._reflectivityTexture);
  45538. }
  45539. if (this._metallicTexture) {
  45540. activeTextures.push(this._metallicTexture);
  45541. }
  45542. if (this._microSurfaceTexture) {
  45543. activeTextures.push(this._microSurfaceTexture);
  45544. }
  45545. if (this._bumpTexture) {
  45546. activeTextures.push(this._bumpTexture);
  45547. }
  45548. if (this._lightmapTexture) {
  45549. activeTextures.push(this._lightmapTexture);
  45550. }
  45551. if (this._refractionTexture) {
  45552. activeTextures.push(this._refractionTexture);
  45553. }
  45554. return activeTextures;
  45555. };
  45556. /**
  45557. * Checks to see if a texture is used in the material.
  45558. * @param texture - Base texture to use.
  45559. * @returns - Boolean specifying if a texture is used in the material.
  45560. */
  45561. PBRMaterial.prototype.hasTexture = function (texture) {
  45562. if (_super.prototype.hasTexture.call(this, texture)) {
  45563. return true;
  45564. }
  45565. if (this._albedoTexture === texture) {
  45566. return true;
  45567. }
  45568. if (this._ambientTexture === texture) {
  45569. return true;
  45570. }
  45571. if (this._opacityTexture === texture) {
  45572. return true;
  45573. }
  45574. if (this._reflectionTexture === texture) {
  45575. return true;
  45576. }
  45577. if (this._reflectivityTexture === texture) {
  45578. return true;
  45579. }
  45580. if (this._metallicTexture === texture) {
  45581. return true;
  45582. }
  45583. if (this._microSurfaceTexture === texture) {
  45584. return true;
  45585. }
  45586. if (this._bumpTexture === texture) {
  45587. return true;
  45588. }
  45589. if (this._lightmapTexture === texture) {
  45590. return true;
  45591. }
  45592. if (this._refractionTexture === texture) {
  45593. return true;
  45594. }
  45595. return false;
  45596. };
  45597. /**
  45598. * Makes a duplicate of the current material.
  45599. * @param name - name to use for the new material.
  45600. */
  45601. PBRMaterial.prototype.clone = function (name) {
  45602. var _this = this;
  45603. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45604. clone.id = name;
  45605. clone.name = name;
  45606. return clone;
  45607. };
  45608. /**
  45609. * Serializes this PBR Material.
  45610. * @returns - An object with the serialized material.
  45611. */
  45612. PBRMaterial.prototype.serialize = function () {
  45613. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45614. serializationObject.customType = "BABYLON.PBRMaterial";
  45615. return serializationObject;
  45616. };
  45617. // Statics
  45618. /**
  45619. * Parses a PBR Material from a serialized object.
  45620. * @param source - Serialized object.
  45621. * @param scene - BJS scene instance.
  45622. * @param rootUrl - url for the scene object
  45623. * @returns - PBRMaterial
  45624. */
  45625. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45626. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45627. };
  45628. /**
  45629. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45630. */
  45631. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45632. /**
  45633. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45634. */
  45635. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45636. /**
  45637. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45638. */
  45639. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45640. /**
  45641. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45642. * They are also discarded below the alpha cutoff threshold to improve performances.
  45643. */
  45644. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45645. /**
  45646. * Defines the default value of how much AO map is occluding the analytical lights
  45647. * (point spot...).
  45648. */
  45649. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45650. __decorate([
  45651. BABYLON.serialize(),
  45652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45653. ], PBRMaterial.prototype, "directIntensity", void 0);
  45654. __decorate([
  45655. BABYLON.serialize(),
  45656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45657. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45658. __decorate([
  45659. BABYLON.serialize(),
  45660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45661. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45662. __decorate([
  45663. BABYLON.serialize(),
  45664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45665. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45666. __decorate([
  45667. BABYLON.serialize(),
  45668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45669. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45670. __decorate([
  45671. BABYLON.serializeAsTexture(),
  45672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45673. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45674. __decorate([
  45675. BABYLON.serializeAsTexture(),
  45676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45677. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45678. __decorate([
  45679. BABYLON.serialize(),
  45680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45681. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45682. __decorate([
  45683. BABYLON.serialize(),
  45684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45685. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45686. __decorate([
  45687. BABYLON.serializeAsTexture(),
  45688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45689. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45690. __decorate([
  45691. BABYLON.serializeAsTexture(),
  45692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45693. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45694. __decorate([
  45695. BABYLON.serializeAsTexture(),
  45696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45697. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45698. __decorate([
  45699. BABYLON.serializeAsTexture(),
  45700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45701. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45702. __decorate([
  45703. BABYLON.serializeAsTexture(),
  45704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45705. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45706. __decorate([
  45707. BABYLON.serialize(),
  45708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45709. ], PBRMaterial.prototype, "metallic", void 0);
  45710. __decorate([
  45711. BABYLON.serialize(),
  45712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45713. ], PBRMaterial.prototype, "roughness", void 0);
  45714. __decorate([
  45715. BABYLON.serializeAsTexture(),
  45716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45717. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45718. __decorate([
  45719. BABYLON.serializeAsTexture(),
  45720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45721. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45722. __decorate([
  45723. BABYLON.serializeAsTexture(),
  45724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45725. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45726. __decorate([
  45727. BABYLON.serializeAsTexture(),
  45728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45729. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45730. __decorate([
  45731. BABYLON.serializeAsColor3("ambient"),
  45732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45733. ], PBRMaterial.prototype, "ambientColor", void 0);
  45734. __decorate([
  45735. BABYLON.serializeAsColor3("albedo"),
  45736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45737. ], PBRMaterial.prototype, "albedoColor", void 0);
  45738. __decorate([
  45739. BABYLON.serializeAsColor3("reflectivity"),
  45740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45741. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45742. __decorate([
  45743. BABYLON.serializeAsColor3("reflection"),
  45744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45745. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45746. __decorate([
  45747. BABYLON.serializeAsColor3("emissive"),
  45748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45749. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45750. __decorate([
  45751. BABYLON.serialize(),
  45752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45753. ], PBRMaterial.prototype, "microSurface", void 0);
  45754. __decorate([
  45755. BABYLON.serialize(),
  45756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45757. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45758. __decorate([
  45759. BABYLON.serialize(),
  45760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45761. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45762. __decorate([
  45763. BABYLON.serialize(),
  45764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45765. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45766. __decorate([
  45767. BABYLON.serialize(),
  45768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45769. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45770. __decorate([
  45771. BABYLON.serialize(),
  45772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45773. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45774. __decorate([
  45775. BABYLON.serialize(),
  45776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45777. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45778. __decorate([
  45779. BABYLON.serialize(),
  45780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45781. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45782. __decorate([
  45783. BABYLON.serialize(),
  45784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45785. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45786. __decorate([
  45787. BABYLON.serialize(),
  45788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45789. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45790. __decorate([
  45791. BABYLON.serialize(),
  45792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45793. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45794. __decorate([
  45795. BABYLON.serialize(),
  45796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45797. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45798. __decorate([
  45799. BABYLON.serialize(),
  45800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45801. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45802. __decorate([
  45803. BABYLON.serialize(),
  45804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45805. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45806. __decorate([
  45807. BABYLON.serialize(),
  45808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45809. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45810. __decorate([
  45811. BABYLON.serialize(),
  45812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45813. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45814. __decorate([
  45815. BABYLON.serialize()
  45816. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45817. __decorate([
  45818. BABYLON.serialize()
  45819. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45820. __decorate([
  45821. BABYLON.serialize(),
  45822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45823. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45824. __decorate([
  45825. BABYLON.serialize(),
  45826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45827. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45828. __decorate([
  45829. BABYLON.serialize(),
  45830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45831. ], PBRMaterial.prototype, "useParallax", void 0);
  45832. __decorate([
  45833. BABYLON.serialize(),
  45834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45835. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45836. __decorate([
  45837. BABYLON.serialize(),
  45838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45839. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45840. __decorate([
  45841. BABYLON.serialize(),
  45842. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45843. ], PBRMaterial.prototype, "disableLighting", void 0);
  45844. __decorate([
  45845. BABYLON.serialize(),
  45846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45847. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45848. __decorate([
  45849. BABYLON.serialize(),
  45850. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45851. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45852. __decorate([
  45853. BABYLON.serialize(),
  45854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45855. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45856. __decorate([
  45857. BABYLON.serialize(),
  45858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45859. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45860. __decorate([
  45861. BABYLON.serialize(),
  45862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45863. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45864. __decorate([
  45865. BABYLON.serialize(),
  45866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45867. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45868. __decorate([
  45869. BABYLON.serialize(),
  45870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45871. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45872. __decorate([
  45873. BABYLON.serializeAsTexture(),
  45874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45875. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45876. __decorate([
  45877. BABYLON.serialize(),
  45878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45879. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45880. __decorate([
  45881. BABYLON.serialize(),
  45882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45883. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45884. __decorate([
  45885. BABYLON.serialize(),
  45886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45887. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45888. __decorate([
  45889. BABYLON.serialize(),
  45890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45891. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45892. __decorate([
  45893. BABYLON.serialize(),
  45894. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45895. ], PBRMaterial.prototype, "unlit", void 0);
  45896. return PBRMaterial;
  45897. }(BABYLON.PBRBaseMaterial));
  45898. BABYLON.PBRMaterial = PBRMaterial;
  45899. })(BABYLON || (BABYLON = {}));
  45900. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45901. var BABYLON;
  45902. (function (BABYLON) {
  45903. /**
  45904. * The PBR material of BJS following the metal roughness convention.
  45905. *
  45906. * This fits to the PBR convention in the GLTF definition:
  45907. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45908. */
  45909. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45910. __extends(PBRMetallicRoughnessMaterial, _super);
  45911. /**
  45912. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45913. *
  45914. * @param name The material name
  45915. * @param scene The scene the material will be use in.
  45916. */
  45917. function PBRMetallicRoughnessMaterial(name, scene) {
  45918. var _this = _super.call(this, name, scene) || this;
  45919. _this._useRoughnessFromMetallicTextureAlpha = false;
  45920. _this._useRoughnessFromMetallicTextureGreen = true;
  45921. _this._useMetallnessFromMetallicTextureBlue = true;
  45922. _this.metallic = 1.0;
  45923. _this.roughness = 1.0;
  45924. return _this;
  45925. }
  45926. /**
  45927. * Return the currrent class name of the material.
  45928. */
  45929. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45930. return "PBRMetallicRoughnessMaterial";
  45931. };
  45932. /**
  45933. * Return the active textures of the material.
  45934. */
  45935. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45936. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45937. if (this.baseTexture) {
  45938. activeTextures.push(this.baseTexture);
  45939. }
  45940. if (this.metallicRoughnessTexture) {
  45941. activeTextures.push(this.metallicRoughnessTexture);
  45942. }
  45943. return activeTextures;
  45944. };
  45945. /**
  45946. * Checks to see if a texture is used in the material.
  45947. * @param texture - Base texture to use.
  45948. * @returns - Boolean specifying if a texture is used in the material.
  45949. */
  45950. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45951. if (_super.prototype.hasTexture.call(this, texture)) {
  45952. return true;
  45953. }
  45954. if (this.baseTexture === texture) {
  45955. return true;
  45956. }
  45957. if (this.metallicRoughnessTexture === texture) {
  45958. return true;
  45959. }
  45960. return false;
  45961. };
  45962. /**
  45963. * Makes a duplicate of the current material.
  45964. * @param name - name to use for the new material.
  45965. */
  45966. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45967. var _this = this;
  45968. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45969. clone.id = name;
  45970. clone.name = name;
  45971. return clone;
  45972. };
  45973. /**
  45974. * Serialize the material to a parsable JSON object.
  45975. */
  45976. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45977. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45978. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45979. return serializationObject;
  45980. };
  45981. /**
  45982. * Parses a JSON object correponding to the serialize function.
  45983. */
  45984. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45985. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45986. };
  45987. __decorate([
  45988. BABYLON.serializeAsColor3(),
  45989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45990. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45991. __decorate([
  45992. BABYLON.serializeAsTexture(),
  45993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45994. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45995. __decorate([
  45996. BABYLON.serialize(),
  45997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45998. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45999. __decorate([
  46000. BABYLON.serialize(),
  46001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46002. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46003. __decorate([
  46004. BABYLON.serializeAsTexture(),
  46005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46006. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46007. return PBRMetallicRoughnessMaterial;
  46008. }(BABYLON.PBRBaseSimpleMaterial));
  46009. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46010. })(BABYLON || (BABYLON = {}));
  46011. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46012. var BABYLON;
  46013. (function (BABYLON) {
  46014. /**
  46015. * The PBR material of BJS following the specular glossiness convention.
  46016. *
  46017. * This fits to the PBR convention in the GLTF definition:
  46018. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46019. */
  46020. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46021. __extends(PBRSpecularGlossinessMaterial, _super);
  46022. /**
  46023. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46024. *
  46025. * @param name The material name
  46026. * @param scene The scene the material will be use in.
  46027. */
  46028. function PBRSpecularGlossinessMaterial(name, scene) {
  46029. var _this = _super.call(this, name, scene) || this;
  46030. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46031. return _this;
  46032. }
  46033. /**
  46034. * Return the currrent class name of the material.
  46035. */
  46036. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46037. return "PBRSpecularGlossinessMaterial";
  46038. };
  46039. /**
  46040. * Return the active textures of the material.
  46041. */
  46042. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46043. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46044. if (this.diffuseTexture) {
  46045. activeTextures.push(this.diffuseTexture);
  46046. }
  46047. if (this.specularGlossinessTexture) {
  46048. activeTextures.push(this.specularGlossinessTexture);
  46049. }
  46050. return activeTextures;
  46051. };
  46052. /**
  46053. * Checks to see if a texture is used in the material.
  46054. * @param texture - Base texture to use.
  46055. * @returns - Boolean specifying if a texture is used in the material.
  46056. */
  46057. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46058. if (_super.prototype.hasTexture.call(this, texture)) {
  46059. return true;
  46060. }
  46061. if (this.diffuseTexture === texture) {
  46062. return true;
  46063. }
  46064. if (this.specularGlossinessTexture === texture) {
  46065. return true;
  46066. }
  46067. return false;
  46068. };
  46069. /**
  46070. * Makes a duplicate of the current material.
  46071. * @param name - name to use for the new material.
  46072. */
  46073. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46074. var _this = this;
  46075. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46076. clone.id = name;
  46077. clone.name = name;
  46078. return clone;
  46079. };
  46080. /**
  46081. * Serialize the material to a parsable JSON object.
  46082. */
  46083. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46084. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46085. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46086. return serializationObject;
  46087. };
  46088. /**
  46089. * Parses a JSON object correponding to the serialize function.
  46090. */
  46091. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46092. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46093. };
  46094. __decorate([
  46095. BABYLON.serializeAsColor3("diffuse"),
  46096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46097. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46098. __decorate([
  46099. BABYLON.serializeAsTexture(),
  46100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46101. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46102. __decorate([
  46103. BABYLON.serializeAsColor3("specular"),
  46104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46105. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46106. __decorate([
  46107. BABYLON.serialize(),
  46108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46109. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46110. __decorate([
  46111. BABYLON.serializeAsTexture(),
  46112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46113. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46114. return PBRSpecularGlossinessMaterial;
  46115. }(BABYLON.PBRBaseSimpleMaterial));
  46116. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46117. })(BABYLON || (BABYLON = {}));
  46118. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46119. var BABYLON;
  46120. (function (BABYLON) {
  46121. BABYLON.CameraInputTypes = {};
  46122. var CameraInputsManager = /** @class */ (function () {
  46123. function CameraInputsManager(camera) {
  46124. this.attached = {};
  46125. this.camera = camera;
  46126. this.checkInputs = function () { };
  46127. }
  46128. /**
  46129. * Add an input method to a camera
  46130. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46131. * @param input camera input method
  46132. */
  46133. CameraInputsManager.prototype.add = function (input) {
  46134. var type = input.getSimpleName();
  46135. if (this.attached[type]) {
  46136. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46137. return;
  46138. }
  46139. this.attached[type] = input;
  46140. input.camera = this.camera;
  46141. //for checkInputs, we are dynamically creating a function
  46142. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46143. if (input.checkInputs) {
  46144. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46145. }
  46146. if (this.attachedElement) {
  46147. input.attachControl(this.attachedElement);
  46148. }
  46149. };
  46150. /**
  46151. * Remove a specific input method from a camera
  46152. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46153. * @param inputToRemove camera input method
  46154. */
  46155. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46156. for (var cam in this.attached) {
  46157. var input = this.attached[cam];
  46158. if (input === inputToRemove) {
  46159. input.detachControl(this.attachedElement);
  46160. input.camera = null;
  46161. delete this.attached[cam];
  46162. this.rebuildInputCheck();
  46163. }
  46164. }
  46165. };
  46166. CameraInputsManager.prototype.removeByType = function (inputType) {
  46167. for (var cam in this.attached) {
  46168. var input = this.attached[cam];
  46169. if (input.getClassName() === inputType) {
  46170. input.detachControl(this.attachedElement);
  46171. input.camera = null;
  46172. delete this.attached[cam];
  46173. this.rebuildInputCheck();
  46174. }
  46175. }
  46176. };
  46177. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46178. var current = this.checkInputs;
  46179. return function () {
  46180. current();
  46181. fn();
  46182. };
  46183. };
  46184. CameraInputsManager.prototype.attachInput = function (input) {
  46185. if (this.attachedElement) {
  46186. input.attachControl(this.attachedElement, this.noPreventDefault);
  46187. }
  46188. };
  46189. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46190. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46191. if (this.attachedElement) {
  46192. return;
  46193. }
  46194. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46195. this.attachedElement = element;
  46196. this.noPreventDefault = noPreventDefault;
  46197. for (var cam in this.attached) {
  46198. this.attached[cam].attachControl(element, noPreventDefault);
  46199. }
  46200. };
  46201. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46202. if (disconnect === void 0) { disconnect = false; }
  46203. if (this.attachedElement !== element) {
  46204. return;
  46205. }
  46206. for (var cam in this.attached) {
  46207. this.attached[cam].detachControl(element);
  46208. if (disconnect) {
  46209. this.attached[cam].camera = null;
  46210. }
  46211. }
  46212. this.attachedElement = null;
  46213. };
  46214. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46215. this.checkInputs = function () { };
  46216. for (var cam in this.attached) {
  46217. var input = this.attached[cam];
  46218. if (input.checkInputs) {
  46219. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46220. }
  46221. }
  46222. };
  46223. /**
  46224. * Remove all attached input methods from a camera
  46225. */
  46226. CameraInputsManager.prototype.clear = function () {
  46227. if (this.attachedElement) {
  46228. this.detachElement(this.attachedElement, true);
  46229. }
  46230. this.attached = {};
  46231. this.attachedElement = null;
  46232. this.checkInputs = function () { };
  46233. };
  46234. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46235. var inputs = {};
  46236. for (var cam in this.attached) {
  46237. var input = this.attached[cam];
  46238. var res = BABYLON.SerializationHelper.Serialize(input);
  46239. inputs[input.getClassName()] = res;
  46240. }
  46241. serializedCamera.inputsmgr = inputs;
  46242. };
  46243. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46244. var parsedInputs = parsedCamera.inputsmgr;
  46245. if (parsedInputs) {
  46246. this.clear();
  46247. for (var n in parsedInputs) {
  46248. var construct = BABYLON.CameraInputTypes[n];
  46249. if (construct) {
  46250. var parsedinput = parsedInputs[n];
  46251. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46252. this.add(input);
  46253. }
  46254. }
  46255. }
  46256. else {
  46257. //2016-03-08 this part is for managing backward compatibility
  46258. for (var n in this.attached) {
  46259. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46260. if (construct) {
  46261. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46262. this.remove(this.attached[n]);
  46263. this.add(input);
  46264. }
  46265. }
  46266. }
  46267. };
  46268. return CameraInputsManager;
  46269. }());
  46270. BABYLON.CameraInputsManager = CameraInputsManager;
  46271. })(BABYLON || (BABYLON = {}));
  46272. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46273. var BABYLON;
  46274. (function (BABYLON) {
  46275. var TargetCamera = /** @class */ (function (_super) {
  46276. __extends(TargetCamera, _super);
  46277. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46278. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46279. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46280. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46281. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46282. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46283. _this.speed = 2.0;
  46284. _this.noRotationConstraint = false;
  46285. _this.lockedTarget = null;
  46286. /** @hidden */
  46287. _this._currentTarget = BABYLON.Vector3.Zero();
  46288. /** @hidden */
  46289. _this._viewMatrix = BABYLON.Matrix.Zero();
  46290. /** @hidden */
  46291. _this._camMatrix = BABYLON.Matrix.Zero();
  46292. /** @hidden */
  46293. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46294. /** @hidden */
  46295. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46296. /** @hidden */
  46297. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46298. /** @hidden */
  46299. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46300. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46301. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46302. _this._defaultUp = BABYLON.Vector3.Up();
  46303. _this._cachedRotationZ = 0;
  46304. return _this;
  46305. }
  46306. TargetCamera.prototype.getFrontPosition = function (distance) {
  46307. this.getWorldMatrix();
  46308. var direction = this.getTarget().subtract(this.position);
  46309. direction.normalize();
  46310. direction.scaleInPlace(distance);
  46311. return this.globalPosition.add(direction);
  46312. };
  46313. /** @hidden */
  46314. TargetCamera.prototype._getLockedTargetPosition = function () {
  46315. if (!this.lockedTarget) {
  46316. return null;
  46317. }
  46318. if (this.lockedTarget.absolutePosition) {
  46319. this.lockedTarget.computeWorldMatrix();
  46320. }
  46321. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46322. };
  46323. TargetCamera.prototype.storeState = function () {
  46324. this._storedPosition = this.position.clone();
  46325. this._storedRotation = this.rotation.clone();
  46326. if (this.rotationQuaternion) {
  46327. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46328. }
  46329. return _super.prototype.storeState.call(this);
  46330. };
  46331. /**
  46332. * Restored camera state. You must call storeState() first
  46333. * @returns whether it was successful or not
  46334. * @hidden
  46335. */
  46336. TargetCamera.prototype._restoreStateValues = function () {
  46337. if (!_super.prototype._restoreStateValues.call(this)) {
  46338. return false;
  46339. }
  46340. this.position = this._storedPosition.clone();
  46341. this.rotation = this._storedRotation.clone();
  46342. if (this.rotationQuaternion) {
  46343. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46344. }
  46345. this.cameraDirection.copyFromFloats(0, 0, 0);
  46346. this.cameraRotation.copyFromFloats(0, 0);
  46347. return true;
  46348. };
  46349. // Cache
  46350. /** @hidden */
  46351. TargetCamera.prototype._initCache = function () {
  46352. _super.prototype._initCache.call(this);
  46353. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46354. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46355. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46356. };
  46357. /** @hidden */
  46358. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46359. if (!ignoreParentClass) {
  46360. _super.prototype._updateCache.call(this);
  46361. }
  46362. var lockedTargetPosition = this._getLockedTargetPosition();
  46363. if (!lockedTargetPosition) {
  46364. this._cache.lockedTarget = null;
  46365. }
  46366. else {
  46367. if (!this._cache.lockedTarget) {
  46368. this._cache.lockedTarget = lockedTargetPosition.clone();
  46369. }
  46370. else {
  46371. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46372. }
  46373. }
  46374. this._cache.rotation.copyFrom(this.rotation);
  46375. if (this.rotationQuaternion)
  46376. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46377. };
  46378. // Synchronized
  46379. /** @hidden */
  46380. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46381. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46382. return false;
  46383. }
  46384. var lockedTargetPosition = this._getLockedTargetPosition();
  46385. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46386. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46387. };
  46388. // Methods
  46389. /** @hidden */
  46390. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46391. var engine = this.getEngine();
  46392. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46393. };
  46394. // Target
  46395. /** @hidden */
  46396. TargetCamera.prototype.setTarget = function (target) {
  46397. this.upVector.normalize();
  46398. if (this.position.z === target.z) {
  46399. this.position.z += BABYLON.Epsilon;
  46400. }
  46401. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46402. this._camMatrix.invert();
  46403. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46404. var vDir = target.subtract(this.position);
  46405. if (vDir.x >= 0.0) {
  46406. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46407. }
  46408. else {
  46409. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46410. }
  46411. this.rotation.z = 0;
  46412. if (isNaN(this.rotation.x)) {
  46413. this.rotation.x = 0;
  46414. }
  46415. if (isNaN(this.rotation.y)) {
  46416. this.rotation.y = 0;
  46417. }
  46418. if (isNaN(this.rotation.z)) {
  46419. this.rotation.z = 0;
  46420. }
  46421. if (this.rotationQuaternion) {
  46422. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46423. }
  46424. };
  46425. /**
  46426. * Return the current target position of the camera. This value is expressed in local space.
  46427. */
  46428. TargetCamera.prototype.getTarget = function () {
  46429. return this._currentTarget;
  46430. };
  46431. /** @hidden */
  46432. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46433. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46434. };
  46435. /** @hidden */
  46436. TargetCamera.prototype._updatePosition = function () {
  46437. if (this.parent) {
  46438. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46439. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46440. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46441. return;
  46442. }
  46443. this.position.addInPlace(this.cameraDirection);
  46444. };
  46445. /** @hidden */
  46446. TargetCamera.prototype._checkInputs = function () {
  46447. var needToMove = this._decideIfNeedsToMove();
  46448. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46449. // Move
  46450. if (needToMove) {
  46451. this._updatePosition();
  46452. }
  46453. // Rotate
  46454. if (needToRotate) {
  46455. this.rotation.x += this.cameraRotation.x;
  46456. this.rotation.y += this.cameraRotation.y;
  46457. //rotate, if quaternion is set and rotation was used
  46458. if (this.rotationQuaternion) {
  46459. var len = this.rotation.lengthSquared();
  46460. if (len) {
  46461. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46462. }
  46463. }
  46464. if (!this.noRotationConstraint) {
  46465. var limit = (Math.PI / 2) * 0.95;
  46466. if (this.rotation.x > limit)
  46467. this.rotation.x = limit;
  46468. if (this.rotation.x < -limit)
  46469. this.rotation.x = -limit;
  46470. }
  46471. }
  46472. // Inertia
  46473. if (needToMove) {
  46474. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46475. this.cameraDirection.x = 0;
  46476. }
  46477. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46478. this.cameraDirection.y = 0;
  46479. }
  46480. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46481. this.cameraDirection.z = 0;
  46482. }
  46483. this.cameraDirection.scaleInPlace(this.inertia);
  46484. }
  46485. if (needToRotate) {
  46486. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46487. this.cameraRotation.x = 0;
  46488. }
  46489. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46490. this.cameraRotation.y = 0;
  46491. }
  46492. this.cameraRotation.scaleInPlace(this.inertia);
  46493. }
  46494. _super.prototype._checkInputs.call(this);
  46495. };
  46496. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46497. if (this.rotationQuaternion) {
  46498. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46499. }
  46500. else {
  46501. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46502. }
  46503. };
  46504. /**
  46505. * 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)
  46506. * @returns the current camera
  46507. */
  46508. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46509. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46510. return this;
  46511. };
  46512. /** @hidden */
  46513. TargetCamera.prototype._getViewMatrix = function () {
  46514. if (this.lockedTarget) {
  46515. this.setTarget(this._getLockedTargetPosition());
  46516. }
  46517. // Compute
  46518. this._updateCameraRotationMatrix();
  46519. // Apply the changed rotation to the upVector.
  46520. if (this._cachedRotationZ != this.rotation.z) {
  46521. this._rotateUpVectorWithCameraRotationMatrix();
  46522. this._cachedRotationZ = this.rotation.z;
  46523. }
  46524. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46525. // Computing target and final matrix
  46526. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46527. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46528. return this._viewMatrix;
  46529. };
  46530. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46531. if (this.parent) {
  46532. var parentWorldMatrix = this.parent.getWorldMatrix();
  46533. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46534. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46535. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46536. this._markSyncedWithParent();
  46537. }
  46538. else {
  46539. this._globalPosition.copyFrom(position);
  46540. this._globalCurrentTarget.copyFrom(target);
  46541. this._globalCurrentUpVector.copyFrom(up);
  46542. }
  46543. if (this.getScene().useRightHandedSystem) {
  46544. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46545. }
  46546. else {
  46547. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46548. }
  46549. };
  46550. /**
  46551. * @override
  46552. * Override Camera.createRigCamera
  46553. */
  46554. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46555. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46556. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46557. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46558. if (!this.rotationQuaternion) {
  46559. this.rotationQuaternion = new BABYLON.Quaternion();
  46560. }
  46561. rigCamera._cameraRigParams = {};
  46562. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46563. }
  46564. return rigCamera;
  46565. }
  46566. return null;
  46567. };
  46568. /**
  46569. * @hidden
  46570. * @override
  46571. * Override Camera._updateRigCameras
  46572. */
  46573. TargetCamera.prototype._updateRigCameras = function () {
  46574. var camLeft = this._rigCameras[0];
  46575. var camRight = this._rigCameras[1];
  46576. switch (this.cameraRigMode) {
  46577. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46578. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46579. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46580. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46581. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46582. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46583. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46584. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46585. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46586. camLeft.setTarget(this.getTarget());
  46587. camRight.setTarget(this.getTarget());
  46588. break;
  46589. case BABYLON.Camera.RIG_MODE_VR:
  46590. if (camLeft.rotationQuaternion) {
  46591. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46592. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46593. }
  46594. else {
  46595. camLeft.rotation.copyFrom(this.rotation);
  46596. camRight.rotation.copyFrom(this.rotation);
  46597. }
  46598. camLeft.position.copyFrom(this.position);
  46599. camRight.position.copyFrom(this.position);
  46600. break;
  46601. }
  46602. _super.prototype._updateRigCameras.call(this);
  46603. };
  46604. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46605. if (!this._rigCamTransformMatrix) {
  46606. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46607. }
  46608. var target = this.getTarget();
  46609. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46610. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46611. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46612. };
  46613. TargetCamera.prototype.getClassName = function () {
  46614. return "TargetCamera";
  46615. };
  46616. __decorate([
  46617. BABYLON.serializeAsVector3()
  46618. ], TargetCamera.prototype, "rotation", void 0);
  46619. __decorate([
  46620. BABYLON.serialize()
  46621. ], TargetCamera.prototype, "speed", void 0);
  46622. __decorate([
  46623. BABYLON.serializeAsMeshReference("lockedTargetId")
  46624. ], TargetCamera.prototype, "lockedTarget", void 0);
  46625. return TargetCamera;
  46626. }(BABYLON.Camera));
  46627. BABYLON.TargetCamera = TargetCamera;
  46628. })(BABYLON || (BABYLON = {}));
  46629. //# sourceMappingURL=babylon.targetCamera.js.map
  46630. var BABYLON;
  46631. (function (BABYLON) {
  46632. var FreeCameraMouseInput = /** @class */ (function () {
  46633. function FreeCameraMouseInput(touchEnabled) {
  46634. if (touchEnabled === void 0) { touchEnabled = true; }
  46635. this.touchEnabled = touchEnabled;
  46636. this.buttons = [0, 1, 2];
  46637. this.angularSensibility = 2000.0;
  46638. this.previousPosition = null;
  46639. }
  46640. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46641. var _this = this;
  46642. var engine = this.camera.getEngine();
  46643. if (!this._pointerInput) {
  46644. this._pointerInput = function (p, s) {
  46645. var evt = p.event;
  46646. if (engine.isInVRExclusivePointerMode) {
  46647. return;
  46648. }
  46649. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46650. return;
  46651. }
  46652. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46653. return;
  46654. }
  46655. var srcElement = (evt.srcElement || evt.target);
  46656. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46657. try {
  46658. srcElement.setPointerCapture(evt.pointerId);
  46659. }
  46660. catch (e) {
  46661. //Nothing to do with the error. Execution will continue.
  46662. }
  46663. _this.previousPosition = {
  46664. x: evt.clientX,
  46665. y: evt.clientY
  46666. };
  46667. if (!noPreventDefault) {
  46668. evt.preventDefault();
  46669. element.focus();
  46670. }
  46671. }
  46672. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46673. try {
  46674. srcElement.releasePointerCapture(evt.pointerId);
  46675. }
  46676. catch (e) {
  46677. //Nothing to do with the error.
  46678. }
  46679. _this.previousPosition = null;
  46680. if (!noPreventDefault) {
  46681. evt.preventDefault();
  46682. }
  46683. }
  46684. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46685. if (!_this.previousPosition || engine.isPointerLock) {
  46686. return;
  46687. }
  46688. var offsetX = evt.clientX - _this.previousPosition.x;
  46689. if (_this.camera.getScene().useRightHandedSystem)
  46690. offsetX *= -1;
  46691. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46692. offsetX *= -1;
  46693. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46694. var offsetY = evt.clientY - _this.previousPosition.y;
  46695. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46696. _this.previousPosition = {
  46697. x: evt.clientX,
  46698. y: evt.clientY
  46699. };
  46700. if (!noPreventDefault) {
  46701. evt.preventDefault();
  46702. }
  46703. }
  46704. };
  46705. }
  46706. this._onMouseMove = function (evt) {
  46707. if (!engine.isPointerLock) {
  46708. return;
  46709. }
  46710. if (engine.isInVRExclusivePointerMode) {
  46711. return;
  46712. }
  46713. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46714. if (_this.camera.getScene().useRightHandedSystem)
  46715. offsetX *= -1;
  46716. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46717. offsetX *= -1;
  46718. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46719. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46720. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46721. _this.previousPosition = null;
  46722. if (!noPreventDefault) {
  46723. evt.preventDefault();
  46724. }
  46725. };
  46726. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46727. element.addEventListener("mousemove", this._onMouseMove, false);
  46728. };
  46729. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46730. if (this._observer && element) {
  46731. this.camera.getScene().onPointerObservable.remove(this._observer);
  46732. if (this._onMouseMove) {
  46733. element.removeEventListener("mousemove", this._onMouseMove);
  46734. }
  46735. this._observer = null;
  46736. this._onMouseMove = null;
  46737. this.previousPosition = null;
  46738. }
  46739. };
  46740. FreeCameraMouseInput.prototype.getClassName = function () {
  46741. return "FreeCameraMouseInput";
  46742. };
  46743. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46744. return "mouse";
  46745. };
  46746. __decorate([
  46747. BABYLON.serialize()
  46748. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46749. __decorate([
  46750. BABYLON.serialize()
  46751. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46752. return FreeCameraMouseInput;
  46753. }());
  46754. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46755. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46756. })(BABYLON || (BABYLON = {}));
  46757. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46758. var BABYLON;
  46759. (function (BABYLON) {
  46760. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46761. function FreeCameraKeyboardMoveInput() {
  46762. this._keys = new Array();
  46763. this.keysUp = [38];
  46764. this.keysDown = [40];
  46765. this.keysLeft = [37];
  46766. this.keysRight = [39];
  46767. }
  46768. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46769. var _this = this;
  46770. if (this._onCanvasBlurObserver) {
  46771. return;
  46772. }
  46773. this._scene = this.camera.getScene();
  46774. this._engine = this._scene.getEngine();
  46775. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46776. _this._keys = [];
  46777. });
  46778. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46779. var evt = info.event;
  46780. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46781. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46782. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46783. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46784. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46785. var index = _this._keys.indexOf(evt.keyCode);
  46786. if (index === -1) {
  46787. _this._keys.push(evt.keyCode);
  46788. }
  46789. if (!noPreventDefault) {
  46790. evt.preventDefault();
  46791. }
  46792. }
  46793. }
  46794. else {
  46795. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46796. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46797. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46798. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46799. var index = _this._keys.indexOf(evt.keyCode);
  46800. if (index >= 0) {
  46801. _this._keys.splice(index, 1);
  46802. }
  46803. if (!noPreventDefault) {
  46804. evt.preventDefault();
  46805. }
  46806. }
  46807. }
  46808. });
  46809. };
  46810. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46811. if (this._scene) {
  46812. if (this._onKeyboardObserver) {
  46813. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46814. }
  46815. if (this._onCanvasBlurObserver) {
  46816. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46817. }
  46818. this._onKeyboardObserver = null;
  46819. this._onCanvasBlurObserver = null;
  46820. }
  46821. this._keys = [];
  46822. };
  46823. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46824. if (this._onKeyboardObserver) {
  46825. var camera = this.camera;
  46826. // Keyboard
  46827. for (var index = 0; index < this._keys.length; index++) {
  46828. var keyCode = this._keys[index];
  46829. var speed = camera._computeLocalCameraSpeed();
  46830. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46831. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46832. }
  46833. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46834. camera._localDirection.copyFromFloats(0, 0, speed);
  46835. }
  46836. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46837. camera._localDirection.copyFromFloats(speed, 0, 0);
  46838. }
  46839. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46840. camera._localDirection.copyFromFloats(0, 0, -speed);
  46841. }
  46842. if (camera.getScene().useRightHandedSystem) {
  46843. camera._localDirection.z *= -1;
  46844. }
  46845. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46846. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46847. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46848. }
  46849. }
  46850. };
  46851. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46852. return "FreeCameraKeyboardMoveInput";
  46853. };
  46854. /** @hidden */
  46855. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46856. this._keys = [];
  46857. };
  46858. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46859. return "keyboard";
  46860. };
  46861. __decorate([
  46862. BABYLON.serialize()
  46863. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46864. __decorate([
  46865. BABYLON.serialize()
  46866. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46867. __decorate([
  46868. BABYLON.serialize()
  46869. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46870. __decorate([
  46871. BABYLON.serialize()
  46872. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46873. return FreeCameraKeyboardMoveInput;
  46874. }());
  46875. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46876. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46877. })(BABYLON || (BABYLON = {}));
  46878. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46879. var BABYLON;
  46880. (function (BABYLON) {
  46881. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46882. __extends(FreeCameraInputsManager, _super);
  46883. function FreeCameraInputsManager(camera) {
  46884. return _super.call(this, camera) || this;
  46885. }
  46886. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46887. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46888. return this;
  46889. };
  46890. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46891. if (touchEnabled === void 0) { touchEnabled = true; }
  46892. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46893. return this;
  46894. };
  46895. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46896. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46897. return this;
  46898. };
  46899. FreeCameraInputsManager.prototype.addTouch = function () {
  46900. this.add(new BABYLON.FreeCameraTouchInput());
  46901. return this;
  46902. };
  46903. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46904. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46905. return this;
  46906. };
  46907. return FreeCameraInputsManager;
  46908. }(BABYLON.CameraInputsManager));
  46909. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46910. })(BABYLON || (BABYLON = {}));
  46911. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46912. var BABYLON;
  46913. (function (BABYLON) {
  46914. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46915. // Forcing to use the Universal camera
  46916. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46917. });
  46918. var FreeCamera = /** @class */ (function (_super) {
  46919. __extends(FreeCamera, _super);
  46920. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46921. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46922. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46923. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46924. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46925. _this.checkCollisions = false;
  46926. _this.applyGravity = false;
  46927. _this._needMoveForGravity = false;
  46928. _this._oldPosition = BABYLON.Vector3.Zero();
  46929. _this._diffPosition = BABYLON.Vector3.Zero();
  46930. _this._newPosition = BABYLON.Vector3.Zero();
  46931. // Collisions
  46932. _this._collisionMask = -1;
  46933. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46934. if (collidedMesh === void 0) { collidedMesh = null; }
  46935. //TODO move this to the collision coordinator!
  46936. if (_this.getScene().workerCollisions)
  46937. newPosition.multiplyInPlace(_this._collider._radius);
  46938. var updatePosition = function (newPos) {
  46939. _this._newPosition.copyFrom(newPos);
  46940. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46941. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46942. _this.position.addInPlace(_this._diffPosition);
  46943. if (_this.onCollide && collidedMesh) {
  46944. _this.onCollide(collidedMesh);
  46945. }
  46946. }
  46947. };
  46948. updatePosition(newPosition);
  46949. };
  46950. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46951. _this.inputs.addKeyboard().addMouse();
  46952. return _this;
  46953. }
  46954. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46955. //-- begin properties for backward compatibility for inputs
  46956. /**
  46957. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46958. * Higher values reduce sensitivity.
  46959. */
  46960. get: function () {
  46961. var mouse = this.inputs.attached["mouse"];
  46962. if (mouse)
  46963. return mouse.angularSensibility;
  46964. return 0;
  46965. },
  46966. /**
  46967. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46968. * Higher values reduce sensitivity.
  46969. */
  46970. set: function (value) {
  46971. var mouse = this.inputs.attached["mouse"];
  46972. if (mouse)
  46973. mouse.angularSensibility = value;
  46974. },
  46975. enumerable: true,
  46976. configurable: true
  46977. });
  46978. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46979. get: function () {
  46980. var keyboard = this.inputs.attached["keyboard"];
  46981. if (keyboard)
  46982. return keyboard.keysUp;
  46983. return [];
  46984. },
  46985. set: function (value) {
  46986. var keyboard = this.inputs.attached["keyboard"];
  46987. if (keyboard)
  46988. keyboard.keysUp = value;
  46989. },
  46990. enumerable: true,
  46991. configurable: true
  46992. });
  46993. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46994. get: function () {
  46995. var keyboard = this.inputs.attached["keyboard"];
  46996. if (keyboard)
  46997. return keyboard.keysDown;
  46998. return [];
  46999. },
  47000. set: function (value) {
  47001. var keyboard = this.inputs.attached["keyboard"];
  47002. if (keyboard)
  47003. keyboard.keysDown = value;
  47004. },
  47005. enumerable: true,
  47006. configurable: true
  47007. });
  47008. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47009. get: function () {
  47010. var keyboard = this.inputs.attached["keyboard"];
  47011. if (keyboard)
  47012. return keyboard.keysLeft;
  47013. return [];
  47014. },
  47015. set: function (value) {
  47016. var keyboard = this.inputs.attached["keyboard"];
  47017. if (keyboard)
  47018. keyboard.keysLeft = value;
  47019. },
  47020. enumerable: true,
  47021. configurable: true
  47022. });
  47023. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47024. get: function () {
  47025. var keyboard = this.inputs.attached["keyboard"];
  47026. if (keyboard)
  47027. return keyboard.keysRight;
  47028. return [];
  47029. },
  47030. set: function (value) {
  47031. var keyboard = this.inputs.attached["keyboard"];
  47032. if (keyboard)
  47033. keyboard.keysRight = value;
  47034. },
  47035. enumerable: true,
  47036. configurable: true
  47037. });
  47038. // Controls
  47039. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47040. this.inputs.attachElement(element, noPreventDefault);
  47041. };
  47042. FreeCamera.prototype.detachControl = function (element) {
  47043. this.inputs.detachElement(element);
  47044. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47045. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47046. };
  47047. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47048. get: function () {
  47049. return this._collisionMask;
  47050. },
  47051. set: function (mask) {
  47052. this._collisionMask = !isNaN(mask) ? mask : -1;
  47053. },
  47054. enumerable: true,
  47055. configurable: true
  47056. });
  47057. /** @hidden */
  47058. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47059. var globalPosition;
  47060. if (this.parent) {
  47061. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47062. }
  47063. else {
  47064. globalPosition = this.position;
  47065. }
  47066. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47067. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47068. if (!this._collider) {
  47069. this._collider = new BABYLON.Collider();
  47070. }
  47071. this._collider._radius = this.ellipsoid;
  47072. this._collider.collisionMask = this._collisionMask;
  47073. //no need for clone, as long as gravity is not on.
  47074. var actualDisplacement = displacement;
  47075. //add gravity to the direction to prevent the dual-collision checking
  47076. if (this.applyGravity) {
  47077. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47078. actualDisplacement = displacement.add(this.getScene().gravity);
  47079. }
  47080. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47081. };
  47082. /** @hidden */
  47083. FreeCamera.prototype._checkInputs = function () {
  47084. if (!this._localDirection) {
  47085. this._localDirection = BABYLON.Vector3.Zero();
  47086. this._transformedDirection = BABYLON.Vector3.Zero();
  47087. }
  47088. this.inputs.checkInputs();
  47089. _super.prototype._checkInputs.call(this);
  47090. };
  47091. /** @hidden */
  47092. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47093. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47094. };
  47095. /** @hidden */
  47096. FreeCamera.prototype._updatePosition = function () {
  47097. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47098. this._collideWithWorld(this.cameraDirection);
  47099. }
  47100. else {
  47101. _super.prototype._updatePosition.call(this);
  47102. }
  47103. };
  47104. FreeCamera.prototype.dispose = function () {
  47105. this.inputs.clear();
  47106. _super.prototype.dispose.call(this);
  47107. };
  47108. FreeCamera.prototype.getClassName = function () {
  47109. return "FreeCamera";
  47110. };
  47111. __decorate([
  47112. BABYLON.serializeAsVector3()
  47113. ], FreeCamera.prototype, "ellipsoid", void 0);
  47114. __decorate([
  47115. BABYLON.serializeAsVector3()
  47116. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47117. __decorate([
  47118. BABYLON.serialize()
  47119. ], FreeCamera.prototype, "checkCollisions", void 0);
  47120. __decorate([
  47121. BABYLON.serialize()
  47122. ], FreeCamera.prototype, "applyGravity", void 0);
  47123. return FreeCamera;
  47124. }(BABYLON.TargetCamera));
  47125. BABYLON.FreeCamera = FreeCamera;
  47126. })(BABYLON || (BABYLON = {}));
  47127. //# sourceMappingURL=babylon.freeCamera.js.map
  47128. var BABYLON;
  47129. (function (BABYLON) {
  47130. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47131. function ArcRotateCameraKeyboardMoveInput() {
  47132. this._keys = new Array();
  47133. this.keysUp = [38];
  47134. this.keysDown = [40];
  47135. this.keysLeft = [37];
  47136. this.keysRight = [39];
  47137. this.keysReset = [220];
  47138. this.panningSensibility = 50.0;
  47139. this.zoomingSensibility = 25.0;
  47140. this.useAltToZoom = true;
  47141. }
  47142. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47143. var _this = this;
  47144. if (this._onCanvasBlurObserver) {
  47145. return;
  47146. }
  47147. this._scene = this.camera.getScene();
  47148. this._engine = this._scene.getEngine();
  47149. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47150. _this._keys = [];
  47151. });
  47152. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47153. var evt = info.event;
  47154. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47155. _this._ctrlPressed = evt.ctrlKey;
  47156. _this._altPressed = evt.altKey;
  47157. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47158. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47159. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47160. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47161. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47162. var index = _this._keys.indexOf(evt.keyCode);
  47163. if (index === -1) {
  47164. _this._keys.push(evt.keyCode);
  47165. }
  47166. if (evt.preventDefault) {
  47167. if (!noPreventDefault) {
  47168. evt.preventDefault();
  47169. }
  47170. }
  47171. }
  47172. }
  47173. else {
  47174. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47175. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47176. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47177. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47178. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47179. var index = _this._keys.indexOf(evt.keyCode);
  47180. if (index >= 0) {
  47181. _this._keys.splice(index, 1);
  47182. }
  47183. if (evt.preventDefault) {
  47184. if (!noPreventDefault) {
  47185. evt.preventDefault();
  47186. }
  47187. }
  47188. }
  47189. }
  47190. });
  47191. };
  47192. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47193. if (this._scene) {
  47194. if (this._onKeyboardObserver) {
  47195. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47196. }
  47197. if (this._onCanvasBlurObserver) {
  47198. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47199. }
  47200. this._onKeyboardObserver = null;
  47201. this._onCanvasBlurObserver = null;
  47202. }
  47203. this._keys = [];
  47204. };
  47205. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47206. if (this._onKeyboardObserver) {
  47207. var camera = this.camera;
  47208. for (var index = 0; index < this._keys.length; index++) {
  47209. var keyCode = this._keys[index];
  47210. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47211. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47212. camera.inertialPanningX -= 1 / this.panningSensibility;
  47213. }
  47214. else {
  47215. camera.inertialAlphaOffset -= 0.01;
  47216. }
  47217. }
  47218. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47219. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47220. camera.inertialPanningY += 1 / this.panningSensibility;
  47221. }
  47222. else if (this._altPressed && this.useAltToZoom) {
  47223. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47224. }
  47225. else {
  47226. camera.inertialBetaOffset -= 0.01;
  47227. }
  47228. }
  47229. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47230. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47231. camera.inertialPanningX += 1 / this.panningSensibility;
  47232. }
  47233. else {
  47234. camera.inertialAlphaOffset += 0.01;
  47235. }
  47236. }
  47237. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47238. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47239. camera.inertialPanningY -= 1 / this.panningSensibility;
  47240. }
  47241. else if (this._altPressed && this.useAltToZoom) {
  47242. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47243. }
  47244. else {
  47245. camera.inertialBetaOffset += 0.01;
  47246. }
  47247. }
  47248. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47249. camera.restoreState();
  47250. }
  47251. }
  47252. }
  47253. };
  47254. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47255. return "ArcRotateCameraKeyboardMoveInput";
  47256. };
  47257. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47258. return "keyboard";
  47259. };
  47260. __decorate([
  47261. BABYLON.serialize()
  47262. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47263. __decorate([
  47264. BABYLON.serialize()
  47265. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47266. __decorate([
  47267. BABYLON.serialize()
  47268. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47269. __decorate([
  47270. BABYLON.serialize()
  47271. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47272. __decorate([
  47273. BABYLON.serialize()
  47274. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47275. __decorate([
  47276. BABYLON.serialize()
  47277. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47278. __decorate([
  47279. BABYLON.serialize()
  47280. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47281. __decorate([
  47282. BABYLON.serialize()
  47283. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47284. return ArcRotateCameraKeyboardMoveInput;
  47285. }());
  47286. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47287. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47288. })(BABYLON || (BABYLON = {}));
  47289. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47290. var BABYLON;
  47291. (function (BABYLON) {
  47292. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47293. function ArcRotateCameraMouseWheelInput() {
  47294. this.wheelPrecision = 3.0;
  47295. /**
  47296. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47297. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47298. */
  47299. this.wheelDeltaPercentage = 0;
  47300. }
  47301. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47302. var _this = this;
  47303. this._wheel = function (p, s) {
  47304. //sanity check - this should be a PointerWheel event.
  47305. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47306. return;
  47307. var event = p.event;
  47308. var delta = 0;
  47309. if (event.wheelDelta) {
  47310. if (_this.wheelDeltaPercentage) {
  47311. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47312. if (event.wheelDelta > 0) {
  47313. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47314. }
  47315. else {
  47316. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47317. }
  47318. }
  47319. else {
  47320. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47321. }
  47322. }
  47323. else if (event.detail) {
  47324. delta = -event.detail / _this.wheelPrecision;
  47325. }
  47326. if (delta)
  47327. _this.camera.inertialRadiusOffset += delta;
  47328. if (event.preventDefault) {
  47329. if (!noPreventDefault) {
  47330. event.preventDefault();
  47331. }
  47332. }
  47333. };
  47334. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47335. };
  47336. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47337. if (this._observer && element) {
  47338. this.camera.getScene().onPointerObservable.remove(this._observer);
  47339. this._observer = null;
  47340. this._wheel = null;
  47341. }
  47342. };
  47343. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47344. return "ArcRotateCameraMouseWheelInput";
  47345. };
  47346. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47347. return "mousewheel";
  47348. };
  47349. __decorate([
  47350. BABYLON.serialize()
  47351. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47352. __decorate([
  47353. BABYLON.serialize()
  47354. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47355. return ArcRotateCameraMouseWheelInput;
  47356. }());
  47357. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47358. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47359. })(BABYLON || (BABYLON = {}));
  47360. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47361. var BABYLON;
  47362. (function (BABYLON) {
  47363. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47364. function ArcRotateCameraPointersInput() {
  47365. this.buttons = [0, 1, 2];
  47366. this.angularSensibilityX = 1000.0;
  47367. this.angularSensibilityY = 1000.0;
  47368. this.pinchPrecision = 12.0;
  47369. /**
  47370. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47371. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47372. */
  47373. this.pinchDeltaPercentage = 0;
  47374. this.panningSensibility = 1000.0;
  47375. this.multiTouchPanning = true;
  47376. this.multiTouchPanAndZoom = true;
  47377. this._isPanClick = false;
  47378. this.pinchInwards = true;
  47379. }
  47380. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47381. var _this = this;
  47382. var engine = this.camera.getEngine();
  47383. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47384. var pointA = null;
  47385. var pointB = null;
  47386. var previousPinchSquaredDistance = 0;
  47387. var initialDistance = 0;
  47388. var twoFingerActivityCount = 0;
  47389. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47390. this._pointerInput = function (p, s) {
  47391. var evt = p.event;
  47392. var isTouch = p.event.pointerType === "touch";
  47393. if (engine.isInVRExclusivePointerMode) {
  47394. return;
  47395. }
  47396. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47397. return;
  47398. }
  47399. var srcElement = (evt.srcElement || evt.target);
  47400. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47401. try {
  47402. srcElement.setPointerCapture(evt.pointerId);
  47403. }
  47404. catch (e) {
  47405. //Nothing to do with the error. Execution will continue.
  47406. }
  47407. // Manage panning with pan button click
  47408. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47409. // manage pointers
  47410. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47411. if (pointA === null) {
  47412. pointA = cacheSoloPointer;
  47413. }
  47414. else if (pointB === null) {
  47415. pointB = cacheSoloPointer;
  47416. }
  47417. if (!noPreventDefault) {
  47418. evt.preventDefault();
  47419. element.focus();
  47420. }
  47421. }
  47422. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47423. _this.camera.restoreState();
  47424. }
  47425. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47426. try {
  47427. srcElement.releasePointerCapture(evt.pointerId);
  47428. }
  47429. catch (e) {
  47430. //Nothing to do with the error.
  47431. }
  47432. cacheSoloPointer = null;
  47433. previousPinchSquaredDistance = 0;
  47434. previousMultiTouchPanPosition.isPaning = false;
  47435. previousMultiTouchPanPosition.isPinching = false;
  47436. twoFingerActivityCount = 0;
  47437. initialDistance = 0;
  47438. if (!isTouch) {
  47439. pointB = null; // Mouse and pen are mono pointer
  47440. }
  47441. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47442. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47443. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47444. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47445. if (engine._badOS) {
  47446. pointA = pointB = null;
  47447. }
  47448. else {
  47449. //only remove the impacted pointer in case of multitouch allowing on most
  47450. //platforms switching from rotate to zoom and pan seamlessly.
  47451. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47452. pointA = pointB;
  47453. pointB = null;
  47454. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47455. }
  47456. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47457. pointB = null;
  47458. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47459. }
  47460. else {
  47461. pointA = pointB = null;
  47462. }
  47463. }
  47464. if (!noPreventDefault) {
  47465. evt.preventDefault();
  47466. }
  47467. }
  47468. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47469. if (!noPreventDefault) {
  47470. evt.preventDefault();
  47471. }
  47472. // One button down
  47473. if (pointA && pointB === null && cacheSoloPointer) {
  47474. if (_this.panningSensibility !== 0 &&
  47475. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47476. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47477. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47478. }
  47479. else {
  47480. var offsetX = evt.clientX - cacheSoloPointer.x;
  47481. var offsetY = evt.clientY - cacheSoloPointer.y;
  47482. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47483. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47484. }
  47485. cacheSoloPointer.x = evt.clientX;
  47486. cacheSoloPointer.y = evt.clientY;
  47487. }
  47488. // Two buttons down: pinch/pan
  47489. else if (pointA && pointB) {
  47490. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47491. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47492. ed.x = evt.clientX;
  47493. ed.y = evt.clientY;
  47494. var direction = _this.pinchInwards ? 1 : -1;
  47495. var distX = pointA.x - pointB.x;
  47496. var distY = pointA.y - pointB.y;
  47497. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47498. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47499. if (previousPinchSquaredDistance === 0) {
  47500. initialDistance = pinchDistance;
  47501. previousPinchSquaredDistance = pinchSquaredDistance;
  47502. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47503. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47504. return;
  47505. }
  47506. if (_this.multiTouchPanAndZoom) {
  47507. if (_this.pinchDeltaPercentage) {
  47508. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47509. }
  47510. else {
  47511. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47512. (_this.pinchPrecision *
  47513. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47514. direction);
  47515. }
  47516. if (_this.panningSensibility !== 0) {
  47517. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47518. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47519. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47520. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47521. previousMultiTouchPanPosition.x = pointersCenterX;
  47522. previousMultiTouchPanPosition.y = pointersCenterY;
  47523. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47524. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47525. }
  47526. }
  47527. else {
  47528. twoFingerActivityCount++;
  47529. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47530. if (_this.pinchDeltaPercentage) {
  47531. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47532. }
  47533. else {
  47534. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47535. (_this.pinchPrecision *
  47536. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47537. direction);
  47538. }
  47539. previousMultiTouchPanPosition.isPaning = false;
  47540. previousMultiTouchPanPosition.isPinching = true;
  47541. }
  47542. else {
  47543. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47544. if (!previousMultiTouchPanPosition.isPaning) {
  47545. previousMultiTouchPanPosition.isPaning = true;
  47546. previousMultiTouchPanPosition.isPinching = false;
  47547. previousMultiTouchPanPosition.x = ed.x;
  47548. previousMultiTouchPanPosition.y = ed.y;
  47549. return;
  47550. }
  47551. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47552. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47553. }
  47554. }
  47555. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47556. previousMultiTouchPanPosition.x = ed.x;
  47557. previousMultiTouchPanPosition.y = ed.y;
  47558. }
  47559. }
  47560. previousPinchSquaredDistance = pinchSquaredDistance;
  47561. }
  47562. }
  47563. };
  47564. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47565. this._onContextMenu = function (evt) {
  47566. evt.preventDefault();
  47567. };
  47568. if (!this.camera._useCtrlForPanning) {
  47569. element.addEventListener("contextmenu", this._onContextMenu, false);
  47570. }
  47571. this._onLostFocus = function () {
  47572. //this._keys = [];
  47573. pointA = pointB = null;
  47574. previousPinchSquaredDistance = 0;
  47575. previousMultiTouchPanPosition.isPaning = false;
  47576. previousMultiTouchPanPosition.isPinching = false;
  47577. twoFingerActivityCount = 0;
  47578. cacheSoloPointer = null;
  47579. initialDistance = 0;
  47580. };
  47581. this._onMouseMove = function (evt) {
  47582. if (!engine.isPointerLock) {
  47583. return;
  47584. }
  47585. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47586. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47587. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47588. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47589. if (!noPreventDefault) {
  47590. evt.preventDefault();
  47591. }
  47592. };
  47593. this._onGestureStart = function (e) {
  47594. if (window.MSGesture === undefined) {
  47595. return;
  47596. }
  47597. if (!_this._MSGestureHandler) {
  47598. _this._MSGestureHandler = new MSGesture();
  47599. _this._MSGestureHandler.target = element;
  47600. }
  47601. _this._MSGestureHandler.addPointer(e.pointerId);
  47602. };
  47603. this._onGesture = function (e) {
  47604. _this.camera.radius *= e.scale;
  47605. if (e.preventDefault) {
  47606. if (!noPreventDefault) {
  47607. e.stopPropagation();
  47608. e.preventDefault();
  47609. }
  47610. }
  47611. };
  47612. element.addEventListener("mousemove", this._onMouseMove, false);
  47613. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47614. element.addEventListener("MSGestureChange", this._onGesture, false);
  47615. BABYLON.Tools.RegisterTopRootEvents([
  47616. { name: "blur", handler: this._onLostFocus }
  47617. ]);
  47618. };
  47619. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47620. if (this._onLostFocus) {
  47621. BABYLON.Tools.UnregisterTopRootEvents([
  47622. { name: "blur", handler: this._onLostFocus }
  47623. ]);
  47624. }
  47625. if (element && this._observer) {
  47626. this.camera.getScene().onPointerObservable.remove(this._observer);
  47627. this._observer = null;
  47628. if (this._onContextMenu) {
  47629. element.removeEventListener("contextmenu", this._onContextMenu);
  47630. }
  47631. if (this._onMouseMove) {
  47632. element.removeEventListener("mousemove", this._onMouseMove);
  47633. }
  47634. if (this._onGestureStart) {
  47635. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47636. }
  47637. if (this._onGesture) {
  47638. element.removeEventListener("MSGestureChange", this._onGesture);
  47639. }
  47640. this._isPanClick = false;
  47641. this.pinchInwards = true;
  47642. this._onMouseMove = null;
  47643. this._onGestureStart = null;
  47644. this._onGesture = null;
  47645. this._MSGestureHandler = null;
  47646. this._onLostFocus = null;
  47647. this._onContextMenu = null;
  47648. }
  47649. };
  47650. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47651. return "ArcRotateCameraPointersInput";
  47652. };
  47653. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47654. return "pointers";
  47655. };
  47656. __decorate([
  47657. BABYLON.serialize()
  47658. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47659. __decorate([
  47660. BABYLON.serialize()
  47661. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47662. __decorate([
  47663. BABYLON.serialize()
  47664. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47665. __decorate([
  47666. BABYLON.serialize()
  47667. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47668. __decorate([
  47669. BABYLON.serialize()
  47670. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47671. __decorate([
  47672. BABYLON.serialize()
  47673. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47674. __decorate([
  47675. BABYLON.serialize()
  47676. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47677. __decorate([
  47678. BABYLON.serialize()
  47679. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47680. return ArcRotateCameraPointersInput;
  47681. }());
  47682. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47683. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47684. })(BABYLON || (BABYLON = {}));
  47685. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47686. var BABYLON;
  47687. (function (BABYLON) {
  47688. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47689. __extends(ArcRotateCameraInputsManager, _super);
  47690. function ArcRotateCameraInputsManager(camera) {
  47691. return _super.call(this, camera) || this;
  47692. }
  47693. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47694. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47695. return this;
  47696. };
  47697. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47698. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47699. return this;
  47700. };
  47701. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47702. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47703. return this;
  47704. };
  47705. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47706. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47707. return this;
  47708. };
  47709. return ArcRotateCameraInputsManager;
  47710. }(BABYLON.CameraInputsManager));
  47711. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47712. })(BABYLON || (BABYLON = {}));
  47713. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47714. var BABYLON;
  47715. (function (BABYLON) {
  47716. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47717. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47718. });
  47719. var ArcRotateCamera = /** @class */ (function (_super) {
  47720. __extends(ArcRotateCamera, _super);
  47721. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47722. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47723. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47724. _this.inertialAlphaOffset = 0;
  47725. _this.inertialBetaOffset = 0;
  47726. _this.inertialRadiusOffset = 0;
  47727. _this.lowerAlphaLimit = null;
  47728. _this.upperAlphaLimit = null;
  47729. _this.lowerBetaLimit = 0.01;
  47730. _this.upperBetaLimit = Math.PI;
  47731. _this.lowerRadiusLimit = null;
  47732. _this.upperRadiusLimit = null;
  47733. _this.inertialPanningX = 0;
  47734. _this.inertialPanningY = 0;
  47735. _this.pinchToPanMaxDistance = 20;
  47736. _this.panningDistanceLimit = null;
  47737. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47738. _this.panningInertia = 0.9;
  47739. //-- end properties for backward compatibility for inputs
  47740. _this.zoomOnFactor = 1;
  47741. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47742. _this.allowUpsideDown = true;
  47743. /** @hidden */
  47744. _this._viewMatrix = new BABYLON.Matrix();
  47745. // Panning
  47746. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47747. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47748. _this.checkCollisions = false;
  47749. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47750. _this._previousPosition = BABYLON.Vector3.Zero();
  47751. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47752. _this._newPosition = BABYLON.Vector3.Zero();
  47753. _this._computationVector = BABYLON.Vector3.Zero();
  47754. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47755. if (collidedMesh === void 0) { collidedMesh = null; }
  47756. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47757. newPosition.multiplyInPlace(_this._collider._radius);
  47758. }
  47759. if (!collidedMesh) {
  47760. _this._previousPosition.copyFrom(_this.position);
  47761. }
  47762. else {
  47763. _this.setPosition(newPosition);
  47764. if (_this.onCollide) {
  47765. _this.onCollide(collidedMesh);
  47766. }
  47767. }
  47768. // Recompute because of constraints
  47769. var cosa = Math.cos(_this.alpha);
  47770. var sina = Math.sin(_this.alpha);
  47771. var cosb = Math.cos(_this.beta);
  47772. var sinb = Math.sin(_this.beta);
  47773. if (sinb === 0) {
  47774. sinb = 0.0001;
  47775. }
  47776. var target = _this._getTargetPosition();
  47777. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47778. target.addToRef(_this._computationVector, _this._newPosition);
  47779. _this.position.copyFrom(_this._newPosition);
  47780. var up = _this.upVector;
  47781. if (_this.allowUpsideDown && _this.beta < 0) {
  47782. up = up.clone();
  47783. up = up.negate();
  47784. }
  47785. _this._computeViewMatrix(_this.position, target, up);
  47786. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47787. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47788. _this._collisionTriggered = false;
  47789. };
  47790. _this._target = BABYLON.Vector3.Zero();
  47791. if (target) {
  47792. _this.setTarget(target);
  47793. }
  47794. _this.alpha = alpha;
  47795. _this.beta = beta;
  47796. _this.radius = radius;
  47797. _this.getViewMatrix();
  47798. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47799. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47800. return _this;
  47801. }
  47802. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47803. get: function () {
  47804. return this._target;
  47805. },
  47806. set: function (value) {
  47807. this.setTarget(value);
  47808. },
  47809. enumerable: true,
  47810. configurable: true
  47811. });
  47812. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47813. //-- begin properties for backward compatibility for inputs
  47814. get: function () {
  47815. var pointers = this.inputs.attached["pointers"];
  47816. if (pointers)
  47817. return pointers.angularSensibilityX;
  47818. return 0;
  47819. },
  47820. set: function (value) {
  47821. var pointers = this.inputs.attached["pointers"];
  47822. if (pointers) {
  47823. pointers.angularSensibilityX = value;
  47824. }
  47825. },
  47826. enumerable: true,
  47827. configurable: true
  47828. });
  47829. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47830. get: function () {
  47831. var pointers = this.inputs.attached["pointers"];
  47832. if (pointers)
  47833. return pointers.angularSensibilityY;
  47834. return 0;
  47835. },
  47836. set: function (value) {
  47837. var pointers = this.inputs.attached["pointers"];
  47838. if (pointers) {
  47839. pointers.angularSensibilityY = value;
  47840. }
  47841. },
  47842. enumerable: true,
  47843. configurable: true
  47844. });
  47845. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47846. get: function () {
  47847. var pointers = this.inputs.attached["pointers"];
  47848. if (pointers)
  47849. return pointers.pinchPrecision;
  47850. return 0;
  47851. },
  47852. set: function (value) {
  47853. var pointers = this.inputs.attached["pointers"];
  47854. if (pointers) {
  47855. pointers.pinchPrecision = value;
  47856. }
  47857. },
  47858. enumerable: true,
  47859. configurable: true
  47860. });
  47861. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47862. get: function () {
  47863. var pointers = this.inputs.attached["pointers"];
  47864. if (pointers)
  47865. return pointers.pinchDeltaPercentage;
  47866. return 0;
  47867. },
  47868. set: function (value) {
  47869. var pointers = this.inputs.attached["pointers"];
  47870. if (pointers) {
  47871. pointers.pinchDeltaPercentage = value;
  47872. }
  47873. },
  47874. enumerable: true,
  47875. configurable: true
  47876. });
  47877. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47878. get: function () {
  47879. var pointers = this.inputs.attached["pointers"];
  47880. if (pointers)
  47881. return pointers.panningSensibility;
  47882. return 0;
  47883. },
  47884. set: function (value) {
  47885. var pointers = this.inputs.attached["pointers"];
  47886. if (pointers) {
  47887. pointers.panningSensibility = value;
  47888. }
  47889. },
  47890. enumerable: true,
  47891. configurable: true
  47892. });
  47893. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47894. get: function () {
  47895. var keyboard = this.inputs.attached["keyboard"];
  47896. if (keyboard)
  47897. return keyboard.keysUp;
  47898. return [];
  47899. },
  47900. set: function (value) {
  47901. var keyboard = this.inputs.attached["keyboard"];
  47902. if (keyboard)
  47903. keyboard.keysUp = value;
  47904. },
  47905. enumerable: true,
  47906. configurable: true
  47907. });
  47908. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47909. get: function () {
  47910. var keyboard = this.inputs.attached["keyboard"];
  47911. if (keyboard)
  47912. return keyboard.keysDown;
  47913. return [];
  47914. },
  47915. set: function (value) {
  47916. var keyboard = this.inputs.attached["keyboard"];
  47917. if (keyboard)
  47918. keyboard.keysDown = value;
  47919. },
  47920. enumerable: true,
  47921. configurable: true
  47922. });
  47923. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47924. get: function () {
  47925. var keyboard = this.inputs.attached["keyboard"];
  47926. if (keyboard)
  47927. return keyboard.keysLeft;
  47928. return [];
  47929. },
  47930. set: function (value) {
  47931. var keyboard = this.inputs.attached["keyboard"];
  47932. if (keyboard)
  47933. keyboard.keysLeft = value;
  47934. },
  47935. enumerable: true,
  47936. configurable: true
  47937. });
  47938. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47939. get: function () {
  47940. var keyboard = this.inputs.attached["keyboard"];
  47941. if (keyboard)
  47942. return keyboard.keysRight;
  47943. return [];
  47944. },
  47945. set: function (value) {
  47946. var keyboard = this.inputs.attached["keyboard"];
  47947. if (keyboard)
  47948. keyboard.keysRight = value;
  47949. },
  47950. enumerable: true,
  47951. configurable: true
  47952. });
  47953. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47954. get: function () {
  47955. var mousewheel = this.inputs.attached["mousewheel"];
  47956. if (mousewheel)
  47957. return mousewheel.wheelPrecision;
  47958. return 0;
  47959. },
  47960. set: function (value) {
  47961. var mousewheel = this.inputs.attached["mousewheel"];
  47962. if (mousewheel)
  47963. mousewheel.wheelPrecision = value;
  47964. },
  47965. enumerable: true,
  47966. configurable: true
  47967. });
  47968. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47969. get: function () {
  47970. var mousewheel = this.inputs.attached["mousewheel"];
  47971. if (mousewheel)
  47972. return mousewheel.wheelDeltaPercentage;
  47973. return 0;
  47974. },
  47975. set: function (value) {
  47976. var mousewheel = this.inputs.attached["mousewheel"];
  47977. if (mousewheel)
  47978. mousewheel.wheelDeltaPercentage = value;
  47979. },
  47980. enumerable: true,
  47981. configurable: true
  47982. });
  47983. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47984. get: function () {
  47985. return this._bouncingBehavior;
  47986. },
  47987. enumerable: true,
  47988. configurable: true
  47989. });
  47990. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47991. get: function () {
  47992. return this._bouncingBehavior != null;
  47993. },
  47994. set: function (value) {
  47995. if (value === this.useBouncingBehavior) {
  47996. return;
  47997. }
  47998. if (value) {
  47999. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48000. this.addBehavior(this._bouncingBehavior);
  48001. }
  48002. else if (this._bouncingBehavior) {
  48003. this.removeBehavior(this._bouncingBehavior);
  48004. this._bouncingBehavior = null;
  48005. }
  48006. },
  48007. enumerable: true,
  48008. configurable: true
  48009. });
  48010. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48011. get: function () {
  48012. return this._framingBehavior;
  48013. },
  48014. enumerable: true,
  48015. configurable: true
  48016. });
  48017. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48018. get: function () {
  48019. return this._framingBehavior != null;
  48020. },
  48021. set: function (value) {
  48022. if (value === this.useFramingBehavior) {
  48023. return;
  48024. }
  48025. if (value) {
  48026. this._framingBehavior = new BABYLON.FramingBehavior();
  48027. this.addBehavior(this._framingBehavior);
  48028. }
  48029. else if (this._framingBehavior) {
  48030. this.removeBehavior(this._framingBehavior);
  48031. this._framingBehavior = null;
  48032. }
  48033. },
  48034. enumerable: true,
  48035. configurable: true
  48036. });
  48037. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48038. get: function () {
  48039. return this._autoRotationBehavior;
  48040. },
  48041. enumerable: true,
  48042. configurable: true
  48043. });
  48044. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48045. get: function () {
  48046. return this._autoRotationBehavior != null;
  48047. },
  48048. set: function (value) {
  48049. if (value === this.useAutoRotationBehavior) {
  48050. return;
  48051. }
  48052. if (value) {
  48053. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48054. this.addBehavior(this._autoRotationBehavior);
  48055. }
  48056. else if (this._autoRotationBehavior) {
  48057. this.removeBehavior(this._autoRotationBehavior);
  48058. this._autoRotationBehavior = null;
  48059. }
  48060. },
  48061. enumerable: true,
  48062. configurable: true
  48063. });
  48064. // Cache
  48065. /** @hidden */
  48066. ArcRotateCamera.prototype._initCache = function () {
  48067. _super.prototype._initCache.call(this);
  48068. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48069. this._cache.alpha = undefined;
  48070. this._cache.beta = undefined;
  48071. this._cache.radius = undefined;
  48072. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48073. };
  48074. /** @hidden */
  48075. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48076. if (!ignoreParentClass) {
  48077. _super.prototype._updateCache.call(this);
  48078. }
  48079. this._cache._target.copyFrom(this._getTargetPosition());
  48080. this._cache.alpha = this.alpha;
  48081. this._cache.beta = this.beta;
  48082. this._cache.radius = this.radius;
  48083. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48084. };
  48085. ArcRotateCamera.prototype._getTargetPosition = function () {
  48086. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48087. var pos = this._targetHost.getAbsolutePosition();
  48088. if (this._targetBoundingCenter) {
  48089. pos.addToRef(this._targetBoundingCenter, this._target);
  48090. }
  48091. else {
  48092. this._target.copyFrom(pos);
  48093. }
  48094. }
  48095. var lockedTargetPosition = this._getLockedTargetPosition();
  48096. if (lockedTargetPosition) {
  48097. return lockedTargetPosition;
  48098. }
  48099. return this._target;
  48100. };
  48101. ArcRotateCamera.prototype.storeState = function () {
  48102. this._storedAlpha = this.alpha;
  48103. this._storedBeta = this.beta;
  48104. this._storedRadius = this.radius;
  48105. this._storedTarget = this._getTargetPosition().clone();
  48106. return _super.prototype.storeState.call(this);
  48107. };
  48108. /**
  48109. * @hidden
  48110. * Restored camera state. You must call storeState() first
  48111. */
  48112. ArcRotateCamera.prototype._restoreStateValues = function () {
  48113. if (!_super.prototype._restoreStateValues.call(this)) {
  48114. return false;
  48115. }
  48116. this.alpha = this._storedAlpha;
  48117. this.beta = this._storedBeta;
  48118. this.radius = this._storedRadius;
  48119. this.setTarget(this._storedTarget.clone());
  48120. this.inertialAlphaOffset = 0;
  48121. this.inertialBetaOffset = 0;
  48122. this.inertialRadiusOffset = 0;
  48123. this.inertialPanningX = 0;
  48124. this.inertialPanningY = 0;
  48125. return true;
  48126. };
  48127. // Synchronized
  48128. /** @hidden */
  48129. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48130. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48131. return false;
  48132. return this._cache._target.equals(this._getTargetPosition())
  48133. && this._cache.alpha === this.alpha
  48134. && this._cache.beta === this.beta
  48135. && this._cache.radius === this.radius
  48136. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48137. };
  48138. // Methods
  48139. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48140. var _this = this;
  48141. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48142. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48143. this._useCtrlForPanning = useCtrlForPanning;
  48144. this._panningMouseButton = panningMouseButton;
  48145. this.inputs.attachElement(element, noPreventDefault);
  48146. this._reset = function () {
  48147. _this.inertialAlphaOffset = 0;
  48148. _this.inertialBetaOffset = 0;
  48149. _this.inertialRadiusOffset = 0;
  48150. _this.inertialPanningX = 0;
  48151. _this.inertialPanningY = 0;
  48152. };
  48153. };
  48154. ArcRotateCamera.prototype.detachControl = function (element) {
  48155. this.inputs.detachElement(element);
  48156. if (this._reset) {
  48157. this._reset();
  48158. }
  48159. };
  48160. /** @hidden */
  48161. ArcRotateCamera.prototype._checkInputs = function () {
  48162. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48163. if (this._collisionTriggered) {
  48164. return;
  48165. }
  48166. this.inputs.checkInputs();
  48167. // Inertia
  48168. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48169. var inertialAlphaOffset = this.inertialAlphaOffset;
  48170. if (this.beta <= 0)
  48171. inertialAlphaOffset *= -1;
  48172. if (this.getScene().useRightHandedSystem)
  48173. inertialAlphaOffset *= -1;
  48174. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48175. inertialAlphaOffset *= -1;
  48176. this.alpha += inertialAlphaOffset;
  48177. this.beta += this.inertialBetaOffset;
  48178. this.radius -= this.inertialRadiusOffset;
  48179. this.inertialAlphaOffset *= this.inertia;
  48180. this.inertialBetaOffset *= this.inertia;
  48181. this.inertialRadiusOffset *= this.inertia;
  48182. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48183. this.inertialAlphaOffset = 0;
  48184. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48185. this.inertialBetaOffset = 0;
  48186. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48187. this.inertialRadiusOffset = 0;
  48188. }
  48189. // Panning inertia
  48190. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48191. if (!this._localDirection) {
  48192. this._localDirection = BABYLON.Vector3.Zero();
  48193. this._transformedDirection = BABYLON.Vector3.Zero();
  48194. }
  48195. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48196. this._localDirection.multiplyInPlace(this.panningAxis);
  48197. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48198. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48199. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48200. if (!this.panningAxis.y) {
  48201. this._transformedDirection.y = 0;
  48202. }
  48203. if (!this._targetHost) {
  48204. if (this.panningDistanceLimit) {
  48205. this._transformedDirection.addInPlace(this._target);
  48206. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48207. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48208. this._target.copyFrom(this._transformedDirection);
  48209. }
  48210. }
  48211. else {
  48212. this._target.addInPlace(this._transformedDirection);
  48213. }
  48214. }
  48215. this.inertialPanningX *= this.panningInertia;
  48216. this.inertialPanningY *= this.panningInertia;
  48217. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48218. this.inertialPanningX = 0;
  48219. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48220. this.inertialPanningY = 0;
  48221. }
  48222. // Limits
  48223. this._checkLimits();
  48224. _super.prototype._checkInputs.call(this);
  48225. };
  48226. ArcRotateCamera.prototype._checkLimits = function () {
  48227. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48228. if (this.allowUpsideDown && this.beta > Math.PI) {
  48229. this.beta = this.beta - (2 * Math.PI);
  48230. }
  48231. }
  48232. else {
  48233. if (this.beta < this.lowerBetaLimit) {
  48234. this.beta = this.lowerBetaLimit;
  48235. }
  48236. }
  48237. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48238. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48239. this.beta = this.beta + (2 * Math.PI);
  48240. }
  48241. }
  48242. else {
  48243. if (this.beta > this.upperBetaLimit) {
  48244. this.beta = this.upperBetaLimit;
  48245. }
  48246. }
  48247. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48248. this.alpha = this.lowerAlphaLimit;
  48249. }
  48250. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48251. this.alpha = this.upperAlphaLimit;
  48252. }
  48253. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48254. this.radius = this.lowerRadiusLimit;
  48255. }
  48256. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48257. this.radius = this.upperRadiusLimit;
  48258. }
  48259. };
  48260. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48261. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48262. this.radius = this._computationVector.length();
  48263. if (this.radius === 0) {
  48264. this.radius = 0.0001; // Just to avoid division by zero
  48265. }
  48266. // Alpha
  48267. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48268. if (this._computationVector.z < 0) {
  48269. this.alpha = 2 * Math.PI - this.alpha;
  48270. }
  48271. // Beta
  48272. this.beta = Math.acos(this._computationVector.y / this.radius);
  48273. this._checkLimits();
  48274. };
  48275. ArcRotateCamera.prototype.setPosition = function (position) {
  48276. if (this.position.equals(position)) {
  48277. return;
  48278. }
  48279. this.position.copyFrom(position);
  48280. this.rebuildAnglesAndRadius();
  48281. };
  48282. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48283. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48284. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48285. if (target.getBoundingInfo) {
  48286. if (toBoundingCenter) {
  48287. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48288. }
  48289. else {
  48290. this._targetBoundingCenter = null;
  48291. }
  48292. this._targetHost = target;
  48293. this._target = this._getTargetPosition();
  48294. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48295. }
  48296. else {
  48297. var newTarget = target;
  48298. var currentTarget = this._getTargetPosition();
  48299. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48300. return;
  48301. }
  48302. this._targetHost = null;
  48303. this._target = newTarget;
  48304. this._targetBoundingCenter = null;
  48305. this.onMeshTargetChangedObservable.notifyObservers(null);
  48306. }
  48307. this.rebuildAnglesAndRadius();
  48308. };
  48309. /** @hidden */
  48310. ArcRotateCamera.prototype._getViewMatrix = function () {
  48311. // Compute
  48312. var cosa = Math.cos(this.alpha);
  48313. var sina = Math.sin(this.alpha);
  48314. var cosb = Math.cos(this.beta);
  48315. var sinb = Math.sin(this.beta);
  48316. if (sinb === 0) {
  48317. sinb = 0.0001;
  48318. }
  48319. var target = this._getTargetPosition();
  48320. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48321. target.addToRef(this._computationVector, this._newPosition);
  48322. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48323. if (!this._collider) {
  48324. this._collider = new BABYLON.Collider();
  48325. }
  48326. this._collider._radius = this.collisionRadius;
  48327. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48328. this._collisionTriggered = true;
  48329. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48330. }
  48331. else {
  48332. this.position.copyFrom(this._newPosition);
  48333. var up = this.upVector;
  48334. if (this.allowUpsideDown && sinb < 0) {
  48335. up = up.clone();
  48336. up = up.negate();
  48337. }
  48338. this._computeViewMatrix(this.position, target, up);
  48339. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48340. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48341. }
  48342. this._currentTarget = target;
  48343. return this._viewMatrix;
  48344. };
  48345. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48346. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48347. meshes = meshes || this.getScene().meshes;
  48348. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48349. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48350. this.radius = distance * this.zoomOnFactor;
  48351. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48352. };
  48353. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48354. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48355. var meshesOrMinMaxVector;
  48356. var distance;
  48357. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48358. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48359. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48360. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48361. }
  48362. else { //minMaxVector and distance
  48363. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48364. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48365. distance = minMaxVectorAndDistance.distance;
  48366. }
  48367. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48368. if (!doNotUpdateMaxZ) {
  48369. this.maxZ = distance * 2;
  48370. }
  48371. };
  48372. /**
  48373. * @override
  48374. * Override Camera.createRigCamera
  48375. */
  48376. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48377. var alphaShift = 0;
  48378. switch (this.cameraRigMode) {
  48379. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48380. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48381. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48382. case BABYLON.Camera.RIG_MODE_VR:
  48383. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48384. break;
  48385. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48386. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48387. break;
  48388. }
  48389. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48390. rigCam._cameraRigParams = {};
  48391. return rigCam;
  48392. };
  48393. /**
  48394. * @hidden
  48395. * @override
  48396. * Override Camera._updateRigCameras
  48397. */
  48398. ArcRotateCamera.prototype._updateRigCameras = function () {
  48399. var camLeft = this._rigCameras[0];
  48400. var camRight = this._rigCameras[1];
  48401. camLeft.beta = camRight.beta = this.beta;
  48402. camLeft.radius = camRight.radius = this.radius;
  48403. switch (this.cameraRigMode) {
  48404. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48405. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48406. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48407. case BABYLON.Camera.RIG_MODE_VR:
  48408. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48409. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48410. break;
  48411. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48412. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48413. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48414. break;
  48415. }
  48416. _super.prototype._updateRigCameras.call(this);
  48417. };
  48418. ArcRotateCamera.prototype.dispose = function () {
  48419. this.inputs.clear();
  48420. _super.prototype.dispose.call(this);
  48421. };
  48422. ArcRotateCamera.prototype.getClassName = function () {
  48423. return "ArcRotateCamera";
  48424. };
  48425. __decorate([
  48426. BABYLON.serialize()
  48427. ], ArcRotateCamera.prototype, "alpha", void 0);
  48428. __decorate([
  48429. BABYLON.serialize()
  48430. ], ArcRotateCamera.prototype, "beta", void 0);
  48431. __decorate([
  48432. BABYLON.serialize()
  48433. ], ArcRotateCamera.prototype, "radius", void 0);
  48434. __decorate([
  48435. BABYLON.serializeAsVector3("target")
  48436. ], ArcRotateCamera.prototype, "_target", void 0);
  48437. __decorate([
  48438. BABYLON.serialize()
  48439. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48440. __decorate([
  48441. BABYLON.serialize()
  48442. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48443. __decorate([
  48444. BABYLON.serialize()
  48445. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48446. __decorate([
  48447. BABYLON.serialize()
  48448. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48449. __decorate([
  48450. BABYLON.serialize()
  48451. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48452. __decorate([
  48453. BABYLON.serialize()
  48454. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48455. __decorate([
  48456. BABYLON.serialize()
  48457. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48458. __decorate([
  48459. BABYLON.serialize()
  48460. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48461. __decorate([
  48462. BABYLON.serialize()
  48463. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48464. __decorate([
  48465. BABYLON.serialize()
  48466. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48467. __decorate([
  48468. BABYLON.serialize()
  48469. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48470. __decorate([
  48471. BABYLON.serialize()
  48472. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48473. __decorate([
  48474. BABYLON.serialize()
  48475. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48476. __decorate([
  48477. BABYLON.serializeAsVector3()
  48478. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48479. __decorate([
  48480. BABYLON.serialize()
  48481. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48482. __decorate([
  48483. BABYLON.serialize()
  48484. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48485. __decorate([
  48486. BABYLON.serialize()
  48487. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48488. return ArcRotateCamera;
  48489. }(BABYLON.TargetCamera));
  48490. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48491. })(BABYLON || (BABYLON = {}));
  48492. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48493. var BABYLON;
  48494. (function (BABYLON) {
  48495. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48496. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48497. });
  48498. /**
  48499. * The HemisphericLight simulates the ambient environment light,
  48500. * so the passed direction is the light reflection direction, not the incoming direction.
  48501. */
  48502. var HemisphericLight = /** @class */ (function (_super) {
  48503. __extends(HemisphericLight, _super);
  48504. /**
  48505. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48506. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48507. * The HemisphericLight can't cast shadows.
  48508. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48509. * @param name The friendly name of the light
  48510. * @param direction The direction of the light reflection
  48511. * @param scene The scene the light belongs to
  48512. */
  48513. function HemisphericLight(name, direction, scene) {
  48514. var _this = _super.call(this, name, scene) || this;
  48515. /**
  48516. * The groundColor is the light in the opposite direction to the one specified during creation.
  48517. * 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.
  48518. */
  48519. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48520. _this.direction = direction || BABYLON.Vector3.Up();
  48521. return _this;
  48522. }
  48523. HemisphericLight.prototype._buildUniformLayout = function () {
  48524. this._uniformBuffer.addUniform("vLightData", 4);
  48525. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48526. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48527. this._uniformBuffer.addUniform("vLightGround", 3);
  48528. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48529. this._uniformBuffer.addUniform("depthValues", 2);
  48530. this._uniformBuffer.create();
  48531. };
  48532. /**
  48533. * Returns the string "HemisphericLight".
  48534. * @return The class name
  48535. */
  48536. HemisphericLight.prototype.getClassName = function () {
  48537. return "HemisphericLight";
  48538. };
  48539. /**
  48540. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48541. * Returns the updated direction.
  48542. * @param target The target the direction should point to
  48543. * @return The computed direction
  48544. */
  48545. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48546. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48547. return this.direction;
  48548. };
  48549. /**
  48550. * Returns the shadow generator associated to the light.
  48551. * @returns Always null for hemispheric lights because it does not support shadows.
  48552. */
  48553. HemisphericLight.prototype.getShadowGenerator = function () {
  48554. return null;
  48555. };
  48556. /**
  48557. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48558. * @param effect The effect to update
  48559. * @param lightIndex The index of the light in the effect to update
  48560. * @returns The hemispheric light
  48561. */
  48562. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48563. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48564. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48565. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48566. return this;
  48567. };
  48568. /**
  48569. * @hidden internal use only.
  48570. */
  48571. HemisphericLight.prototype._getWorldMatrix = function () {
  48572. if (!this._worldMatrix) {
  48573. this._worldMatrix = BABYLON.Matrix.Identity();
  48574. }
  48575. return this._worldMatrix;
  48576. };
  48577. /**
  48578. * Returns the integer 3.
  48579. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48580. */
  48581. HemisphericLight.prototype.getTypeID = function () {
  48582. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48583. };
  48584. /**
  48585. * Prepares the list of defines specific to the light type.
  48586. * @param defines the list of defines
  48587. * @param lightIndex defines the index of the light for the effect
  48588. */
  48589. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48590. defines["HEMILIGHT" + lightIndex] = true;
  48591. };
  48592. __decorate([
  48593. BABYLON.serializeAsColor3()
  48594. ], HemisphericLight.prototype, "groundColor", void 0);
  48595. __decorate([
  48596. BABYLON.serializeAsVector3()
  48597. ], HemisphericLight.prototype, "direction", void 0);
  48598. return HemisphericLight;
  48599. }(BABYLON.Light));
  48600. BABYLON.HemisphericLight = HemisphericLight;
  48601. })(BABYLON || (BABYLON = {}));
  48602. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48603. var BABYLON;
  48604. (function (BABYLON) {
  48605. /**
  48606. * Base implementation IShadowLight
  48607. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48608. */
  48609. var ShadowLight = /** @class */ (function (_super) {
  48610. __extends(ShadowLight, _super);
  48611. function ShadowLight() {
  48612. var _this = _super !== null && _super.apply(this, arguments) || this;
  48613. _this._needProjectionMatrixCompute = true;
  48614. return _this;
  48615. }
  48616. ShadowLight.prototype._setPosition = function (value) {
  48617. this._position = value;
  48618. };
  48619. Object.defineProperty(ShadowLight.prototype, "position", {
  48620. /**
  48621. * Sets the position the shadow will be casted from. Also use as the light position for both
  48622. * point and spot lights.
  48623. */
  48624. get: function () {
  48625. return this._position;
  48626. },
  48627. /**
  48628. * Sets the position the shadow will be casted from. Also use as the light position for both
  48629. * point and spot lights.
  48630. */
  48631. set: function (value) {
  48632. this._setPosition(value);
  48633. },
  48634. enumerable: true,
  48635. configurable: true
  48636. });
  48637. ShadowLight.prototype._setDirection = function (value) {
  48638. this._direction = value;
  48639. };
  48640. Object.defineProperty(ShadowLight.prototype, "direction", {
  48641. /**
  48642. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48643. * Also use as the light direction on spot and directional lights.
  48644. */
  48645. get: function () {
  48646. return this._direction;
  48647. },
  48648. /**
  48649. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48650. * Also use as the light direction on spot and directional lights.
  48651. */
  48652. set: function (value) {
  48653. this._setDirection(value);
  48654. },
  48655. enumerable: true,
  48656. configurable: true
  48657. });
  48658. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48659. /**
  48660. * Gets the shadow projection clipping minimum z value.
  48661. */
  48662. get: function () {
  48663. return this._shadowMinZ;
  48664. },
  48665. /**
  48666. * Sets the shadow projection clipping minimum z value.
  48667. */
  48668. set: function (value) {
  48669. this._shadowMinZ = value;
  48670. this.forceProjectionMatrixCompute();
  48671. },
  48672. enumerable: true,
  48673. configurable: true
  48674. });
  48675. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48676. /**
  48677. * Sets the shadow projection clipping maximum z value.
  48678. */
  48679. get: function () {
  48680. return this._shadowMaxZ;
  48681. },
  48682. /**
  48683. * Gets the shadow projection clipping maximum z value.
  48684. */
  48685. set: function (value) {
  48686. this._shadowMaxZ = value;
  48687. this.forceProjectionMatrixCompute();
  48688. },
  48689. enumerable: true,
  48690. configurable: true
  48691. });
  48692. /**
  48693. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48694. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48695. */
  48696. ShadowLight.prototype.computeTransformedInformation = function () {
  48697. if (this.parent && this.parent.getWorldMatrix) {
  48698. if (!this.transformedPosition) {
  48699. this.transformedPosition = BABYLON.Vector3.Zero();
  48700. }
  48701. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48702. // In case the direction is present.
  48703. if (this.direction) {
  48704. if (!this.transformedDirection) {
  48705. this.transformedDirection = BABYLON.Vector3.Zero();
  48706. }
  48707. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48708. }
  48709. return true;
  48710. }
  48711. return false;
  48712. };
  48713. /**
  48714. * Return the depth scale used for the shadow map.
  48715. * @returns the depth scale.
  48716. */
  48717. ShadowLight.prototype.getDepthScale = function () {
  48718. return 50.0;
  48719. };
  48720. /**
  48721. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48722. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48723. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48724. */
  48725. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48726. return this.transformedDirection ? this.transformedDirection : this.direction;
  48727. };
  48728. /**
  48729. * Returns the ShadowLight absolute position in the World.
  48730. * @returns the position vector in world space
  48731. */
  48732. ShadowLight.prototype.getAbsolutePosition = function () {
  48733. return this.transformedPosition ? this.transformedPosition : this.position;
  48734. };
  48735. /**
  48736. * Sets the ShadowLight direction toward the passed target.
  48737. * @param target The point tot target in local space
  48738. * @returns the updated ShadowLight direction
  48739. */
  48740. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48741. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48742. return this.direction;
  48743. };
  48744. /**
  48745. * Returns the light rotation in euler definition.
  48746. * @returns the x y z rotation in local space.
  48747. */
  48748. ShadowLight.prototype.getRotation = function () {
  48749. this.direction.normalize();
  48750. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48751. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48752. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48753. };
  48754. /**
  48755. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48756. * @returns true if a cube texture needs to be use
  48757. */
  48758. ShadowLight.prototype.needCube = function () {
  48759. return false;
  48760. };
  48761. /**
  48762. * Detects if the projection matrix requires to be recomputed this frame.
  48763. * @returns true if it requires to be recomputed otherwise, false.
  48764. */
  48765. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48766. return this._needProjectionMatrixCompute;
  48767. };
  48768. /**
  48769. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48770. */
  48771. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48772. this._needProjectionMatrixCompute = true;
  48773. };
  48774. /**
  48775. * Get the world matrix of the sahdow lights.
  48776. * @hidden Internal Use Only
  48777. */
  48778. ShadowLight.prototype._getWorldMatrix = function () {
  48779. if (!this._worldMatrix) {
  48780. this._worldMatrix = BABYLON.Matrix.Identity();
  48781. }
  48782. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48783. return this._worldMatrix;
  48784. };
  48785. /**
  48786. * Gets the minZ used for shadow according to both the scene and the light.
  48787. * @param activeCamera The camera we are returning the min for
  48788. * @returns the depth min z
  48789. */
  48790. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48791. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48792. };
  48793. /**
  48794. * Gets the maxZ used for shadow according to both the scene and the light.
  48795. * @param activeCamera The camera we are returning the max for
  48796. * @returns the depth max z
  48797. */
  48798. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48799. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48800. };
  48801. /**
  48802. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48803. * @param matrix The materix to updated with the projection information
  48804. * @param viewMatrix The transform matrix of the light
  48805. * @param renderList The list of mesh to render in the map
  48806. * @returns The current light
  48807. */
  48808. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48809. if (this.customProjectionMatrixBuilder) {
  48810. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48811. }
  48812. else {
  48813. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48814. }
  48815. return this;
  48816. };
  48817. __decorate([
  48818. BABYLON.serializeAsVector3()
  48819. ], ShadowLight.prototype, "position", null);
  48820. __decorate([
  48821. BABYLON.serializeAsVector3()
  48822. ], ShadowLight.prototype, "direction", null);
  48823. __decorate([
  48824. BABYLON.serialize()
  48825. ], ShadowLight.prototype, "shadowMinZ", null);
  48826. __decorate([
  48827. BABYLON.serialize()
  48828. ], ShadowLight.prototype, "shadowMaxZ", null);
  48829. return ShadowLight;
  48830. }(BABYLON.Light));
  48831. BABYLON.ShadowLight = ShadowLight;
  48832. })(BABYLON || (BABYLON = {}));
  48833. //# sourceMappingURL=babylon.shadowLight.js.map
  48834. var BABYLON;
  48835. (function (BABYLON) {
  48836. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48837. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48838. });
  48839. /**
  48840. * A point light is a light defined by an unique point in world space.
  48841. * The light is emitted in every direction from this point.
  48842. * A good example of a point light is a standard light bulb.
  48843. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48844. */
  48845. var PointLight = /** @class */ (function (_super) {
  48846. __extends(PointLight, _super);
  48847. /**
  48848. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48849. * A PointLight emits the light in every direction.
  48850. * It can cast shadows.
  48851. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48852. * ```javascript
  48853. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48854. * ```
  48855. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48856. * @param name The light friendly name
  48857. * @param position The position of the point light in the scene
  48858. * @param scene The scene the lights belongs to
  48859. */
  48860. function PointLight(name, position, scene) {
  48861. var _this = _super.call(this, name, scene) || this;
  48862. _this._shadowAngle = Math.PI / 2;
  48863. _this.position = position;
  48864. return _this;
  48865. }
  48866. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48867. /**
  48868. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48869. * This specifies what angle the shadow will use to be created.
  48870. *
  48871. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48872. */
  48873. get: function () {
  48874. return this._shadowAngle;
  48875. },
  48876. /**
  48877. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48878. * This specifies what angle the shadow will use to be created.
  48879. *
  48880. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48881. */
  48882. set: function (value) {
  48883. this._shadowAngle = value;
  48884. this.forceProjectionMatrixCompute();
  48885. },
  48886. enumerable: true,
  48887. configurable: true
  48888. });
  48889. Object.defineProperty(PointLight.prototype, "direction", {
  48890. /**
  48891. * Gets the direction if it has been set.
  48892. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48893. */
  48894. get: function () {
  48895. return this._direction;
  48896. },
  48897. /**
  48898. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48899. */
  48900. set: function (value) {
  48901. var previousNeedCube = this.needCube();
  48902. this._direction = value;
  48903. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48904. this._shadowGenerator.recreateShadowMap();
  48905. }
  48906. },
  48907. enumerable: true,
  48908. configurable: true
  48909. });
  48910. /**
  48911. * Returns the string "PointLight"
  48912. * @returns the class name
  48913. */
  48914. PointLight.prototype.getClassName = function () {
  48915. return "PointLight";
  48916. };
  48917. /**
  48918. * Returns the integer 0.
  48919. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48920. */
  48921. PointLight.prototype.getTypeID = function () {
  48922. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48923. };
  48924. /**
  48925. * Specifies wether or not the shadowmap should be a cube texture.
  48926. * @returns true if the shadowmap needs to be a cube texture.
  48927. */
  48928. PointLight.prototype.needCube = function () {
  48929. return !this.direction;
  48930. };
  48931. /**
  48932. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48933. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48934. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48935. */
  48936. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48937. if (this.direction) {
  48938. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48939. }
  48940. else {
  48941. switch (faceIndex) {
  48942. case 0:
  48943. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48944. case 1:
  48945. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48946. case 2:
  48947. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48948. case 3:
  48949. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48950. case 4:
  48951. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48952. case 5:
  48953. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48954. }
  48955. }
  48956. return BABYLON.Vector3.Zero();
  48957. };
  48958. /**
  48959. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48960. * - fov = PI / 2
  48961. * - aspect ratio : 1.0
  48962. * - z-near and far equal to the active camera minZ and maxZ.
  48963. * Returns the PointLight.
  48964. */
  48965. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48966. var activeCamera = this.getScene().activeCamera;
  48967. if (!activeCamera) {
  48968. return;
  48969. }
  48970. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48971. };
  48972. PointLight.prototype._buildUniformLayout = function () {
  48973. this._uniformBuffer.addUniform("vLightData", 4);
  48974. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48975. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48976. this._uniformBuffer.addUniform("vLightFalloff", 4);
  48977. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48978. this._uniformBuffer.addUniform("depthValues", 2);
  48979. this._uniformBuffer.create();
  48980. };
  48981. /**
  48982. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48983. * @param effect The effect to update
  48984. * @param lightIndex The index of the light in the effect to update
  48985. * @returns The point light
  48986. */
  48987. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48988. if (this.computeTransformedInformation()) {
  48989. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48990. }
  48991. else {
  48992. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48993. }
  48994. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  48995. return this;
  48996. };
  48997. /**
  48998. * Prepares the list of defines specific to the light type.
  48999. * @param defines the list of defines
  49000. * @param lightIndex defines the index of the light for the effect
  49001. */
  49002. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49003. defines["POINTLIGHT" + lightIndex] = true;
  49004. };
  49005. __decorate([
  49006. BABYLON.serialize()
  49007. ], PointLight.prototype, "shadowAngle", null);
  49008. return PointLight;
  49009. }(BABYLON.ShadowLight));
  49010. BABYLON.PointLight = PointLight;
  49011. })(BABYLON || (BABYLON = {}));
  49012. //# sourceMappingURL=babylon.pointLight.js.map
  49013. var BABYLON;
  49014. (function (BABYLON) {
  49015. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49016. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49017. });
  49018. /**
  49019. * A directional light is defined by a direction (what a surprise!).
  49020. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49021. * 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.
  49022. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49023. */
  49024. var DirectionalLight = /** @class */ (function (_super) {
  49025. __extends(DirectionalLight, _super);
  49026. /**
  49027. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49028. * The directional light is emitted from everywhere in the given direction.
  49029. * It can cast shawdows.
  49030. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49031. * @param name The friendly name of the light
  49032. * @param direction The direction of the light
  49033. * @param scene The scene the light belongs to
  49034. */
  49035. function DirectionalLight(name, direction, scene) {
  49036. var _this = _super.call(this, name, scene) || this;
  49037. _this._shadowFrustumSize = 0;
  49038. _this._shadowOrthoScale = 0.1;
  49039. /**
  49040. * Automatically compute the projection matrix to best fit (including all the casters)
  49041. * on each frame.
  49042. */
  49043. _this.autoUpdateExtends = true;
  49044. // Cache
  49045. _this._orthoLeft = Number.MAX_VALUE;
  49046. _this._orthoRight = Number.MIN_VALUE;
  49047. _this._orthoTop = Number.MIN_VALUE;
  49048. _this._orthoBottom = Number.MAX_VALUE;
  49049. _this.position = direction.scale(-1.0);
  49050. _this.direction = direction;
  49051. return _this;
  49052. }
  49053. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49054. /**
  49055. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49056. */
  49057. get: function () {
  49058. return this._shadowFrustumSize;
  49059. },
  49060. /**
  49061. * Specifies a fix frustum size for the shadow generation.
  49062. */
  49063. set: function (value) {
  49064. this._shadowFrustumSize = value;
  49065. this.forceProjectionMatrixCompute();
  49066. },
  49067. enumerable: true,
  49068. configurable: true
  49069. });
  49070. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49071. /**
  49072. * Gets the shadow projection scale against the optimal computed one.
  49073. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49074. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49075. */
  49076. get: function () {
  49077. return this._shadowOrthoScale;
  49078. },
  49079. /**
  49080. * Sets the shadow projection scale against the optimal computed one.
  49081. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49082. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49083. */
  49084. set: function (value) {
  49085. this._shadowOrthoScale = value;
  49086. this.forceProjectionMatrixCompute();
  49087. },
  49088. enumerable: true,
  49089. configurable: true
  49090. });
  49091. /**
  49092. * Returns the string "DirectionalLight".
  49093. * @return The class name
  49094. */
  49095. DirectionalLight.prototype.getClassName = function () {
  49096. return "DirectionalLight";
  49097. };
  49098. /**
  49099. * Returns the integer 1.
  49100. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49101. */
  49102. DirectionalLight.prototype.getTypeID = function () {
  49103. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49104. };
  49105. /**
  49106. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49107. * Returns the DirectionalLight Shadow projection matrix.
  49108. */
  49109. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49110. if (this.shadowFrustumSize > 0) {
  49111. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49112. }
  49113. else {
  49114. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49115. }
  49116. };
  49117. /**
  49118. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49119. * Returns the DirectionalLight Shadow projection matrix.
  49120. */
  49121. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49122. var activeCamera = this.getScene().activeCamera;
  49123. if (!activeCamera) {
  49124. return;
  49125. }
  49126. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49127. };
  49128. /**
  49129. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49130. * Returns the DirectionalLight Shadow projection matrix.
  49131. */
  49132. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49133. var activeCamera = this.getScene().activeCamera;
  49134. if (!activeCamera) {
  49135. return;
  49136. }
  49137. // Check extends
  49138. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49139. var tempVector3 = BABYLON.Vector3.Zero();
  49140. this._orthoLeft = Number.MAX_VALUE;
  49141. this._orthoRight = Number.MIN_VALUE;
  49142. this._orthoTop = Number.MIN_VALUE;
  49143. this._orthoBottom = Number.MAX_VALUE;
  49144. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49145. var mesh = renderList[meshIndex];
  49146. if (!mesh) {
  49147. continue;
  49148. }
  49149. var boundingInfo = mesh.getBoundingInfo();
  49150. var boundingBox = boundingInfo.boundingBox;
  49151. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49152. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49153. if (tempVector3.x < this._orthoLeft)
  49154. this._orthoLeft = tempVector3.x;
  49155. if (tempVector3.y < this._orthoBottom)
  49156. this._orthoBottom = tempVector3.y;
  49157. if (tempVector3.x > this._orthoRight)
  49158. this._orthoRight = tempVector3.x;
  49159. if (tempVector3.y > this._orthoTop)
  49160. this._orthoTop = tempVector3.y;
  49161. }
  49162. }
  49163. }
  49164. var xOffset = this._orthoRight - this._orthoLeft;
  49165. var yOffset = this._orthoTop - this._orthoBottom;
  49166. 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);
  49167. };
  49168. DirectionalLight.prototype._buildUniformLayout = function () {
  49169. this._uniformBuffer.addUniform("vLightData", 4);
  49170. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49171. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49172. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49173. this._uniformBuffer.addUniform("depthValues", 2);
  49174. this._uniformBuffer.create();
  49175. };
  49176. /**
  49177. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49178. * @param effect The effect to update
  49179. * @param lightIndex The index of the light in the effect to update
  49180. * @returns The directional light
  49181. */
  49182. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49183. if (this.computeTransformedInformation()) {
  49184. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49185. return this;
  49186. }
  49187. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49188. return this;
  49189. };
  49190. /**
  49191. * Gets the minZ used for shadow according to both the scene and the light.
  49192. *
  49193. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49194. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49195. * @param activeCamera The camera we are returning the min for
  49196. * @returns the depth min z
  49197. */
  49198. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49199. return 1;
  49200. };
  49201. /**
  49202. * Gets the maxZ used for shadow according to both the scene and the light.
  49203. *
  49204. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49205. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49206. * @param activeCamera The camera we are returning the max for
  49207. * @returns the depth max z
  49208. */
  49209. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49210. return 1;
  49211. };
  49212. /**
  49213. * Prepares the list of defines specific to the light type.
  49214. * @param defines the list of defines
  49215. * @param lightIndex defines the index of the light for the effect
  49216. */
  49217. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49218. defines["DIRLIGHT" + lightIndex] = true;
  49219. };
  49220. __decorate([
  49221. BABYLON.serialize()
  49222. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49223. __decorate([
  49224. BABYLON.serialize()
  49225. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49226. __decorate([
  49227. BABYLON.serialize()
  49228. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49229. return DirectionalLight;
  49230. }(BABYLON.ShadowLight));
  49231. BABYLON.DirectionalLight = DirectionalLight;
  49232. })(BABYLON || (BABYLON = {}));
  49233. //# sourceMappingURL=babylon.directionalLight.js.map
  49234. var BABYLON;
  49235. (function (BABYLON) {
  49236. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49237. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49238. });
  49239. /**
  49240. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49241. * These values define a cone of light starting from the position, emitting toward the direction.
  49242. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49243. * and the exponent defines the speed of the decay of the light with distance (reach).
  49244. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49245. */
  49246. var SpotLight = /** @class */ (function (_super) {
  49247. __extends(SpotLight, _super);
  49248. /**
  49249. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49250. * It can cast shadows.
  49251. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49252. * @param name The light friendly name
  49253. * @param position The position of the spot light in the scene
  49254. * @param direction The direction of the light in the scene
  49255. * @param angle The cone angle of the light in Radians
  49256. * @param exponent The light decay speed with the distance from the emission spot
  49257. * @param scene The scene the lights belongs to
  49258. */
  49259. function SpotLight(name, position, direction, angle, exponent, scene) {
  49260. var _this = _super.call(this, name, scene) || this;
  49261. _this._innerAngle = 0;
  49262. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49263. _this._projectionTextureLightNear = 1e-6;
  49264. _this._projectionTextureLightFar = 1000.0;
  49265. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49266. _this._projectionTextureViewLightDirty = true;
  49267. _this._projectionTextureProjectionLightDirty = true;
  49268. _this._projectionTextureDirty = true;
  49269. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49270. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49271. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49272. _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);
  49273. _this.position = position;
  49274. _this.direction = direction;
  49275. _this.angle = angle;
  49276. _this.exponent = exponent;
  49277. return _this;
  49278. }
  49279. Object.defineProperty(SpotLight.prototype, "angle", {
  49280. /**
  49281. * Gets the cone angle of the spot light in Radians.
  49282. */
  49283. get: function () {
  49284. return this._angle;
  49285. },
  49286. /**
  49287. * Sets the cone angle of the spot light in Radians.
  49288. */
  49289. set: function (value) {
  49290. this._angle = value;
  49291. this._cosHalfAngle = Math.cos(value * 0.5);
  49292. this._projectionTextureProjectionLightDirty = true;
  49293. this.forceProjectionMatrixCompute();
  49294. this._computeAngleValues();
  49295. },
  49296. enumerable: true,
  49297. configurable: true
  49298. });
  49299. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49300. /**
  49301. * Only used in gltf falloff mode, this defines the angle where
  49302. * the directional falloff will start before cutting at angle which could be seen
  49303. * as outer angle.
  49304. */
  49305. get: function () {
  49306. return this._angle;
  49307. },
  49308. /**
  49309. * Only used in gltf falloff mode, this defines the angle where
  49310. * the directional falloff will start before cutting at angle which could be seen
  49311. * as outer angle.
  49312. */
  49313. set: function (value) {
  49314. this._innerAngle = value;
  49315. this._computeAngleValues();
  49316. },
  49317. enumerable: true,
  49318. configurable: true
  49319. });
  49320. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49321. /**
  49322. * Allows scaling the angle of the light for shadow generation only.
  49323. */
  49324. get: function () {
  49325. return this._shadowAngleScale;
  49326. },
  49327. /**
  49328. * Allows scaling the angle of the light for shadow generation only.
  49329. */
  49330. set: function (value) {
  49331. this._shadowAngleScale = value;
  49332. this.forceProjectionMatrixCompute();
  49333. },
  49334. enumerable: true,
  49335. configurable: true
  49336. });
  49337. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49338. /**
  49339. * Allows reading the projecton texture
  49340. */
  49341. get: function () {
  49342. return this._projectionTextureMatrix;
  49343. },
  49344. enumerable: true,
  49345. configurable: true
  49346. });
  49347. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49348. /**
  49349. * Gets the near clip of the Spotlight for texture projection.
  49350. */
  49351. get: function () {
  49352. return this._projectionTextureLightNear;
  49353. },
  49354. /**
  49355. * Sets the near clip of the Spotlight for texture projection.
  49356. */
  49357. set: function (value) {
  49358. this._projectionTextureLightNear = value;
  49359. this._projectionTextureProjectionLightDirty = true;
  49360. },
  49361. enumerable: true,
  49362. configurable: true
  49363. });
  49364. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49365. /**
  49366. * Gets the far clip of the Spotlight for texture projection.
  49367. */
  49368. get: function () {
  49369. return this._projectionTextureLightFar;
  49370. },
  49371. /**
  49372. * Sets the far clip of the Spotlight for texture projection.
  49373. */
  49374. set: function (value) {
  49375. this._projectionTextureLightFar = value;
  49376. this._projectionTextureProjectionLightDirty = true;
  49377. },
  49378. enumerable: true,
  49379. configurable: true
  49380. });
  49381. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49382. /**
  49383. * Gets the Up vector of the Spotlight for texture projection.
  49384. */
  49385. get: function () {
  49386. return this._projectionTextureUpDirection;
  49387. },
  49388. /**
  49389. * Sets the Up vector of the Spotlight for texture projection.
  49390. */
  49391. set: function (value) {
  49392. this._projectionTextureUpDirection = value;
  49393. this._projectionTextureProjectionLightDirty = true;
  49394. },
  49395. enumerable: true,
  49396. configurable: true
  49397. });
  49398. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49399. /**
  49400. * Gets the projection texture of the light.
  49401. */
  49402. get: function () {
  49403. return this._projectionTexture;
  49404. },
  49405. /**
  49406. * Sets the projection texture of the light.
  49407. */
  49408. set: function (value) {
  49409. this._projectionTexture = value;
  49410. this._projectionTextureDirty = true;
  49411. },
  49412. enumerable: true,
  49413. configurable: true
  49414. });
  49415. /**
  49416. * Returns the string "SpotLight".
  49417. * @returns the class name
  49418. */
  49419. SpotLight.prototype.getClassName = function () {
  49420. return "SpotLight";
  49421. };
  49422. /**
  49423. * Returns the integer 2.
  49424. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49425. */
  49426. SpotLight.prototype.getTypeID = function () {
  49427. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49428. };
  49429. /**
  49430. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49431. */
  49432. SpotLight.prototype._setDirection = function (value) {
  49433. _super.prototype._setDirection.call(this, value);
  49434. this._projectionTextureViewLightDirty = true;
  49435. };
  49436. /**
  49437. * Overrides the position setter to recompute the projection texture view light Matrix.
  49438. */
  49439. SpotLight.prototype._setPosition = function (value) {
  49440. _super.prototype._setPosition.call(this, value);
  49441. this._projectionTextureViewLightDirty = true;
  49442. };
  49443. /**
  49444. * 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.
  49445. * Returns the SpotLight.
  49446. */
  49447. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49448. var activeCamera = this.getScene().activeCamera;
  49449. if (!activeCamera) {
  49450. return;
  49451. }
  49452. this._shadowAngleScale = this._shadowAngleScale || 1;
  49453. var angle = this._shadowAngleScale * this._angle;
  49454. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49455. };
  49456. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49457. this._projectionTextureViewLightDirty = false;
  49458. this._projectionTextureDirty = true;
  49459. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49460. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49461. };
  49462. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49463. this._projectionTextureProjectionLightDirty = false;
  49464. this._projectionTextureDirty = true;
  49465. var light_far = this.projectionTextureLightFar;
  49466. var light_near = this.projectionTextureLightNear;
  49467. var P = light_far / (light_far - light_near);
  49468. var Q = -P * light_near;
  49469. var S = 1.0 / Math.tan(this._angle / 2.0);
  49470. var A = 1.0;
  49471. 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);
  49472. };
  49473. /**
  49474. * Main function for light texture projection matrix computing.
  49475. */
  49476. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49477. this._projectionTextureDirty = false;
  49478. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49479. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49480. };
  49481. SpotLight.prototype._buildUniformLayout = function () {
  49482. this._uniformBuffer.addUniform("vLightData", 4);
  49483. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49484. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49485. this._uniformBuffer.addUniform("vLightDirection", 3);
  49486. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49487. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49488. this._uniformBuffer.addUniform("depthValues", 2);
  49489. this._uniformBuffer.create();
  49490. };
  49491. SpotLight.prototype._computeAngleValues = function () {
  49492. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49493. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49494. };
  49495. /**
  49496. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49497. * @param effect The effect to update
  49498. * @param lightIndex The index of the light in the effect to update
  49499. * @returns The spot light
  49500. */
  49501. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49502. var normalizeDirection;
  49503. if (this.computeTransformedInformation()) {
  49504. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49505. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49506. }
  49507. else {
  49508. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49509. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49510. }
  49511. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49512. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49513. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49514. if (this._projectionTextureViewLightDirty) {
  49515. this._computeProjectionTextureViewLightMatrix();
  49516. }
  49517. if (this._projectionTextureProjectionLightDirty) {
  49518. this._computeProjectionTextureProjectionLightMatrix();
  49519. }
  49520. if (this._projectionTextureDirty) {
  49521. this._computeProjectionTextureMatrix();
  49522. }
  49523. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49524. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49525. }
  49526. return this;
  49527. };
  49528. /**
  49529. * Disposes the light and the associated resources.
  49530. */
  49531. SpotLight.prototype.dispose = function () {
  49532. _super.prototype.dispose.call(this);
  49533. if (this._projectionTexture) {
  49534. this._projectionTexture.dispose();
  49535. }
  49536. };
  49537. /**
  49538. * Prepares the list of defines specific to the light type.
  49539. * @param defines the list of defines
  49540. * @param lightIndex defines the index of the light for the effect
  49541. */
  49542. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49543. defines["SPOTLIGHT" + lightIndex] = true;
  49544. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49545. };
  49546. __decorate([
  49547. BABYLON.serialize()
  49548. ], SpotLight.prototype, "angle", null);
  49549. __decorate([
  49550. BABYLON.serialize()
  49551. ], SpotLight.prototype, "innerAngle", null);
  49552. __decorate([
  49553. BABYLON.serialize()
  49554. ], SpotLight.prototype, "shadowAngleScale", null);
  49555. __decorate([
  49556. BABYLON.serialize()
  49557. ], SpotLight.prototype, "exponent", void 0);
  49558. __decorate([
  49559. BABYLON.serialize()
  49560. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49561. __decorate([
  49562. BABYLON.serialize()
  49563. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49564. __decorate([
  49565. BABYLON.serialize()
  49566. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49567. __decorate([
  49568. BABYLON.serializeAsTexture("projectedLightTexture")
  49569. ], SpotLight.prototype, "_projectionTexture", void 0);
  49570. return SpotLight;
  49571. }(BABYLON.ShadowLight));
  49572. BABYLON.SpotLight = SpotLight;
  49573. })(BABYLON || (BABYLON = {}));
  49574. //# sourceMappingURL=babylon.spotLight.js.map
  49575. var BABYLON;
  49576. (function (BABYLON) {
  49577. /**
  49578. * Class used to override all child animations of a given target
  49579. */
  49580. var AnimationPropertiesOverride = /** @class */ (function () {
  49581. function AnimationPropertiesOverride() {
  49582. /**
  49583. * Gets or sets a value indicating if animation blending must be used
  49584. */
  49585. this.enableBlending = false;
  49586. /**
  49587. * Gets or sets the blending speed to use when enableBlending is true
  49588. */
  49589. this.blendingSpeed = 0.01;
  49590. /**
  49591. * Gets or sets the default loop mode to use
  49592. */
  49593. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49594. }
  49595. return AnimationPropertiesOverride;
  49596. }());
  49597. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49598. })(BABYLON || (BABYLON = {}));
  49599. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49600. var BABYLON;
  49601. (function (BABYLON) {
  49602. /**
  49603. * Represents the range of an animation
  49604. */
  49605. var AnimationRange = /** @class */ (function () {
  49606. /**
  49607. * Initializes the range of an animation
  49608. * @param name The name of the animation range
  49609. * @param from The starting frame of the animation
  49610. * @param to The ending frame of the animation
  49611. */
  49612. function AnimationRange(
  49613. /**The name of the animation range**/
  49614. name,
  49615. /**The starting frame of the animation */
  49616. from,
  49617. /**The ending frame of the animation*/
  49618. to) {
  49619. this.name = name;
  49620. this.from = from;
  49621. this.to = to;
  49622. }
  49623. /**
  49624. * Makes a copy of the animation range
  49625. * @returns A copy of the animation range
  49626. */
  49627. AnimationRange.prototype.clone = function () {
  49628. return new AnimationRange(this.name, this.from, this.to);
  49629. };
  49630. return AnimationRange;
  49631. }());
  49632. BABYLON.AnimationRange = AnimationRange;
  49633. /**
  49634. * Composed of a frame, and an action function
  49635. */
  49636. var AnimationEvent = /** @class */ (function () {
  49637. /**
  49638. * Initializes the animation event
  49639. * @param frame The frame for which the event is triggered
  49640. * @param action The event to perform when triggered
  49641. * @param onlyOnce Specifies if the event should be triggered only once
  49642. */
  49643. function AnimationEvent(
  49644. /** The frame for which the event is triggered **/
  49645. frame,
  49646. /** The event to perform when triggered **/
  49647. action,
  49648. /** Specifies if the event should be triggered only once**/
  49649. onlyOnce) {
  49650. this.frame = frame;
  49651. this.action = action;
  49652. this.onlyOnce = onlyOnce;
  49653. /**
  49654. * Specifies if the animation event is done
  49655. */
  49656. this.isDone = false;
  49657. }
  49658. /** @hidden */
  49659. AnimationEvent.prototype._clone = function () {
  49660. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49661. };
  49662. return AnimationEvent;
  49663. }());
  49664. BABYLON.AnimationEvent = AnimationEvent;
  49665. /**
  49666. * A cursor which tracks a point on a path
  49667. */
  49668. var PathCursor = /** @class */ (function () {
  49669. /**
  49670. * Initializes the path cursor
  49671. * @param path The path to track
  49672. */
  49673. function PathCursor(path) {
  49674. this.path = path;
  49675. /**
  49676. * Stores path cursor callbacks for when an onchange event is triggered
  49677. */
  49678. this._onchange = new Array();
  49679. /**
  49680. * The value of the path cursor
  49681. */
  49682. this.value = 0;
  49683. /**
  49684. * The animation array of the path cursor
  49685. */
  49686. this.animations = new Array();
  49687. }
  49688. /**
  49689. * Gets the cursor point on the path
  49690. * @returns A point on the path cursor at the cursor location
  49691. */
  49692. PathCursor.prototype.getPoint = function () {
  49693. var point = this.path.getPointAtLengthPosition(this.value);
  49694. return new BABYLON.Vector3(point.x, 0, point.y);
  49695. };
  49696. /**
  49697. * Moves the cursor ahead by the step amount
  49698. * @param step The amount to move the cursor forward
  49699. * @returns This path cursor
  49700. */
  49701. PathCursor.prototype.moveAhead = function (step) {
  49702. if (step === void 0) { step = 0.002; }
  49703. this.move(step);
  49704. return this;
  49705. };
  49706. /**
  49707. * Moves the cursor behind by the step amount
  49708. * @param step The amount to move the cursor back
  49709. * @returns This path cursor
  49710. */
  49711. PathCursor.prototype.moveBack = function (step) {
  49712. if (step === void 0) { step = 0.002; }
  49713. this.move(-step);
  49714. return this;
  49715. };
  49716. /**
  49717. * Moves the cursor by the step amount
  49718. * If the step amount is greater than one, an exception is thrown
  49719. * @param step The amount to move the cursor
  49720. * @returns This path cursor
  49721. */
  49722. PathCursor.prototype.move = function (step) {
  49723. if (Math.abs(step) > 1) {
  49724. throw "step size should be less than 1.";
  49725. }
  49726. this.value += step;
  49727. this.ensureLimits();
  49728. this.raiseOnChange();
  49729. return this;
  49730. };
  49731. /**
  49732. * Ensures that the value is limited between zero and one
  49733. * @returns This path cursor
  49734. */
  49735. PathCursor.prototype.ensureLimits = function () {
  49736. while (this.value > 1) {
  49737. this.value -= 1;
  49738. }
  49739. while (this.value < 0) {
  49740. this.value += 1;
  49741. }
  49742. return this;
  49743. };
  49744. /**
  49745. * Runs onchange callbacks on change (used by the animation engine)
  49746. * @returns This path cursor
  49747. */
  49748. PathCursor.prototype.raiseOnChange = function () {
  49749. var _this = this;
  49750. this._onchange.forEach(function (f) { return f(_this); });
  49751. return this;
  49752. };
  49753. /**
  49754. * Executes a function on change
  49755. * @param f A path cursor onchange callback
  49756. * @returns This path cursor
  49757. */
  49758. PathCursor.prototype.onchange = function (f) {
  49759. this._onchange.push(f);
  49760. return this;
  49761. };
  49762. return PathCursor;
  49763. }());
  49764. BABYLON.PathCursor = PathCursor;
  49765. /**
  49766. * Enum for the animation key frame interpolation type
  49767. */
  49768. var AnimationKeyInterpolation;
  49769. (function (AnimationKeyInterpolation) {
  49770. /**
  49771. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49772. */
  49773. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49774. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49775. /**
  49776. * Class used to store any kind of animation
  49777. */
  49778. var Animation = /** @class */ (function () {
  49779. /**
  49780. * Initializes the animation
  49781. * @param name Name of the animation
  49782. * @param targetProperty Property to animate
  49783. * @param framePerSecond The frames per second of the animation
  49784. * @param dataType The data type of the animation
  49785. * @param loopMode The loop mode of the animation
  49786. * @param enableBlendings Specifies if blending should be enabled
  49787. */
  49788. function Animation(
  49789. /**Name of the animation */
  49790. name,
  49791. /**Property to animate */
  49792. targetProperty,
  49793. /**The frames per second of the animation */
  49794. framePerSecond,
  49795. /**The data type of the animation */
  49796. dataType,
  49797. /**The loop mode of the animation */
  49798. loopMode,
  49799. /**Specifies if blending should be enabled */
  49800. enableBlending) {
  49801. this.name = name;
  49802. this.targetProperty = targetProperty;
  49803. this.framePerSecond = framePerSecond;
  49804. this.dataType = dataType;
  49805. this.loopMode = loopMode;
  49806. this.enableBlending = enableBlending;
  49807. /**
  49808. * @hidden Internal use only
  49809. */
  49810. this._runtimeAnimations = new Array();
  49811. /**
  49812. * The set of event that will be linked to this animation
  49813. */
  49814. this._events = new Array();
  49815. /**
  49816. * Stores the blending speed of the animation
  49817. */
  49818. this.blendingSpeed = 0.01;
  49819. /**
  49820. * Stores the animation ranges for the animation
  49821. */
  49822. this._ranges = {};
  49823. this.targetPropertyPath = targetProperty.split(".");
  49824. this.dataType = dataType;
  49825. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49826. }
  49827. /**
  49828. * @hidden Internal use
  49829. */
  49830. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49831. var dataType = undefined;
  49832. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49833. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49834. }
  49835. else if (from instanceof BABYLON.Quaternion) {
  49836. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49837. }
  49838. else if (from instanceof BABYLON.Vector3) {
  49839. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49840. }
  49841. else if (from instanceof BABYLON.Vector2) {
  49842. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49843. }
  49844. else if (from instanceof BABYLON.Color3) {
  49845. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49846. }
  49847. else if (from instanceof BABYLON.Size) {
  49848. dataType = Animation.ANIMATIONTYPE_SIZE;
  49849. }
  49850. if (dataType == undefined) {
  49851. return null;
  49852. }
  49853. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49854. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49855. animation.setKeys(keys);
  49856. if (easingFunction !== undefined) {
  49857. animation.setEasingFunction(easingFunction);
  49858. }
  49859. return animation;
  49860. };
  49861. /**
  49862. * Sets up an animation
  49863. * @param property The property to animate
  49864. * @param animationType The animation type to apply
  49865. * @param framePerSecond The frames per second of the animation
  49866. * @param easingFunction The easing function used in the animation
  49867. * @returns The created animation
  49868. */
  49869. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49870. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49871. animation.setEasingFunction(easingFunction);
  49872. return animation;
  49873. };
  49874. /**
  49875. * Create and start an animation on a node
  49876. * @param name defines the name of the global animation that will be run on all nodes
  49877. * @param node defines the root node where the animation will take place
  49878. * @param targetProperty defines property to animate
  49879. * @param framePerSecond defines the number of frame per second yo use
  49880. * @param totalFrame defines the number of frames in total
  49881. * @param from defines the initial value
  49882. * @param to defines the final value
  49883. * @param loopMode defines which loop mode you want to use (off by default)
  49884. * @param easingFunction defines the easing function to use (linear by default)
  49885. * @param onAnimationEnd defines the callback to call when animation end
  49886. * @returns the animatable created for this animation
  49887. */
  49888. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49889. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49890. if (!animation) {
  49891. return null;
  49892. }
  49893. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49894. };
  49895. /**
  49896. * Create and start an animation on a node and its descendants
  49897. * @param name defines the name of the global animation that will be run on all nodes
  49898. * @param node defines the root node where the animation will take place
  49899. * @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
  49900. * @param targetProperty defines property to animate
  49901. * @param framePerSecond defines the number of frame per second to use
  49902. * @param totalFrame defines the number of frames in total
  49903. * @param from defines the initial value
  49904. * @param to defines the final value
  49905. * @param loopMode defines which loop mode you want to use (off by default)
  49906. * @param easingFunction defines the easing function to use (linear by default)
  49907. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49908. * @returns the list of animatables created for all nodes
  49909. * @example https://www.babylonjs-playground.com/#MH0VLI
  49910. */
  49911. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49912. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49913. if (!animation) {
  49914. return null;
  49915. }
  49916. var scene = node.getScene();
  49917. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49918. };
  49919. /**
  49920. * Creates a new animation, merges it with the existing animations and starts it
  49921. * @param name Name of the animation
  49922. * @param node Node which contains the scene that begins the animations
  49923. * @param targetProperty Specifies which property to animate
  49924. * @param framePerSecond The frames per second of the animation
  49925. * @param totalFrame The total number of frames
  49926. * @param from The frame at the beginning of the animation
  49927. * @param to The frame at the end of the animation
  49928. * @param loopMode Specifies the loop mode of the animation
  49929. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49930. * @param onAnimationEnd Callback to run once the animation is complete
  49931. * @returns Nullable animation
  49932. */
  49933. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49934. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49935. if (!animation) {
  49936. return null;
  49937. }
  49938. node.animations.push(animation);
  49939. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49940. };
  49941. /**
  49942. * Transition property of an host to the target Value
  49943. * @param property The property to transition
  49944. * @param targetValue The target Value of the property
  49945. * @param host The object where the property to animate belongs
  49946. * @param scene Scene used to run the animation
  49947. * @param frameRate Framerate (in frame/s) to use
  49948. * @param transition The transition type we want to use
  49949. * @param duration The duration of the animation, in milliseconds
  49950. * @param onAnimationEnd Callback trigger at the end of the animation
  49951. * @returns Nullable animation
  49952. */
  49953. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49954. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49955. if (duration <= 0) {
  49956. host[property] = targetValue;
  49957. if (onAnimationEnd) {
  49958. onAnimationEnd();
  49959. }
  49960. return null;
  49961. }
  49962. var endFrame = frameRate * (duration / 1000);
  49963. transition.setKeys([{
  49964. frame: 0,
  49965. value: host[property].clone ? host[property].clone() : host[property]
  49966. },
  49967. {
  49968. frame: endFrame,
  49969. value: targetValue
  49970. }]);
  49971. if (!host.animations) {
  49972. host.animations = [];
  49973. }
  49974. host.animations.push(transition);
  49975. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49976. animation.onAnimationEnd = onAnimationEnd;
  49977. return animation;
  49978. };
  49979. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49980. /**
  49981. * Return the array of runtime animations currently using this animation
  49982. */
  49983. get: function () {
  49984. return this._runtimeAnimations;
  49985. },
  49986. enumerable: true,
  49987. configurable: true
  49988. });
  49989. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49990. /**
  49991. * Specifies if any of the runtime animations are currently running
  49992. */
  49993. get: function () {
  49994. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49995. var runtimeAnimation = _a[_i];
  49996. if (!runtimeAnimation.isStopped) {
  49997. return true;
  49998. }
  49999. }
  50000. return false;
  50001. },
  50002. enumerable: true,
  50003. configurable: true
  50004. });
  50005. // Methods
  50006. /**
  50007. * Converts the animation to a string
  50008. * @param fullDetails support for multiple levels of logging within scene loading
  50009. * @returns String form of the animation
  50010. */
  50011. Animation.prototype.toString = function (fullDetails) {
  50012. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50013. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50014. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50015. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50016. if (fullDetails) {
  50017. ret += ", Ranges: {";
  50018. var first = true;
  50019. for (var name in this._ranges) {
  50020. if (first) {
  50021. ret += ", ";
  50022. first = false;
  50023. }
  50024. ret += name;
  50025. }
  50026. ret += "}";
  50027. }
  50028. return ret;
  50029. };
  50030. /**
  50031. * Add an event to this animation
  50032. * @param event Event to add
  50033. */
  50034. Animation.prototype.addEvent = function (event) {
  50035. this._events.push(event);
  50036. };
  50037. /**
  50038. * Remove all events found at the given frame
  50039. * @param frame The frame to remove events from
  50040. */
  50041. Animation.prototype.removeEvents = function (frame) {
  50042. for (var index = 0; index < this._events.length; index++) {
  50043. if (this._events[index].frame === frame) {
  50044. this._events.splice(index, 1);
  50045. index--;
  50046. }
  50047. }
  50048. };
  50049. /**
  50050. * Retrieves all the events from the animation
  50051. * @returns Events from the animation
  50052. */
  50053. Animation.prototype.getEvents = function () {
  50054. return this._events;
  50055. };
  50056. /**
  50057. * Creates an animation range
  50058. * @param name Name of the animation range
  50059. * @param from Starting frame of the animation range
  50060. * @param to Ending frame of the animation
  50061. */
  50062. Animation.prototype.createRange = function (name, from, to) {
  50063. // check name not already in use; could happen for bones after serialized
  50064. if (!this._ranges[name]) {
  50065. this._ranges[name] = new AnimationRange(name, from, to);
  50066. }
  50067. };
  50068. /**
  50069. * Deletes an animation range by name
  50070. * @param name Name of the animation range to delete
  50071. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50072. */
  50073. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50074. if (deleteFrames === void 0) { deleteFrames = true; }
  50075. var range = this._ranges[name];
  50076. if (!range) {
  50077. return;
  50078. }
  50079. if (deleteFrames) {
  50080. var from = range.from;
  50081. var to = range.to;
  50082. // this loop MUST go high to low for multiple splices to work
  50083. for (var key = this._keys.length - 1; key >= 0; key--) {
  50084. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50085. this._keys.splice(key, 1);
  50086. }
  50087. }
  50088. }
  50089. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50090. };
  50091. /**
  50092. * Gets the animation range by name, or null if not defined
  50093. * @param name Name of the animation range
  50094. * @returns Nullable animation range
  50095. */
  50096. Animation.prototype.getRange = function (name) {
  50097. return this._ranges[name];
  50098. };
  50099. /**
  50100. * Gets the key frames from the animation
  50101. * @returns The key frames of the animation
  50102. */
  50103. Animation.prototype.getKeys = function () {
  50104. return this._keys;
  50105. };
  50106. /**
  50107. * Gets the highest frame rate of the animation
  50108. * @returns Highest frame rate of the animation
  50109. */
  50110. Animation.prototype.getHighestFrame = function () {
  50111. var ret = 0;
  50112. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50113. if (ret < this._keys[key].frame) {
  50114. ret = this._keys[key].frame;
  50115. }
  50116. }
  50117. return ret;
  50118. };
  50119. /**
  50120. * Gets the easing function of the animation
  50121. * @returns Easing function of the animation
  50122. */
  50123. Animation.prototype.getEasingFunction = function () {
  50124. return this._easingFunction;
  50125. };
  50126. /**
  50127. * Sets the easing function of the animation
  50128. * @param easingFunction A custom mathematical formula for animation
  50129. */
  50130. Animation.prototype.setEasingFunction = function (easingFunction) {
  50131. this._easingFunction = easingFunction;
  50132. };
  50133. /**
  50134. * Interpolates a scalar linearly
  50135. * @param startValue Start value of the animation curve
  50136. * @param endValue End value of the animation curve
  50137. * @param gradient Scalar amount to interpolate
  50138. * @returns Interpolated scalar value
  50139. */
  50140. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50141. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50142. };
  50143. /**
  50144. * Interpolates a scalar cubically
  50145. * @param startValue Start value of the animation curve
  50146. * @param outTangent End tangent of the animation
  50147. * @param endValue End value of the animation curve
  50148. * @param inTangent Start tangent of the animation curve
  50149. * @param gradient Scalar amount to interpolate
  50150. * @returns Interpolated scalar value
  50151. */
  50152. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50153. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50154. };
  50155. /**
  50156. * Interpolates a quaternion using a spherical linear interpolation
  50157. * @param startValue Start value of the animation curve
  50158. * @param endValue End value of the animation curve
  50159. * @param gradient Scalar amount to interpolate
  50160. * @returns Interpolated quaternion value
  50161. */
  50162. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50163. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50164. };
  50165. /**
  50166. * Interpolates a quaternion cubically
  50167. * @param startValue Start value of the animation curve
  50168. * @param outTangent End tangent of the animation curve
  50169. * @param endValue End value of the animation curve
  50170. * @param inTangent Start tangent of the animation curve
  50171. * @param gradient Scalar amount to interpolate
  50172. * @returns Interpolated quaternion value
  50173. */
  50174. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50175. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50176. };
  50177. /**
  50178. * Interpolates a Vector3 linearl
  50179. * @param startValue Start value of the animation curve
  50180. * @param endValue End value of the animation curve
  50181. * @param gradient Scalar amount to interpolate
  50182. * @returns Interpolated scalar value
  50183. */
  50184. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50185. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50186. };
  50187. /**
  50188. * Interpolates a Vector3 cubically
  50189. * @param startValue Start value of the animation curve
  50190. * @param outTangent End tangent of the animation
  50191. * @param endValue End value of the animation curve
  50192. * @param inTangent Start tangent of the animation curve
  50193. * @param gradient Scalar amount to interpolate
  50194. * @returns InterpolatedVector3 value
  50195. */
  50196. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50197. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50198. };
  50199. /**
  50200. * Interpolates a Vector2 linearly
  50201. * @param startValue Start value of the animation curve
  50202. * @param endValue End value of the animation curve
  50203. * @param gradient Scalar amount to interpolate
  50204. * @returns Interpolated Vector2 value
  50205. */
  50206. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50207. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50208. };
  50209. /**
  50210. * Interpolates a Vector2 cubically
  50211. * @param startValue Start value of the animation curve
  50212. * @param outTangent End tangent of the animation
  50213. * @param endValue End value of the animation curve
  50214. * @param inTangent Start tangent of the animation curve
  50215. * @param gradient Scalar amount to interpolate
  50216. * @returns Interpolated Vector2 value
  50217. */
  50218. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50219. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50220. };
  50221. /**
  50222. * Interpolates a size linearly
  50223. * @param startValue Start value of the animation curve
  50224. * @param endValue End value of the animation curve
  50225. * @param gradient Scalar amount to interpolate
  50226. * @returns Interpolated Size value
  50227. */
  50228. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50229. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50230. };
  50231. /**
  50232. * Interpolates a Color3 linearly
  50233. * @param startValue Start value of the animation curve
  50234. * @param endValue End value of the animation curve
  50235. * @param gradient Scalar amount to interpolate
  50236. * @returns Interpolated Color3 value
  50237. */
  50238. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50239. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50240. };
  50241. /**
  50242. * @hidden Internal use only
  50243. */
  50244. Animation.prototype._getKeyValue = function (value) {
  50245. if (typeof value === "function") {
  50246. return value();
  50247. }
  50248. return value;
  50249. };
  50250. /**
  50251. * @hidden Internal use only
  50252. */
  50253. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50254. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50255. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50256. }
  50257. var keys = this.getKeys();
  50258. // Try to get a hash to find the right key
  50259. 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));
  50260. if (keys[startKeyIndex].frame >= currentFrame) {
  50261. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50262. startKeyIndex--;
  50263. }
  50264. }
  50265. for (var key = startKeyIndex; key < keys.length; key++) {
  50266. var endKey = keys[key + 1];
  50267. if (endKey.frame >= currentFrame) {
  50268. var startKey = keys[key];
  50269. var startValue = this._getKeyValue(startKey.value);
  50270. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50271. return startValue;
  50272. }
  50273. var endValue = this._getKeyValue(endKey.value);
  50274. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50275. var frameDelta = endKey.frame - startKey.frame;
  50276. // gradient : percent of currentFrame between the frame inf and the frame sup
  50277. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50278. // check for easingFunction and correction of gradient
  50279. var easingFunction = this.getEasingFunction();
  50280. if (easingFunction != null) {
  50281. gradient = easingFunction.ease(gradient);
  50282. }
  50283. switch (this.dataType) {
  50284. // Float
  50285. case Animation.ANIMATIONTYPE_FLOAT:
  50286. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50287. switch (loopMode) {
  50288. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50289. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50290. return floatValue;
  50291. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50292. return offsetValue * repeatCount + floatValue;
  50293. }
  50294. break;
  50295. // Quaternion
  50296. case Animation.ANIMATIONTYPE_QUATERNION:
  50297. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50298. switch (loopMode) {
  50299. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50300. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50301. return quatValue;
  50302. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50303. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50304. }
  50305. return quatValue;
  50306. // Vector3
  50307. case Animation.ANIMATIONTYPE_VECTOR3:
  50308. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50309. switch (loopMode) {
  50310. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50311. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50312. return vec3Value;
  50313. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50314. return vec3Value.add(offsetValue.scale(repeatCount));
  50315. }
  50316. // Vector2
  50317. case Animation.ANIMATIONTYPE_VECTOR2:
  50318. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50319. switch (loopMode) {
  50320. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50321. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50322. return vec2Value;
  50323. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50324. return vec2Value.add(offsetValue.scale(repeatCount));
  50325. }
  50326. // Size
  50327. case Animation.ANIMATIONTYPE_SIZE:
  50328. switch (loopMode) {
  50329. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50330. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50331. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50332. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50333. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50334. }
  50335. // Color3
  50336. case Animation.ANIMATIONTYPE_COLOR3:
  50337. switch (loopMode) {
  50338. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50339. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50340. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50341. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50342. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50343. }
  50344. // Matrix
  50345. case Animation.ANIMATIONTYPE_MATRIX:
  50346. switch (loopMode) {
  50347. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50348. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50349. if (Animation.AllowMatricesInterpolation) {
  50350. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50351. }
  50352. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50353. return startValue;
  50354. }
  50355. default:
  50356. break;
  50357. }
  50358. break;
  50359. }
  50360. }
  50361. return this._getKeyValue(keys[keys.length - 1].value);
  50362. };
  50363. /**
  50364. * Defines the function to use to interpolate matrices
  50365. * @param startValue defines the start matrix
  50366. * @param endValue defines the end matrix
  50367. * @param gradient defines the gradient between both matrices
  50368. * @param result defines an optional target matrix where to store the interpolation
  50369. * @returns the interpolated matrix
  50370. */
  50371. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50372. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50373. if (result) {
  50374. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50375. return result;
  50376. }
  50377. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50378. }
  50379. if (result) {
  50380. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50381. return result;
  50382. }
  50383. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50384. };
  50385. /**
  50386. * Makes a copy of the animation
  50387. * @returns Cloned animation
  50388. */
  50389. Animation.prototype.clone = function () {
  50390. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50391. clone.enableBlending = this.enableBlending;
  50392. clone.blendingSpeed = this.blendingSpeed;
  50393. if (this._keys) {
  50394. clone.setKeys(this._keys);
  50395. }
  50396. if (this._ranges) {
  50397. clone._ranges = {};
  50398. for (var name in this._ranges) {
  50399. var range = this._ranges[name];
  50400. if (!range) {
  50401. continue;
  50402. }
  50403. clone._ranges[name] = range.clone();
  50404. }
  50405. }
  50406. return clone;
  50407. };
  50408. /**
  50409. * Sets the key frames of the animation
  50410. * @param values The animation key frames to set
  50411. */
  50412. Animation.prototype.setKeys = function (values) {
  50413. this._keys = values.slice(0);
  50414. };
  50415. /**
  50416. * Serializes the animation to an object
  50417. * @returns Serialized object
  50418. */
  50419. Animation.prototype.serialize = function () {
  50420. var serializationObject = {};
  50421. serializationObject.name = this.name;
  50422. serializationObject.property = this.targetProperty;
  50423. serializationObject.framePerSecond = this.framePerSecond;
  50424. serializationObject.dataType = this.dataType;
  50425. serializationObject.loopBehavior = this.loopMode;
  50426. serializationObject.enableBlending = this.enableBlending;
  50427. serializationObject.blendingSpeed = this.blendingSpeed;
  50428. var dataType = this.dataType;
  50429. serializationObject.keys = [];
  50430. var keys = this.getKeys();
  50431. for (var index = 0; index < keys.length; index++) {
  50432. var animationKey = keys[index];
  50433. var key = {};
  50434. key.frame = animationKey.frame;
  50435. switch (dataType) {
  50436. case Animation.ANIMATIONTYPE_FLOAT:
  50437. key.values = [animationKey.value];
  50438. break;
  50439. case Animation.ANIMATIONTYPE_QUATERNION:
  50440. case Animation.ANIMATIONTYPE_MATRIX:
  50441. case Animation.ANIMATIONTYPE_VECTOR3:
  50442. case Animation.ANIMATIONTYPE_COLOR3:
  50443. key.values = animationKey.value.asArray();
  50444. break;
  50445. }
  50446. serializationObject.keys.push(key);
  50447. }
  50448. serializationObject.ranges = [];
  50449. for (var name in this._ranges) {
  50450. var source = this._ranges[name];
  50451. if (!source) {
  50452. continue;
  50453. }
  50454. var range = {};
  50455. range.name = name;
  50456. range.from = source.from;
  50457. range.to = source.to;
  50458. serializationObject.ranges.push(range);
  50459. }
  50460. return serializationObject;
  50461. };
  50462. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50463. /**
  50464. * Get the float animation type
  50465. */
  50466. get: function () {
  50467. return Animation._ANIMATIONTYPE_FLOAT;
  50468. },
  50469. enumerable: true,
  50470. configurable: true
  50471. });
  50472. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50473. /**
  50474. * Get the Vector3 animation type
  50475. */
  50476. get: function () {
  50477. return Animation._ANIMATIONTYPE_VECTOR3;
  50478. },
  50479. enumerable: true,
  50480. configurable: true
  50481. });
  50482. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50483. /**
  50484. * Get the Vector2 animation type
  50485. */
  50486. get: function () {
  50487. return Animation._ANIMATIONTYPE_VECTOR2;
  50488. },
  50489. enumerable: true,
  50490. configurable: true
  50491. });
  50492. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50493. /**
  50494. * Get the Size animation type
  50495. */
  50496. get: function () {
  50497. return Animation._ANIMATIONTYPE_SIZE;
  50498. },
  50499. enumerable: true,
  50500. configurable: true
  50501. });
  50502. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50503. /**
  50504. * Get the Quaternion animation type
  50505. */
  50506. get: function () {
  50507. return Animation._ANIMATIONTYPE_QUATERNION;
  50508. },
  50509. enumerable: true,
  50510. configurable: true
  50511. });
  50512. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50513. /**
  50514. * Get the Matrix animation type
  50515. */
  50516. get: function () {
  50517. return Animation._ANIMATIONTYPE_MATRIX;
  50518. },
  50519. enumerable: true,
  50520. configurable: true
  50521. });
  50522. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50523. /**
  50524. * Get the Color3 animation type
  50525. */
  50526. get: function () {
  50527. return Animation._ANIMATIONTYPE_COLOR3;
  50528. },
  50529. enumerable: true,
  50530. configurable: true
  50531. });
  50532. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50533. /**
  50534. * Get the Relative Loop Mode
  50535. */
  50536. get: function () {
  50537. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50538. },
  50539. enumerable: true,
  50540. configurable: true
  50541. });
  50542. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50543. /**
  50544. * Get the Cycle Loop Mode
  50545. */
  50546. get: function () {
  50547. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50548. },
  50549. enumerable: true,
  50550. configurable: true
  50551. });
  50552. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50553. /**
  50554. * Get the Constant Loop Mode
  50555. */
  50556. get: function () {
  50557. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50558. },
  50559. enumerable: true,
  50560. configurable: true
  50561. });
  50562. /** @hidden */
  50563. Animation._UniversalLerp = function (left, right, amount) {
  50564. var constructor = left.constructor;
  50565. if (constructor.Lerp) { // Lerp supported
  50566. return constructor.Lerp(left, right, amount);
  50567. }
  50568. else if (constructor.Slerp) { // Slerp supported
  50569. return constructor.Slerp(left, right, amount);
  50570. }
  50571. else if (left.toFixed) { // Number
  50572. return left * (1.0 - amount) + amount * right;
  50573. }
  50574. else { // Blending not supported
  50575. return right;
  50576. }
  50577. };
  50578. /**
  50579. * Parses an animation object and creates an animation
  50580. * @param parsedAnimation Parsed animation object
  50581. * @returns Animation object
  50582. */
  50583. Animation.Parse = function (parsedAnimation) {
  50584. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50585. var dataType = parsedAnimation.dataType;
  50586. var keys = [];
  50587. var data;
  50588. var index;
  50589. if (parsedAnimation.enableBlending) {
  50590. animation.enableBlending = parsedAnimation.enableBlending;
  50591. }
  50592. if (parsedAnimation.blendingSpeed) {
  50593. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50594. }
  50595. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50596. var key = parsedAnimation.keys[index];
  50597. var inTangent;
  50598. var outTangent;
  50599. switch (dataType) {
  50600. case Animation.ANIMATIONTYPE_FLOAT:
  50601. data = key.values[0];
  50602. if (key.values.length >= 1) {
  50603. inTangent = key.values[1];
  50604. }
  50605. if (key.values.length >= 2) {
  50606. outTangent = key.values[2];
  50607. }
  50608. break;
  50609. case Animation.ANIMATIONTYPE_QUATERNION:
  50610. data = BABYLON.Quaternion.FromArray(key.values);
  50611. if (key.values.length >= 8) {
  50612. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50613. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50614. inTangent = _inTangent;
  50615. }
  50616. }
  50617. if (key.values.length >= 12) {
  50618. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50619. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50620. outTangent = _outTangent;
  50621. }
  50622. }
  50623. break;
  50624. case Animation.ANIMATIONTYPE_MATRIX:
  50625. data = BABYLON.Matrix.FromArray(key.values);
  50626. break;
  50627. case Animation.ANIMATIONTYPE_COLOR3:
  50628. data = BABYLON.Color3.FromArray(key.values);
  50629. break;
  50630. case Animation.ANIMATIONTYPE_VECTOR3:
  50631. default:
  50632. data = BABYLON.Vector3.FromArray(key.values);
  50633. break;
  50634. }
  50635. var keyData = {};
  50636. keyData.frame = key.frame;
  50637. keyData.value = data;
  50638. if (inTangent != undefined) {
  50639. keyData.inTangent = inTangent;
  50640. }
  50641. if (outTangent != undefined) {
  50642. keyData.outTangent = outTangent;
  50643. }
  50644. keys.push(keyData);
  50645. }
  50646. animation.setKeys(keys);
  50647. if (parsedAnimation.ranges) {
  50648. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50649. data = parsedAnimation.ranges[index];
  50650. animation.createRange(data.name, data.from, data.to);
  50651. }
  50652. }
  50653. return animation;
  50654. };
  50655. /**
  50656. * Appends the serialized animations from the source animations
  50657. * @param source Source containing the animations
  50658. * @param destination Target to store the animations
  50659. */
  50660. Animation.AppendSerializedAnimations = function (source, destination) {
  50661. if (source.animations) {
  50662. destination.animations = [];
  50663. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50664. var animation = source.animations[animationIndex];
  50665. destination.animations.push(animation.serialize());
  50666. }
  50667. }
  50668. };
  50669. /**
  50670. * Use matrix interpolation instead of using direct key value when animating matrices
  50671. */
  50672. Animation.AllowMatricesInterpolation = false;
  50673. /**
  50674. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50675. */
  50676. Animation.AllowMatrixDecomposeForInterpolation = true;
  50677. // Statics
  50678. /**
  50679. * Float animation type
  50680. */
  50681. Animation._ANIMATIONTYPE_FLOAT = 0;
  50682. /**
  50683. * Vector3 animation type
  50684. */
  50685. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50686. /**
  50687. * Quaternion animation type
  50688. */
  50689. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50690. /**
  50691. * Matrix animation type
  50692. */
  50693. Animation._ANIMATIONTYPE_MATRIX = 3;
  50694. /**
  50695. * Color3 animation type
  50696. */
  50697. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50698. /**
  50699. * Vector2 animation type
  50700. */
  50701. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50702. /**
  50703. * Size animation type
  50704. */
  50705. Animation._ANIMATIONTYPE_SIZE = 6;
  50706. /**
  50707. * Relative Loop Mode
  50708. */
  50709. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50710. /**
  50711. * Cycle Loop Mode
  50712. */
  50713. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50714. /**
  50715. * Constant Loop Mode
  50716. */
  50717. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50718. return Animation;
  50719. }());
  50720. BABYLON.Animation = Animation;
  50721. })(BABYLON || (BABYLON = {}));
  50722. //# sourceMappingURL=babylon.animation.js.map
  50723. var BABYLON;
  50724. (function (BABYLON) {
  50725. /**
  50726. * This class defines the direct association between an animation and a target
  50727. */
  50728. var TargetedAnimation = /** @class */ (function () {
  50729. function TargetedAnimation() {
  50730. }
  50731. return TargetedAnimation;
  50732. }());
  50733. BABYLON.TargetedAnimation = TargetedAnimation;
  50734. /**
  50735. * Use this class to create coordinated animations on multiple targets
  50736. */
  50737. var AnimationGroup = /** @class */ (function () {
  50738. function AnimationGroup(name, scene) {
  50739. if (scene === void 0) { scene = null; }
  50740. this.name = name;
  50741. this._targetedAnimations = new Array();
  50742. this._animatables = new Array();
  50743. this._from = Number.MAX_VALUE;
  50744. this._to = -Number.MAX_VALUE;
  50745. this._speedRatio = 1;
  50746. this.onAnimationEndObservable = new BABYLON.Observable();
  50747. /**
  50748. * This observable will notify when all animations have ended.
  50749. */
  50750. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50751. /**
  50752. * This observable will notify when all animations have paused.
  50753. */
  50754. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50755. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50756. this._scene.animationGroups.push(this);
  50757. }
  50758. Object.defineProperty(AnimationGroup.prototype, "from", {
  50759. /**
  50760. * Gets the first frame
  50761. */
  50762. get: function () {
  50763. return this._from;
  50764. },
  50765. enumerable: true,
  50766. configurable: true
  50767. });
  50768. Object.defineProperty(AnimationGroup.prototype, "to", {
  50769. /**
  50770. * Gets the last frame
  50771. */
  50772. get: function () {
  50773. return this._to;
  50774. },
  50775. enumerable: true,
  50776. configurable: true
  50777. });
  50778. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50779. /**
  50780. * Define if the animations are started
  50781. */
  50782. get: function () {
  50783. return this._isStarted;
  50784. },
  50785. enumerable: true,
  50786. configurable: true
  50787. });
  50788. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50789. /**
  50790. * Gets or sets the speed ratio to use for all animations
  50791. */
  50792. get: function () {
  50793. return this._speedRatio;
  50794. },
  50795. /**
  50796. * Gets or sets the speed ratio to use for all animations
  50797. */
  50798. set: function (value) {
  50799. if (this._speedRatio === value) {
  50800. return;
  50801. }
  50802. this._speedRatio = value;
  50803. for (var index = 0; index < this._animatables.length; index++) {
  50804. var animatable = this._animatables[index];
  50805. animatable.speedRatio = this._speedRatio;
  50806. }
  50807. },
  50808. enumerable: true,
  50809. configurable: true
  50810. });
  50811. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50812. /**
  50813. * Gets the targeted animations for this animation group
  50814. */
  50815. get: function () {
  50816. return this._targetedAnimations;
  50817. },
  50818. enumerable: true,
  50819. configurable: true
  50820. });
  50821. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50822. /**
  50823. * returning the list of animatables controlled by this animation group.
  50824. */
  50825. get: function () {
  50826. return this._animatables;
  50827. },
  50828. enumerable: true,
  50829. configurable: true
  50830. });
  50831. /**
  50832. * Add an animation (with its target) in the group
  50833. * @param animation defines the animation we want to add
  50834. * @param target defines the target of the animation
  50835. * @returns the {BABYLON.TargetedAnimation} object
  50836. */
  50837. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50838. var targetedAnimation = {
  50839. animation: animation,
  50840. target: target
  50841. };
  50842. var keys = animation.getKeys();
  50843. if (this._from > keys[0].frame) {
  50844. this._from = keys[0].frame;
  50845. }
  50846. if (this._to < keys[keys.length - 1].frame) {
  50847. this._to = keys[keys.length - 1].frame;
  50848. }
  50849. this._targetedAnimations.push(targetedAnimation);
  50850. return targetedAnimation;
  50851. };
  50852. /**
  50853. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50854. * It can add constant keys at begin or end
  50855. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50856. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50857. */
  50858. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50859. if (beginFrame === void 0) { beginFrame = null; }
  50860. if (endFrame === void 0) { endFrame = null; }
  50861. if (beginFrame == null)
  50862. beginFrame = this._from;
  50863. if (endFrame == null)
  50864. endFrame = this._to;
  50865. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50866. var targetedAnimation = this._targetedAnimations[index];
  50867. var keys = targetedAnimation.animation.getKeys();
  50868. var startKey = keys[0];
  50869. var endKey = keys[keys.length - 1];
  50870. if (startKey.frame > beginFrame) {
  50871. var newKey = {
  50872. frame: beginFrame,
  50873. value: startKey.value,
  50874. inTangent: startKey.inTangent,
  50875. outTangent: startKey.outTangent,
  50876. interpolation: startKey.interpolation
  50877. };
  50878. keys.splice(0, 0, newKey);
  50879. }
  50880. if (endKey.frame < endFrame) {
  50881. var newKey = {
  50882. frame: endFrame,
  50883. value: endKey.value,
  50884. inTangent: endKey.outTangent,
  50885. outTangent: endKey.outTangent,
  50886. interpolation: endKey.interpolation
  50887. };
  50888. keys.push(newKey);
  50889. }
  50890. }
  50891. this._from = beginFrame;
  50892. this._to = endFrame;
  50893. return this;
  50894. };
  50895. /**
  50896. * Start all animations on given targets
  50897. * @param loop defines if animations must loop
  50898. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50899. * @param from defines the from key (optional)
  50900. * @param to defines the to key (optional)
  50901. * @returns the current animation group
  50902. */
  50903. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50904. var _this = this;
  50905. if (loop === void 0) { loop = false; }
  50906. if (speedRatio === void 0) { speedRatio = 1; }
  50907. if (this._isStarted || this._targetedAnimations.length === 0) {
  50908. return this;
  50909. }
  50910. var _loop_1 = function (targetedAnimation) {
  50911. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50912. animatable.onAnimationEnd = function () {
  50913. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50914. _this._checkAnimationGroupEnded(animatable);
  50915. };
  50916. this_1._animatables.push(animatable);
  50917. };
  50918. var this_1 = this;
  50919. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50920. var targetedAnimation = _a[_i];
  50921. _loop_1(targetedAnimation);
  50922. }
  50923. this._speedRatio = speedRatio;
  50924. this._isStarted = true;
  50925. return this;
  50926. };
  50927. /**
  50928. * Pause all animations
  50929. */
  50930. AnimationGroup.prototype.pause = function () {
  50931. if (!this._isStarted) {
  50932. return this;
  50933. }
  50934. for (var index = 0; index < this._animatables.length; index++) {
  50935. var animatable = this._animatables[index];
  50936. animatable.pause();
  50937. }
  50938. this.onAnimationGroupPauseObservable.notifyObservers(this);
  50939. return this;
  50940. };
  50941. /**
  50942. * Play all animations to initial state
  50943. * This function will start() the animations if they were not started or will restart() them if they were paused
  50944. * @param loop defines if animations must loop
  50945. */
  50946. AnimationGroup.prototype.play = function (loop) {
  50947. // only if all animatables are ready and exist
  50948. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50949. if (loop !== undefined) {
  50950. for (var index = 0; index < this._animatables.length; index++) {
  50951. var animatable = this._animatables[index];
  50952. animatable.loopAnimation = loop;
  50953. }
  50954. }
  50955. this.restart();
  50956. }
  50957. else {
  50958. this.stop();
  50959. this.start(loop, this._speedRatio);
  50960. }
  50961. return this;
  50962. };
  50963. /**
  50964. * Reset all animations to initial state
  50965. */
  50966. AnimationGroup.prototype.reset = function () {
  50967. if (!this._isStarted) {
  50968. return this;
  50969. }
  50970. for (var index = 0; index < this._animatables.length; index++) {
  50971. var animatable = this._animatables[index];
  50972. animatable.reset();
  50973. }
  50974. return this;
  50975. };
  50976. /**
  50977. * Restart animations from key 0
  50978. */
  50979. AnimationGroup.prototype.restart = function () {
  50980. if (!this._isStarted) {
  50981. return this;
  50982. }
  50983. for (var index = 0; index < this._animatables.length; index++) {
  50984. var animatable = this._animatables[index];
  50985. animatable.restart();
  50986. }
  50987. return this;
  50988. };
  50989. /**
  50990. * Stop all animations
  50991. */
  50992. AnimationGroup.prototype.stop = function () {
  50993. if (!this._isStarted) {
  50994. return this;
  50995. }
  50996. var list = this._animatables.slice();
  50997. for (var index = 0; index < list.length; index++) {
  50998. list[index].stop();
  50999. }
  51000. this._isStarted = false;
  51001. return this;
  51002. };
  51003. /**
  51004. * Set animation weight for all animatables
  51005. * @param weight defines the weight to use
  51006. * @return the animationGroup
  51007. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51008. */
  51009. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51010. for (var index = 0; index < this._animatables.length; index++) {
  51011. var animatable = this._animatables[index];
  51012. animatable.weight = weight;
  51013. }
  51014. return this;
  51015. };
  51016. /**
  51017. * Synchronize and normalize all animatables with a source animatable
  51018. * @param root defines the root animatable to synchronize with
  51019. * @return the animationGroup
  51020. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51021. */
  51022. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51023. for (var index = 0; index < this._animatables.length; index++) {
  51024. var animatable = this._animatables[index];
  51025. animatable.syncWith(root);
  51026. }
  51027. return this;
  51028. };
  51029. /**
  51030. * Goes to a specific frame in this animation group
  51031. * @param frame the frame number to go to
  51032. * @return the animationGroup
  51033. */
  51034. AnimationGroup.prototype.goToFrame = function (frame) {
  51035. if (!this._isStarted) {
  51036. return this;
  51037. }
  51038. for (var index = 0; index < this._animatables.length; index++) {
  51039. var animatable = this._animatables[index];
  51040. animatable.goToFrame(frame);
  51041. }
  51042. return this;
  51043. };
  51044. /**
  51045. * Dispose all associated resources
  51046. */
  51047. AnimationGroup.prototype.dispose = function () {
  51048. this._targetedAnimations = [];
  51049. this._animatables = [];
  51050. var index = this._scene.animationGroups.indexOf(this);
  51051. if (index > -1) {
  51052. this._scene.animationGroups.splice(index, 1);
  51053. }
  51054. };
  51055. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51056. // animatable should be taken out of the array
  51057. var idx = this._animatables.indexOf(animatable);
  51058. if (idx > -1) {
  51059. this._animatables.splice(idx, 1);
  51060. }
  51061. // all animatables were removed? animation group ended!
  51062. if (this._animatables.length === 0) {
  51063. this._isStarted = false;
  51064. this.onAnimationGroupEndObservable.notifyObservers(this);
  51065. }
  51066. };
  51067. return AnimationGroup;
  51068. }());
  51069. BABYLON.AnimationGroup = AnimationGroup;
  51070. })(BABYLON || (BABYLON = {}));
  51071. //# sourceMappingURL=babylon.animationGroup.js.map
  51072. var BABYLON;
  51073. (function (BABYLON) {
  51074. // Static values to help the garbage collector
  51075. // Quaternion
  51076. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  51077. // Vector3
  51078. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  51079. // Vector2
  51080. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51081. // Size
  51082. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51083. // Color3
  51084. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51085. /**
  51086. * Defines a runtime animation
  51087. */
  51088. var RuntimeAnimation = /** @class */ (function () {
  51089. /**
  51090. * Create a new RuntimeAnimation object
  51091. * @param target defines the target of the animation
  51092. * @param animation defines the source animation object
  51093. * @param scene defines the hosting scene
  51094. * @param host defines the initiating Animatable
  51095. */
  51096. function RuntimeAnimation(target, animation, scene, host) {
  51097. var _this = this;
  51098. this._events = new Array();
  51099. /**
  51100. * The current frame of the runtime animation
  51101. */
  51102. this._currentFrame = 0;
  51103. /**
  51104. * The original value of the runtime animation
  51105. */
  51106. this._originalValue = new Array();
  51107. /**
  51108. * The offsets cache of the runtime animation
  51109. */
  51110. this._offsetsCache = {};
  51111. /**
  51112. * The high limits cache of the runtime animation
  51113. */
  51114. this._highLimitsCache = {};
  51115. /**
  51116. * Specifies if the runtime animation has been stopped
  51117. */
  51118. this._stopped = false;
  51119. /**
  51120. * The blending factor of the runtime animation
  51121. */
  51122. this._blendingFactor = 0;
  51123. /**
  51124. * The target path of the runtime animation
  51125. */
  51126. this._targetPath = "";
  51127. /**
  51128. * The weight of the runtime animation
  51129. */
  51130. this._weight = 1.0;
  51131. /**
  51132. * The ratio offset of the runtime animation
  51133. */
  51134. this._ratioOffset = 0;
  51135. /**
  51136. * The previous delay of the runtime animation
  51137. */
  51138. this._previousDelay = 0;
  51139. /**
  51140. * The previous ratio of the runtime animation
  51141. */
  51142. this._previousRatio = 0;
  51143. this._animation = animation;
  51144. this._target = target;
  51145. this._scene = scene;
  51146. this._host = host;
  51147. animation._runtimeAnimations.push(this);
  51148. // Cloning events locally
  51149. var events = animation.getEvents();
  51150. if (events && events.length > 0) {
  51151. events.forEach(function (e) {
  51152. _this._events.push(e._clone());
  51153. });
  51154. }
  51155. }
  51156. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51157. /**
  51158. * Gets the current frame of the runtime animation
  51159. */
  51160. get: function () {
  51161. return this._currentFrame;
  51162. },
  51163. enumerable: true,
  51164. configurable: true
  51165. });
  51166. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51167. /**
  51168. * Gets the weight of the runtime animation
  51169. */
  51170. get: function () {
  51171. return this._weight;
  51172. },
  51173. enumerable: true,
  51174. configurable: true
  51175. });
  51176. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51177. /**
  51178. * Gets the current value of the runtime animation
  51179. */
  51180. get: function () {
  51181. return this._currentValue;
  51182. },
  51183. enumerable: true,
  51184. configurable: true
  51185. });
  51186. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51187. /**
  51188. * Gets the target path of the runtime animation
  51189. */
  51190. get: function () {
  51191. return this._targetPath;
  51192. },
  51193. enumerable: true,
  51194. configurable: true
  51195. });
  51196. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51197. /**
  51198. * Gets the actual target of the runtime animation
  51199. */
  51200. get: function () {
  51201. return this._activeTarget;
  51202. },
  51203. enumerable: true,
  51204. configurable: true
  51205. });
  51206. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51207. /**
  51208. * Gets the animation from the runtime animation
  51209. */
  51210. get: function () {
  51211. return this._animation;
  51212. },
  51213. enumerable: true,
  51214. configurable: true
  51215. });
  51216. /**
  51217. * Resets the runtime animation to the beginning
  51218. * @param restoreOriginal defines whether to restore the target property to the original value
  51219. */
  51220. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51221. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51222. if (restoreOriginal) {
  51223. if (this._target instanceof Array) {
  51224. var index = 0;
  51225. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51226. var target = _a[_i];
  51227. if (this._originalValue[index] !== undefined) {
  51228. this._setValue(target, this._originalValue[index], -1);
  51229. }
  51230. index++;
  51231. }
  51232. }
  51233. else {
  51234. if (this._originalValue[0] !== undefined) {
  51235. this._setValue(this._target, this._originalValue[0], -1);
  51236. }
  51237. }
  51238. }
  51239. this._offsetsCache = {};
  51240. this._highLimitsCache = {};
  51241. this._currentFrame = 0;
  51242. this._blendingFactor = 0;
  51243. this._originalValue = new Array();
  51244. // Events
  51245. for (var index = 0; index < this._events.length; index++) {
  51246. this._events[index].isDone = false;
  51247. }
  51248. };
  51249. /**
  51250. * Specifies if the runtime animation is stopped
  51251. * @returns Boolean specifying if the runtime animation is stopped
  51252. */
  51253. RuntimeAnimation.prototype.isStopped = function () {
  51254. return this._stopped;
  51255. };
  51256. /**
  51257. * Disposes of the runtime animation
  51258. */
  51259. RuntimeAnimation.prototype.dispose = function () {
  51260. var index = this._animation.runtimeAnimations.indexOf(this);
  51261. if (index > -1) {
  51262. this._animation.runtimeAnimations.splice(index, 1);
  51263. }
  51264. };
  51265. /**
  51266. * Interpolates the animation from the current frame
  51267. * @param currentFrame The frame to interpolate the animation to
  51268. * @param repeatCount The number of times that the animation should loop
  51269. * @param loopMode The type of looping mode to use
  51270. * @param offsetValue Animation offset value
  51271. * @param highLimitValue The high limit value
  51272. * @returns The interpolated value
  51273. */
  51274. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51275. this._currentFrame = currentFrame;
  51276. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51277. this._workValue = BABYLON.Matrix.Zero();
  51278. }
  51279. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51280. };
  51281. /**
  51282. * Apply the interpolated value to the target
  51283. * @param currentValue defines the value computed by the animation
  51284. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51285. */
  51286. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51287. if (weight === void 0) { weight = 1.0; }
  51288. if (this._target instanceof Array) {
  51289. var index = 0;
  51290. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51291. var target = _a[_i];
  51292. this._setValue(target, currentValue, weight, index);
  51293. index++;
  51294. }
  51295. }
  51296. else {
  51297. this._setValue(this._target, currentValue, weight);
  51298. }
  51299. };
  51300. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51301. if (targetIndex === void 0) { targetIndex = 0; }
  51302. // Set value
  51303. var path;
  51304. var destination;
  51305. var targetPropertyPath = this._animation.targetPropertyPath;
  51306. if (targetPropertyPath.length > 1) {
  51307. var property = target[targetPropertyPath[0]];
  51308. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51309. property = property[targetPropertyPath[index]];
  51310. }
  51311. path = targetPropertyPath[targetPropertyPath.length - 1];
  51312. destination = property;
  51313. }
  51314. else {
  51315. path = targetPropertyPath[0];
  51316. destination = target;
  51317. }
  51318. this._targetPath = path;
  51319. this._activeTarget = destination;
  51320. this._weight = weight;
  51321. if (this._originalValue[targetIndex] === undefined) {
  51322. var originalValue = void 0;
  51323. if (destination.getRestPose && path === "_matrix") { // For bones
  51324. originalValue = destination.getRestPose();
  51325. }
  51326. else {
  51327. originalValue = destination[path];
  51328. }
  51329. if (originalValue && originalValue.clone) {
  51330. this._originalValue[targetIndex] = originalValue.clone();
  51331. }
  51332. else {
  51333. this._originalValue[targetIndex] = originalValue;
  51334. }
  51335. }
  51336. // Blending
  51337. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51338. if (enableBlending && this._blendingFactor <= 1.0) {
  51339. if (!this._originalBlendValue) {
  51340. var originalValue = destination[path];
  51341. if (originalValue.clone) {
  51342. this._originalBlendValue = originalValue.clone();
  51343. }
  51344. else {
  51345. this._originalBlendValue = originalValue;
  51346. }
  51347. }
  51348. if (this._originalBlendValue.m) { // Matrix
  51349. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51350. if (this._currentValue) {
  51351. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51352. }
  51353. else {
  51354. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51355. }
  51356. }
  51357. else {
  51358. if (this._currentValue) {
  51359. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51360. }
  51361. else {
  51362. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51363. }
  51364. }
  51365. }
  51366. else {
  51367. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51368. }
  51369. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51370. this._blendingFactor += blendingSpeed;
  51371. }
  51372. else {
  51373. this._currentValue = currentValue;
  51374. }
  51375. if (weight !== -1.0) {
  51376. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51377. }
  51378. else {
  51379. destination[path] = this._currentValue;
  51380. }
  51381. if (target.markAsDirty) {
  51382. target.markAsDirty(this._animation.targetProperty);
  51383. }
  51384. };
  51385. /**
  51386. * Gets the loop pmode of the runtime animation
  51387. * @returns Loop Mode
  51388. */
  51389. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51390. if (this._target && this._target.animationPropertiesOverride) {
  51391. return this._target.animationPropertiesOverride.loopMode;
  51392. }
  51393. return this._animation.loopMode;
  51394. };
  51395. /**
  51396. * Move the current animation to a given frame
  51397. * @param frame defines the frame to move to
  51398. */
  51399. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51400. var keys = this._animation.getKeys();
  51401. if (frame < keys[0].frame) {
  51402. frame = keys[0].frame;
  51403. }
  51404. else if (frame > keys[keys.length - 1].frame) {
  51405. frame = keys[keys.length - 1].frame;
  51406. }
  51407. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51408. this.setValue(currentValue, -1);
  51409. };
  51410. /**
  51411. * @hidden Internal use only
  51412. */
  51413. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51414. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51415. this._ratioOffset = this._previousRatio - newRatio;
  51416. };
  51417. /**
  51418. * Execute the current animation
  51419. * @param delay defines the delay to add to the current frame
  51420. * @param from defines the lower bound of the animation range
  51421. * @param to defines the upper bound of the animation range
  51422. * @param loop defines if the current animation must loop
  51423. * @param speedRatio defines the current speed ratio
  51424. * @param weight defines the weight of the animation (default is -1 so no weight)
  51425. * @returns a boolean indicating if the animation is running
  51426. */
  51427. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51428. if (weight === void 0) { weight = -1.0; }
  51429. var targetPropertyPath = this._animation.targetPropertyPath;
  51430. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51431. this._stopped = true;
  51432. return false;
  51433. }
  51434. var returnValue = true;
  51435. var keys = this._animation.getKeys();
  51436. // Adding a start key at frame 0 if missing
  51437. if (keys[0].frame !== 0) {
  51438. var newKey = { frame: 0, value: keys[0].value };
  51439. keys.splice(0, 0, newKey);
  51440. }
  51441. // Adding a duplicate key when there is only one key at frame zero
  51442. else if (keys.length === 1) {
  51443. var newKey = { frame: 0.001, value: keys[0].value };
  51444. keys.push(newKey);
  51445. }
  51446. // Check limits
  51447. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51448. from = keys[0].frame;
  51449. }
  51450. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51451. to = keys[keys.length - 1].frame;
  51452. }
  51453. //to and from cannot be the same key
  51454. if (from === to) {
  51455. if (from > keys[0].frame) {
  51456. from--;
  51457. }
  51458. else if (to < keys[keys.length - 1].frame) {
  51459. to++;
  51460. }
  51461. }
  51462. // Compute ratio
  51463. var range = to - from;
  51464. var offsetValue;
  51465. // ratio represents the frame delta between from and to
  51466. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51467. var highLimitValue = 0;
  51468. this._previousDelay = delay;
  51469. this._previousRatio = ratio;
  51470. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51471. returnValue = false;
  51472. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51473. }
  51474. else {
  51475. // Get max value if required
  51476. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51477. var keyOffset = to.toString() + from.toString();
  51478. if (!this._offsetsCache[keyOffset]) {
  51479. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51480. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51481. switch (this._animation.dataType) {
  51482. // Float
  51483. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51484. this._offsetsCache[keyOffset] = toValue - fromValue;
  51485. break;
  51486. // Quaternion
  51487. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51488. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51489. break;
  51490. // Vector3
  51491. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51492. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51493. // Vector2
  51494. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51495. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51496. // Size
  51497. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51498. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51499. // Color3
  51500. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51501. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51502. default:
  51503. break;
  51504. }
  51505. this._highLimitsCache[keyOffset] = toValue;
  51506. }
  51507. highLimitValue = this._highLimitsCache[keyOffset];
  51508. offsetValue = this._offsetsCache[keyOffset];
  51509. }
  51510. }
  51511. if (offsetValue === undefined) {
  51512. switch (this._animation.dataType) {
  51513. // Float
  51514. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51515. offsetValue = 0;
  51516. break;
  51517. // Quaternion
  51518. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51519. offsetValue = _staticOffsetValueQuaternion;
  51520. break;
  51521. // Vector3
  51522. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51523. offsetValue = _staticOffsetValueVector3;
  51524. break;
  51525. // Vector2
  51526. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51527. offsetValue = _staticOffsetValueVector2;
  51528. break;
  51529. // Size
  51530. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51531. offsetValue = _staticOffsetValueSize;
  51532. break;
  51533. // Color3
  51534. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51535. offsetValue = _staticOffsetValueColor3;
  51536. }
  51537. }
  51538. // Compute value
  51539. var repeatCount = (ratio / range) >> 0;
  51540. var currentFrame = returnValue ? from + ratio % range : to;
  51541. // Need to normalize?
  51542. if (this._host && this._host.syncRoot) {
  51543. var syncRoot = this._host.syncRoot;
  51544. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51545. currentFrame = from + (to - from) * hostNormalizedFrame;
  51546. }
  51547. // Reset events if looping
  51548. var events = this._events;
  51549. if (range > 0 && this.currentFrame > currentFrame ||
  51550. range < 0 && this.currentFrame < currentFrame) {
  51551. // Need to reset animation events
  51552. for (var index = 0; index < events.length; index++) {
  51553. if (!events[index].onlyOnce) {
  51554. // reset event, the animation is looping
  51555. events[index].isDone = false;
  51556. }
  51557. }
  51558. }
  51559. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51560. // Set value
  51561. this.setValue(currentValue, weight);
  51562. // Check events
  51563. for (var index = 0; index < events.length; index++) {
  51564. // Make sure current frame has passed event frame and that event frame is within the current range
  51565. // Also, handle both forward and reverse animations
  51566. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51567. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51568. var event = events[index];
  51569. if (!event.isDone) {
  51570. // If event should be done only once, remove it.
  51571. if (event.onlyOnce) {
  51572. events.splice(index, 1);
  51573. index--;
  51574. }
  51575. event.isDone = true;
  51576. event.action(currentFrame);
  51577. } // Don't do anything if the event has already be done.
  51578. }
  51579. }
  51580. if (!returnValue) {
  51581. this._stopped = true;
  51582. }
  51583. return returnValue;
  51584. };
  51585. return RuntimeAnimation;
  51586. }());
  51587. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51588. })(BABYLON || (BABYLON = {}));
  51589. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51590. var BABYLON;
  51591. (function (BABYLON) {
  51592. /**
  51593. * Class used to store an actual running animation
  51594. */
  51595. var Animatable = /** @class */ (function () {
  51596. /**
  51597. * Creates a new Animatable
  51598. * @param scene defines the hosting scene
  51599. * @param target defines the target object
  51600. * @param fromFrame defines the starting frame number (default is 0)
  51601. * @param toFrame defines the ending frame number (default is 100)
  51602. * @param loopAnimation defines if the animation must loop (default is false)
  51603. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51604. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51605. * @param animations defines a group of animation to add to the new Animatable
  51606. */
  51607. function Animatable(scene,
  51608. /** defines the target object */
  51609. target,
  51610. /** defines the starting frame number (default is 0) */
  51611. fromFrame,
  51612. /** defines the ending frame number (default is 100) */
  51613. toFrame,
  51614. /** defines if the animation must loop (default is false) */
  51615. loopAnimation, speedRatio,
  51616. /** defines a callback to call when animation ends if it is not looping */
  51617. onAnimationEnd, animations) {
  51618. if (fromFrame === void 0) { fromFrame = 0; }
  51619. if (toFrame === void 0) { toFrame = 100; }
  51620. if (loopAnimation === void 0) { loopAnimation = false; }
  51621. if (speedRatio === void 0) { speedRatio = 1.0; }
  51622. this.target = target;
  51623. this.fromFrame = fromFrame;
  51624. this.toFrame = toFrame;
  51625. this.loopAnimation = loopAnimation;
  51626. this.onAnimationEnd = onAnimationEnd;
  51627. this._localDelayOffset = null;
  51628. this._pausedDelay = null;
  51629. this._runtimeAnimations = new Array();
  51630. this._paused = false;
  51631. this._speedRatio = 1;
  51632. this._weight = -1.0;
  51633. /**
  51634. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51635. * This will only apply for non looping animation (default is true)
  51636. */
  51637. this.disposeOnEnd = true;
  51638. /**
  51639. * Gets a boolean indicating if the animation has started
  51640. */
  51641. this.animationStarted = false;
  51642. /**
  51643. * Observer raised when the animation ends
  51644. */
  51645. this.onAnimationEndObservable = new BABYLON.Observable();
  51646. this._scene = scene;
  51647. if (animations) {
  51648. this.appendAnimations(target, animations);
  51649. }
  51650. this._speedRatio = speedRatio;
  51651. scene._activeAnimatables.push(this);
  51652. }
  51653. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51654. /**
  51655. * Gets the root Animatable used to synchronize and normalize animations
  51656. */
  51657. get: function () {
  51658. return this._syncRoot;
  51659. },
  51660. enumerable: true,
  51661. configurable: true
  51662. });
  51663. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51664. /**
  51665. * Gets the current frame of the first RuntimeAnimation
  51666. * Used to synchronize Animatables
  51667. */
  51668. get: function () {
  51669. if (this._runtimeAnimations.length === 0) {
  51670. return 0;
  51671. }
  51672. return this._runtimeAnimations[0].currentFrame;
  51673. },
  51674. enumerable: true,
  51675. configurable: true
  51676. });
  51677. Object.defineProperty(Animatable.prototype, "weight", {
  51678. /**
  51679. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51680. */
  51681. get: function () {
  51682. return this._weight;
  51683. },
  51684. set: function (value) {
  51685. if (value === -1) { // -1 is ok and means no weight
  51686. this._weight = -1;
  51687. return;
  51688. }
  51689. // Else weight must be in [0, 1] range
  51690. this._weight = Math.min(Math.max(value, 0), 1.0);
  51691. },
  51692. enumerable: true,
  51693. configurable: true
  51694. });
  51695. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51696. /**
  51697. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51698. */
  51699. get: function () {
  51700. return this._speedRatio;
  51701. },
  51702. set: function (value) {
  51703. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51704. var animation = this._runtimeAnimations[index];
  51705. animation._prepareForSpeedRatioChange(value);
  51706. }
  51707. this._speedRatio = value;
  51708. },
  51709. enumerable: true,
  51710. configurable: true
  51711. });
  51712. // Methods
  51713. /**
  51714. * Synchronize and normalize current Animatable with a source Animatable
  51715. * This is useful when using animation weights and when animations are not of the same length
  51716. * @param root defines the root Animatable to synchronize with
  51717. * @returns the current Animatable
  51718. */
  51719. Animatable.prototype.syncWith = function (root) {
  51720. this._syncRoot = root;
  51721. if (root) {
  51722. // Make sure this animatable will animate after the root
  51723. var index = this._scene._activeAnimatables.indexOf(this);
  51724. if (index > -1) {
  51725. this._scene._activeAnimatables.splice(index, 1);
  51726. this._scene._activeAnimatables.push(this);
  51727. }
  51728. }
  51729. return this;
  51730. };
  51731. /**
  51732. * Gets the list of runtime animations
  51733. * @returns an array of RuntimeAnimation
  51734. */
  51735. Animatable.prototype.getAnimations = function () {
  51736. return this._runtimeAnimations;
  51737. };
  51738. /**
  51739. * Adds more animations to the current animatable
  51740. * @param target defines the target of the animations
  51741. * @param animations defines the new animations to add
  51742. */
  51743. Animatable.prototype.appendAnimations = function (target, animations) {
  51744. for (var index = 0; index < animations.length; index++) {
  51745. var animation = animations[index];
  51746. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51747. }
  51748. };
  51749. /**
  51750. * Gets the source animation for a specific property
  51751. * @param property defines the propertyu to look for
  51752. * @returns null or the source animation for the given property
  51753. */
  51754. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51755. var runtimeAnimations = this._runtimeAnimations;
  51756. for (var index = 0; index < runtimeAnimations.length; index++) {
  51757. if (runtimeAnimations[index].animation.targetProperty === property) {
  51758. return runtimeAnimations[index].animation;
  51759. }
  51760. }
  51761. return null;
  51762. };
  51763. /**
  51764. * Gets the runtime animation for a specific property
  51765. * @param property defines the propertyu to look for
  51766. * @returns null or the runtime animation for the given property
  51767. */
  51768. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51769. var runtimeAnimations = this._runtimeAnimations;
  51770. for (var index = 0; index < runtimeAnimations.length; index++) {
  51771. if (runtimeAnimations[index].animation.targetProperty === property) {
  51772. return runtimeAnimations[index];
  51773. }
  51774. }
  51775. return null;
  51776. };
  51777. /**
  51778. * Resets the animatable to its original state
  51779. */
  51780. Animatable.prototype.reset = function () {
  51781. var runtimeAnimations = this._runtimeAnimations;
  51782. for (var index = 0; index < runtimeAnimations.length; index++) {
  51783. runtimeAnimations[index].reset(true);
  51784. }
  51785. this._localDelayOffset = null;
  51786. this._pausedDelay = null;
  51787. };
  51788. /**
  51789. * Allows the animatable to blend with current running animations
  51790. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51791. * @param blendingSpeed defines the blending speed to use
  51792. */
  51793. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51794. var runtimeAnimations = this._runtimeAnimations;
  51795. for (var index = 0; index < runtimeAnimations.length; index++) {
  51796. runtimeAnimations[index].animation.enableBlending = true;
  51797. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51798. }
  51799. };
  51800. /**
  51801. * Disable animation blending
  51802. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51803. */
  51804. Animatable.prototype.disableBlending = function () {
  51805. var runtimeAnimations = this._runtimeAnimations;
  51806. for (var index = 0; index < runtimeAnimations.length; index++) {
  51807. runtimeAnimations[index].animation.enableBlending = false;
  51808. }
  51809. };
  51810. /**
  51811. * Jump directly to a given frame
  51812. * @param frame defines the frame to jump to
  51813. */
  51814. Animatable.prototype.goToFrame = function (frame) {
  51815. var runtimeAnimations = this._runtimeAnimations;
  51816. if (runtimeAnimations[0]) {
  51817. var fps = runtimeAnimations[0].animation.framePerSecond;
  51818. var currentFrame = runtimeAnimations[0].currentFrame;
  51819. var adjustTime = frame - currentFrame;
  51820. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51821. if (this._localDelayOffset === null) {
  51822. this._localDelayOffset = 0;
  51823. }
  51824. this._localDelayOffset -= delay;
  51825. }
  51826. for (var index = 0; index < runtimeAnimations.length; index++) {
  51827. runtimeAnimations[index].goToFrame(frame);
  51828. }
  51829. };
  51830. /**
  51831. * Pause the animation
  51832. */
  51833. Animatable.prototype.pause = function () {
  51834. if (this._paused) {
  51835. return;
  51836. }
  51837. this._paused = true;
  51838. };
  51839. /**
  51840. * Restart the animation
  51841. */
  51842. Animatable.prototype.restart = function () {
  51843. this._paused = false;
  51844. };
  51845. Animatable.prototype._raiseOnAnimationEnd = function () {
  51846. if (this.onAnimationEnd) {
  51847. this.onAnimationEnd();
  51848. }
  51849. this.onAnimationEndObservable.notifyObservers(this);
  51850. };
  51851. /**
  51852. * Stop and delete the current animation
  51853. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51854. * @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)
  51855. */
  51856. Animatable.prototype.stop = function (animationName, targetMask) {
  51857. if (animationName || targetMask) {
  51858. var idx = this._scene._activeAnimatables.indexOf(this);
  51859. if (idx > -1) {
  51860. var runtimeAnimations = this._runtimeAnimations;
  51861. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51862. var runtimeAnimation = runtimeAnimations[index];
  51863. if (animationName && runtimeAnimation.animation.name != animationName) {
  51864. continue;
  51865. }
  51866. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51867. continue;
  51868. }
  51869. runtimeAnimation.dispose();
  51870. runtimeAnimations.splice(index, 1);
  51871. }
  51872. if (runtimeAnimations.length == 0) {
  51873. this._scene._activeAnimatables.splice(idx, 1);
  51874. this._raiseOnAnimationEnd();
  51875. }
  51876. }
  51877. }
  51878. else {
  51879. var index = this._scene._activeAnimatables.indexOf(this);
  51880. if (index > -1) {
  51881. this._scene._activeAnimatables.splice(index, 1);
  51882. var runtimeAnimations = this._runtimeAnimations;
  51883. for (var index = 0; index < runtimeAnimations.length; index++) {
  51884. runtimeAnimations[index].dispose();
  51885. }
  51886. this._raiseOnAnimationEnd();
  51887. }
  51888. }
  51889. };
  51890. /**
  51891. * Wait asynchronously for the animation to end
  51892. * @returns a promise which will be fullfilled when the animation ends
  51893. */
  51894. Animatable.prototype.waitAsync = function () {
  51895. var _this = this;
  51896. return new Promise(function (resolve, reject) {
  51897. _this.onAnimationEndObservable.add(function () {
  51898. resolve(_this);
  51899. }, undefined, undefined, _this, true);
  51900. });
  51901. };
  51902. /** @hidden */
  51903. Animatable.prototype._animate = function (delay) {
  51904. if (this._paused) {
  51905. this.animationStarted = false;
  51906. if (this._pausedDelay === null) {
  51907. this._pausedDelay = delay;
  51908. }
  51909. return true;
  51910. }
  51911. if (this._localDelayOffset === null) {
  51912. this._localDelayOffset = delay;
  51913. this._pausedDelay = null;
  51914. }
  51915. else if (this._pausedDelay !== null) {
  51916. this._localDelayOffset += delay - this._pausedDelay;
  51917. this._pausedDelay = null;
  51918. }
  51919. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51920. return true;
  51921. }
  51922. // Animating
  51923. var running = false;
  51924. var runtimeAnimations = this._runtimeAnimations;
  51925. var index;
  51926. for (index = 0; index < runtimeAnimations.length; index++) {
  51927. var animation = runtimeAnimations[index];
  51928. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51929. running = running || isRunning;
  51930. }
  51931. this.animationStarted = running;
  51932. if (!running) {
  51933. if (this.disposeOnEnd) {
  51934. // Remove from active animatables
  51935. index = this._scene._activeAnimatables.indexOf(this);
  51936. this._scene._activeAnimatables.splice(index, 1);
  51937. // Dispose all runtime animations
  51938. for (index = 0; index < runtimeAnimations.length; index++) {
  51939. runtimeAnimations[index].dispose();
  51940. }
  51941. }
  51942. this._raiseOnAnimationEnd();
  51943. if (this.disposeOnEnd) {
  51944. this.onAnimationEnd = null;
  51945. this.onAnimationEndObservable.clear();
  51946. }
  51947. }
  51948. return running;
  51949. };
  51950. return Animatable;
  51951. }());
  51952. BABYLON.Animatable = Animatable;
  51953. })(BABYLON || (BABYLON = {}));
  51954. //# sourceMappingURL=babylon.animatable.js.map
  51955. var BABYLON;
  51956. (function (BABYLON) {
  51957. var EasingFunction = /** @class */ (function () {
  51958. function EasingFunction() {
  51959. // Properties
  51960. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51961. }
  51962. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51963. get: function () {
  51964. return EasingFunction._EASINGMODE_EASEIN;
  51965. },
  51966. enumerable: true,
  51967. configurable: true
  51968. });
  51969. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51970. get: function () {
  51971. return EasingFunction._EASINGMODE_EASEOUT;
  51972. },
  51973. enumerable: true,
  51974. configurable: true
  51975. });
  51976. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51977. get: function () {
  51978. return EasingFunction._EASINGMODE_EASEINOUT;
  51979. },
  51980. enumerable: true,
  51981. configurable: true
  51982. });
  51983. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51984. var n = Math.min(Math.max(easingMode, 0), 2);
  51985. this._easingMode = n;
  51986. };
  51987. EasingFunction.prototype.getEasingMode = function () {
  51988. return this._easingMode;
  51989. };
  51990. EasingFunction.prototype.easeInCore = function (gradient) {
  51991. throw new Error('You must implement this method');
  51992. };
  51993. EasingFunction.prototype.ease = function (gradient) {
  51994. switch (this._easingMode) {
  51995. case EasingFunction.EASINGMODE_EASEIN:
  51996. return this.easeInCore(gradient);
  51997. case EasingFunction.EASINGMODE_EASEOUT:
  51998. return (1 - this.easeInCore(1 - gradient));
  51999. }
  52000. if (gradient >= 0.5) {
  52001. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52002. }
  52003. return (this.easeInCore(gradient * 2) * 0.5);
  52004. };
  52005. //Statics
  52006. EasingFunction._EASINGMODE_EASEIN = 0;
  52007. EasingFunction._EASINGMODE_EASEOUT = 1;
  52008. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52009. return EasingFunction;
  52010. }());
  52011. BABYLON.EasingFunction = EasingFunction;
  52012. var CircleEase = /** @class */ (function (_super) {
  52013. __extends(CircleEase, _super);
  52014. function CircleEase() {
  52015. return _super !== null && _super.apply(this, arguments) || this;
  52016. }
  52017. CircleEase.prototype.easeInCore = function (gradient) {
  52018. gradient = Math.max(0, Math.min(1, gradient));
  52019. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52020. };
  52021. return CircleEase;
  52022. }(EasingFunction));
  52023. BABYLON.CircleEase = CircleEase;
  52024. var BackEase = /** @class */ (function (_super) {
  52025. __extends(BackEase, _super);
  52026. function BackEase(amplitude) {
  52027. if (amplitude === void 0) { amplitude = 1; }
  52028. var _this = _super.call(this) || this;
  52029. _this.amplitude = amplitude;
  52030. return _this;
  52031. }
  52032. BackEase.prototype.easeInCore = function (gradient) {
  52033. var num = Math.max(0, this.amplitude);
  52034. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52035. };
  52036. return BackEase;
  52037. }(EasingFunction));
  52038. BABYLON.BackEase = BackEase;
  52039. var BounceEase = /** @class */ (function (_super) {
  52040. __extends(BounceEase, _super);
  52041. function BounceEase(bounces, bounciness) {
  52042. if (bounces === void 0) { bounces = 3; }
  52043. if (bounciness === void 0) { bounciness = 2; }
  52044. var _this = _super.call(this) || this;
  52045. _this.bounces = bounces;
  52046. _this.bounciness = bounciness;
  52047. return _this;
  52048. }
  52049. BounceEase.prototype.easeInCore = function (gradient) {
  52050. var y = Math.max(0.0, this.bounces);
  52051. var bounciness = this.bounciness;
  52052. if (bounciness <= 1.0) {
  52053. bounciness = 1.001;
  52054. }
  52055. var num9 = Math.pow(bounciness, y);
  52056. var num5 = 1.0 - bounciness;
  52057. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52058. var num15 = gradient * num4;
  52059. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52060. var num3 = Math.floor(num65);
  52061. var num13 = num3 + 1.0;
  52062. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52063. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52064. var num7 = (num8 + num12) * 0.5;
  52065. var num6 = gradient - num7;
  52066. var num2 = num7 - num8;
  52067. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52068. };
  52069. return BounceEase;
  52070. }(EasingFunction));
  52071. BABYLON.BounceEase = BounceEase;
  52072. var CubicEase = /** @class */ (function (_super) {
  52073. __extends(CubicEase, _super);
  52074. function CubicEase() {
  52075. return _super !== null && _super.apply(this, arguments) || this;
  52076. }
  52077. CubicEase.prototype.easeInCore = function (gradient) {
  52078. return (gradient * gradient * gradient);
  52079. };
  52080. return CubicEase;
  52081. }(EasingFunction));
  52082. BABYLON.CubicEase = CubicEase;
  52083. var ElasticEase = /** @class */ (function (_super) {
  52084. __extends(ElasticEase, _super);
  52085. function ElasticEase(oscillations, springiness) {
  52086. if (oscillations === void 0) { oscillations = 3; }
  52087. if (springiness === void 0) { springiness = 3; }
  52088. var _this = _super.call(this) || this;
  52089. _this.oscillations = oscillations;
  52090. _this.springiness = springiness;
  52091. return _this;
  52092. }
  52093. ElasticEase.prototype.easeInCore = function (gradient) {
  52094. var num2;
  52095. var num3 = Math.max(0.0, this.oscillations);
  52096. var num = Math.max(0.0, this.springiness);
  52097. if (num == 0) {
  52098. num2 = gradient;
  52099. }
  52100. else {
  52101. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52102. }
  52103. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52104. };
  52105. return ElasticEase;
  52106. }(EasingFunction));
  52107. BABYLON.ElasticEase = ElasticEase;
  52108. var ExponentialEase = /** @class */ (function (_super) {
  52109. __extends(ExponentialEase, _super);
  52110. function ExponentialEase(exponent) {
  52111. if (exponent === void 0) { exponent = 2; }
  52112. var _this = _super.call(this) || this;
  52113. _this.exponent = exponent;
  52114. return _this;
  52115. }
  52116. ExponentialEase.prototype.easeInCore = function (gradient) {
  52117. if (this.exponent <= 0) {
  52118. return gradient;
  52119. }
  52120. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52121. };
  52122. return ExponentialEase;
  52123. }(EasingFunction));
  52124. BABYLON.ExponentialEase = ExponentialEase;
  52125. var PowerEase = /** @class */ (function (_super) {
  52126. __extends(PowerEase, _super);
  52127. function PowerEase(power) {
  52128. if (power === void 0) { power = 2; }
  52129. var _this = _super.call(this) || this;
  52130. _this.power = power;
  52131. return _this;
  52132. }
  52133. PowerEase.prototype.easeInCore = function (gradient) {
  52134. var y = Math.max(0.0, this.power);
  52135. return Math.pow(gradient, y);
  52136. };
  52137. return PowerEase;
  52138. }(EasingFunction));
  52139. BABYLON.PowerEase = PowerEase;
  52140. var QuadraticEase = /** @class */ (function (_super) {
  52141. __extends(QuadraticEase, _super);
  52142. function QuadraticEase() {
  52143. return _super !== null && _super.apply(this, arguments) || this;
  52144. }
  52145. QuadraticEase.prototype.easeInCore = function (gradient) {
  52146. return (gradient * gradient);
  52147. };
  52148. return QuadraticEase;
  52149. }(EasingFunction));
  52150. BABYLON.QuadraticEase = QuadraticEase;
  52151. var QuarticEase = /** @class */ (function (_super) {
  52152. __extends(QuarticEase, _super);
  52153. function QuarticEase() {
  52154. return _super !== null && _super.apply(this, arguments) || this;
  52155. }
  52156. QuarticEase.prototype.easeInCore = function (gradient) {
  52157. return (gradient * gradient * gradient * gradient);
  52158. };
  52159. return QuarticEase;
  52160. }(EasingFunction));
  52161. BABYLON.QuarticEase = QuarticEase;
  52162. var QuinticEase = /** @class */ (function (_super) {
  52163. __extends(QuinticEase, _super);
  52164. function QuinticEase() {
  52165. return _super !== null && _super.apply(this, arguments) || this;
  52166. }
  52167. QuinticEase.prototype.easeInCore = function (gradient) {
  52168. return (gradient * gradient * gradient * gradient * gradient);
  52169. };
  52170. return QuinticEase;
  52171. }(EasingFunction));
  52172. BABYLON.QuinticEase = QuinticEase;
  52173. var SineEase = /** @class */ (function (_super) {
  52174. __extends(SineEase, _super);
  52175. function SineEase() {
  52176. return _super !== null && _super.apply(this, arguments) || this;
  52177. }
  52178. SineEase.prototype.easeInCore = function (gradient) {
  52179. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52180. };
  52181. return SineEase;
  52182. }(EasingFunction));
  52183. BABYLON.SineEase = SineEase;
  52184. var BezierCurveEase = /** @class */ (function (_super) {
  52185. __extends(BezierCurveEase, _super);
  52186. function BezierCurveEase(x1, y1, x2, y2) {
  52187. if (x1 === void 0) { x1 = 0; }
  52188. if (y1 === void 0) { y1 = 0; }
  52189. if (x2 === void 0) { x2 = 1; }
  52190. if (y2 === void 0) { y2 = 1; }
  52191. var _this = _super.call(this) || this;
  52192. _this.x1 = x1;
  52193. _this.y1 = y1;
  52194. _this.x2 = x2;
  52195. _this.y2 = y2;
  52196. return _this;
  52197. }
  52198. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52199. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52200. };
  52201. return BezierCurveEase;
  52202. }(EasingFunction));
  52203. BABYLON.BezierCurveEase = BezierCurveEase;
  52204. })(BABYLON || (BABYLON = {}));
  52205. //# sourceMappingURL=babylon.easing.js.map
  52206. var BABYLON;
  52207. (function (BABYLON) {
  52208. /**
  52209. * A Condition applied to an Action
  52210. */
  52211. var Condition = /** @class */ (function () {
  52212. /**
  52213. * Creates a new Condition
  52214. * @param actionManager the manager of the action the condition is applied to
  52215. */
  52216. function Condition(actionManager) {
  52217. this._actionManager = actionManager;
  52218. }
  52219. /**
  52220. * Check if the current condition is valid
  52221. * @returns a boolean
  52222. */
  52223. Condition.prototype.isValid = function () {
  52224. return true;
  52225. };
  52226. /**
  52227. * Internal only
  52228. * @hidden
  52229. */
  52230. Condition.prototype._getProperty = function (propertyPath) {
  52231. return this._actionManager._getProperty(propertyPath);
  52232. };
  52233. /**
  52234. * Internal only
  52235. * @hidden
  52236. */
  52237. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52238. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52239. };
  52240. /**
  52241. * Serialize placeholder for child classes
  52242. * @returns the serialized object
  52243. */
  52244. Condition.prototype.serialize = function () {
  52245. };
  52246. /**
  52247. * Internal only
  52248. * @hidden
  52249. */
  52250. Condition.prototype._serialize = function (serializedCondition) {
  52251. return {
  52252. type: 2,
  52253. children: [],
  52254. name: serializedCondition.name,
  52255. properties: serializedCondition.properties
  52256. };
  52257. };
  52258. return Condition;
  52259. }());
  52260. BABYLON.Condition = Condition;
  52261. /**
  52262. * Defines specific conditional operators as extensions of Condition
  52263. */
  52264. var ValueCondition = /** @class */ (function (_super) {
  52265. __extends(ValueCondition, _super);
  52266. /**
  52267. * Creates a new ValueCondition
  52268. * @param actionManager manager for the action the condition applies to
  52269. * @param target for the action
  52270. * @param propertyPath path to specify the property of the target the conditional operator uses
  52271. * @param value the value compared by the conditional operator against the current value of the property
  52272. * @param operator the conditional operator, default ValueCondition.IsEqual
  52273. */
  52274. function ValueCondition(actionManager, target,
  52275. /** path to specify the property of the target the conditional operator uses */
  52276. propertyPath,
  52277. /** the value compared by the conditional operator against the current value of the property */
  52278. value,
  52279. /** the conditional operator, default ValueCondition.IsEqual */
  52280. operator) {
  52281. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52282. var _this = _super.call(this, actionManager) || this;
  52283. _this.propertyPath = propertyPath;
  52284. _this.value = value;
  52285. _this.operator = operator;
  52286. _this._target = target;
  52287. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52288. _this._property = _this._getProperty(_this.propertyPath);
  52289. return _this;
  52290. }
  52291. Object.defineProperty(ValueCondition, "IsEqual", {
  52292. /**
  52293. * returns the number for IsEqual
  52294. */
  52295. get: function () {
  52296. return ValueCondition._IsEqual;
  52297. },
  52298. enumerable: true,
  52299. configurable: true
  52300. });
  52301. Object.defineProperty(ValueCondition, "IsDifferent", {
  52302. /**
  52303. * Returns the number for IsDifferent
  52304. */
  52305. get: function () {
  52306. return ValueCondition._IsDifferent;
  52307. },
  52308. enumerable: true,
  52309. configurable: true
  52310. });
  52311. Object.defineProperty(ValueCondition, "IsGreater", {
  52312. /**
  52313. * Returns the number for IsGreater
  52314. */
  52315. get: function () {
  52316. return ValueCondition._IsGreater;
  52317. },
  52318. enumerable: true,
  52319. configurable: true
  52320. });
  52321. Object.defineProperty(ValueCondition, "IsLesser", {
  52322. /**
  52323. * Returns the number for IsLesser
  52324. */
  52325. get: function () {
  52326. return ValueCondition._IsLesser;
  52327. },
  52328. enumerable: true,
  52329. configurable: true
  52330. });
  52331. /**
  52332. * Compares the given value with the property value for the specified conditional operator
  52333. * @returns the result of the comparison
  52334. */
  52335. ValueCondition.prototype.isValid = function () {
  52336. switch (this.operator) {
  52337. case ValueCondition.IsGreater:
  52338. return this._effectiveTarget[this._property] > this.value;
  52339. case ValueCondition.IsLesser:
  52340. return this._effectiveTarget[this._property] < this.value;
  52341. case ValueCondition.IsEqual:
  52342. case ValueCondition.IsDifferent:
  52343. var check;
  52344. if (this.value.equals) {
  52345. check = this.value.equals(this._effectiveTarget[this._property]);
  52346. }
  52347. else {
  52348. check = this.value === this._effectiveTarget[this._property];
  52349. }
  52350. return this.operator === ValueCondition.IsEqual ? check : !check;
  52351. }
  52352. return false;
  52353. };
  52354. /**
  52355. * Serialize the ValueCondition into a JSON compatible object
  52356. * @returns serialization object
  52357. */
  52358. ValueCondition.prototype.serialize = function () {
  52359. return this._serialize({
  52360. name: "ValueCondition",
  52361. properties: [
  52362. BABYLON.Action._GetTargetProperty(this._target),
  52363. { name: "propertyPath", value: this.propertyPath },
  52364. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52365. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52366. ]
  52367. });
  52368. };
  52369. /**
  52370. * Gets the name of the conditional operator for the ValueCondition
  52371. * @param operator the conditional operator
  52372. * @returns the name
  52373. */
  52374. ValueCondition.GetOperatorName = function (operator) {
  52375. switch (operator) {
  52376. case ValueCondition._IsEqual: return "IsEqual";
  52377. case ValueCondition._IsDifferent: return "IsDifferent";
  52378. case ValueCondition._IsGreater: return "IsGreater";
  52379. case ValueCondition._IsLesser: return "IsLesser";
  52380. default: return "";
  52381. }
  52382. };
  52383. /**
  52384. * Internal only
  52385. * @hidden
  52386. */
  52387. ValueCondition._IsEqual = 0;
  52388. /**
  52389. * Internal only
  52390. * @hidden
  52391. */
  52392. ValueCondition._IsDifferent = 1;
  52393. /**
  52394. * Internal only
  52395. * @hidden
  52396. */
  52397. ValueCondition._IsGreater = 2;
  52398. /**
  52399. * Internal only
  52400. * @hidden
  52401. */
  52402. ValueCondition._IsLesser = 3;
  52403. return ValueCondition;
  52404. }(Condition));
  52405. BABYLON.ValueCondition = ValueCondition;
  52406. /**
  52407. * Defines a predicate condition as an extension of Condition
  52408. */
  52409. var PredicateCondition = /** @class */ (function (_super) {
  52410. __extends(PredicateCondition, _super);
  52411. /**
  52412. * Creates a new PredicateCondition
  52413. * @param actionManager manager for the action the condition applies to
  52414. * @param predicate defines the predicate function used to validate the condition
  52415. */
  52416. function PredicateCondition(actionManager,
  52417. /** defines the predicate function used to validate the condition */
  52418. predicate) {
  52419. var _this = _super.call(this, actionManager) || this;
  52420. _this.predicate = predicate;
  52421. return _this;
  52422. }
  52423. /**
  52424. * @returns the validity of the predicate condition
  52425. */
  52426. PredicateCondition.prototype.isValid = function () {
  52427. return this.predicate();
  52428. };
  52429. return PredicateCondition;
  52430. }(Condition));
  52431. BABYLON.PredicateCondition = PredicateCondition;
  52432. /**
  52433. * Defines a state condition as an extension of Condition
  52434. */
  52435. var StateCondition = /** @class */ (function (_super) {
  52436. __extends(StateCondition, _super);
  52437. /**
  52438. * Creates a new StateCondition
  52439. * @param actionManager manager for the action the condition applies to
  52440. * @param target of the condition
  52441. * @param value to compare with target state
  52442. */
  52443. function StateCondition(actionManager, target, value) {
  52444. var _this = _super.call(this, actionManager) || this;
  52445. _this.value = value;
  52446. _this._target = target;
  52447. return _this;
  52448. }
  52449. /**
  52450. * @returns the validity of the state
  52451. */
  52452. StateCondition.prototype.isValid = function () {
  52453. return this._target.state === this.value;
  52454. };
  52455. /**
  52456. * Serialize the StateCondition into a JSON compatible object
  52457. * @returns serialization object
  52458. */
  52459. StateCondition.prototype.serialize = function () {
  52460. return this._serialize({
  52461. name: "StateCondition",
  52462. properties: [
  52463. BABYLON.Action._GetTargetProperty(this._target),
  52464. { name: "value", value: this.value }
  52465. ]
  52466. });
  52467. };
  52468. return StateCondition;
  52469. }(Condition));
  52470. BABYLON.StateCondition = StateCondition;
  52471. })(BABYLON || (BABYLON = {}));
  52472. //# sourceMappingURL=babylon.condition.js.map
  52473. var BABYLON;
  52474. (function (BABYLON) {
  52475. /**
  52476. * The action to be carried out following a trigger
  52477. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52478. */
  52479. var Action = /** @class */ (function () {
  52480. /**
  52481. * Creates a new Action
  52482. * @param triggerOptions the trigger, with or without parameters, for the action
  52483. * @param condition an optional determinant of action
  52484. */
  52485. function Action(
  52486. /** the trigger, with or without parameters, for the action */
  52487. triggerOptions, condition) {
  52488. this.triggerOptions = triggerOptions;
  52489. /**
  52490. * An event triggered prior to action being executed.
  52491. */
  52492. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52493. if (triggerOptions.parameter) {
  52494. this.trigger = triggerOptions.trigger;
  52495. this._triggerParameter = triggerOptions.parameter;
  52496. }
  52497. else if (triggerOptions.trigger) {
  52498. this.trigger = triggerOptions.trigger;
  52499. }
  52500. else {
  52501. this.trigger = triggerOptions;
  52502. }
  52503. this._nextActiveAction = this;
  52504. this._condition = condition;
  52505. }
  52506. /**
  52507. * Internal only
  52508. * @hidden
  52509. */
  52510. Action.prototype._prepare = function () {
  52511. };
  52512. /**
  52513. * Gets the trigger parameters
  52514. * @returns the trigger parameters
  52515. */
  52516. Action.prototype.getTriggerParameter = function () {
  52517. return this._triggerParameter;
  52518. };
  52519. /**
  52520. * Internal only - executes current action event
  52521. * @hidden
  52522. */
  52523. Action.prototype._executeCurrent = function (evt) {
  52524. if (this._nextActiveAction._condition) {
  52525. var condition = this._nextActiveAction._condition;
  52526. var currentRenderId = this._actionManager.getScene().getRenderId();
  52527. // We cache the current evaluation for the current frame
  52528. if (condition._evaluationId === currentRenderId) {
  52529. if (!condition._currentResult) {
  52530. return;
  52531. }
  52532. }
  52533. else {
  52534. condition._evaluationId = currentRenderId;
  52535. if (!condition.isValid()) {
  52536. condition._currentResult = false;
  52537. return;
  52538. }
  52539. condition._currentResult = true;
  52540. }
  52541. }
  52542. this.onBeforeExecuteObservable.notifyObservers(this);
  52543. this._nextActiveAction.execute(evt);
  52544. this.skipToNextActiveAction();
  52545. };
  52546. /**
  52547. * Execute placeholder for child classes
  52548. * @param evt optional action event
  52549. */
  52550. Action.prototype.execute = function (evt) {
  52551. };
  52552. /**
  52553. * Skips to next active action
  52554. */
  52555. Action.prototype.skipToNextActiveAction = function () {
  52556. if (this._nextActiveAction._child) {
  52557. if (!this._nextActiveAction._child._actionManager) {
  52558. this._nextActiveAction._child._actionManager = this._actionManager;
  52559. }
  52560. this._nextActiveAction = this._nextActiveAction._child;
  52561. }
  52562. else {
  52563. this._nextActiveAction = this;
  52564. }
  52565. };
  52566. /**
  52567. * Adds action to chain of actions, may be a DoNothingAction
  52568. * @param action defines the next action to execute
  52569. * @returns The action passed in
  52570. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52571. */
  52572. Action.prototype.then = function (action) {
  52573. this._child = action;
  52574. action._actionManager = this._actionManager;
  52575. action._prepare();
  52576. return action;
  52577. };
  52578. /**
  52579. * Internal only
  52580. * @hidden
  52581. */
  52582. Action.prototype._getProperty = function (propertyPath) {
  52583. return this._actionManager._getProperty(propertyPath);
  52584. };
  52585. /**
  52586. * Internal only
  52587. * @hidden
  52588. */
  52589. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52590. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52591. };
  52592. /**
  52593. * Serialize placeholder for child classes
  52594. * @param parent of child
  52595. * @returns the serialized object
  52596. */
  52597. Action.prototype.serialize = function (parent) {
  52598. };
  52599. /**
  52600. * Internal only called by serialize
  52601. * @hidden
  52602. */
  52603. Action.prototype._serialize = function (serializedAction, parent) {
  52604. var serializationObject = {
  52605. type: 1,
  52606. children: [],
  52607. name: serializedAction.name,
  52608. properties: serializedAction.properties || []
  52609. };
  52610. // Serialize child
  52611. if (this._child) {
  52612. this._child.serialize(serializationObject);
  52613. }
  52614. // Check if "this" has a condition
  52615. if (this._condition) {
  52616. var serializedCondition = this._condition.serialize();
  52617. serializedCondition.children.push(serializationObject);
  52618. if (parent) {
  52619. parent.children.push(serializedCondition);
  52620. }
  52621. return serializedCondition;
  52622. }
  52623. if (parent) {
  52624. parent.children.push(serializationObject);
  52625. }
  52626. return serializationObject;
  52627. };
  52628. /**
  52629. * Internal only
  52630. * @hidden
  52631. */
  52632. Action._SerializeValueAsString = function (value) {
  52633. if (typeof value === "number") {
  52634. return value.toString();
  52635. }
  52636. if (typeof value === "boolean") {
  52637. return value ? "true" : "false";
  52638. }
  52639. if (value instanceof BABYLON.Vector2) {
  52640. return value.x + ", " + value.y;
  52641. }
  52642. if (value instanceof BABYLON.Vector3) {
  52643. return value.x + ", " + value.y + ", " + value.z;
  52644. }
  52645. if (value instanceof BABYLON.Color3) {
  52646. return value.r + ", " + value.g + ", " + value.b;
  52647. }
  52648. if (value instanceof BABYLON.Color4) {
  52649. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52650. }
  52651. return value; // string
  52652. };
  52653. /**
  52654. * Internal only
  52655. * @hidden
  52656. */
  52657. Action._GetTargetProperty = function (target) {
  52658. return {
  52659. name: "target",
  52660. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52661. : target instanceof BABYLON.Light ? "LightProperties"
  52662. : target instanceof BABYLON.Camera ? "CameraProperties"
  52663. : "SceneProperties",
  52664. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52665. };
  52666. };
  52667. return Action;
  52668. }());
  52669. BABYLON.Action = Action;
  52670. })(BABYLON || (BABYLON = {}));
  52671. //# sourceMappingURL=babylon.action.js.map
  52672. var BABYLON;
  52673. (function (BABYLON) {
  52674. /**
  52675. * ActionEvent is the event being sent when an action is triggered.
  52676. */
  52677. var ActionEvent = /** @class */ (function () {
  52678. /**
  52679. * Creates a new ActionEvent
  52680. * @param source The mesh or sprite that triggered the action
  52681. * @param pointerX The X mouse cursor position at the time of the event
  52682. * @param pointerY The Y mouse cursor position at the time of the event
  52683. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52684. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52685. * @param additionalData additional data for the event
  52686. */
  52687. function ActionEvent(
  52688. /** The mesh or sprite that triggered the action */
  52689. source,
  52690. /** The X mouse cursor position at the time of the event */
  52691. pointerX,
  52692. /** The Y mouse cursor position at the time of the event */
  52693. pointerY,
  52694. /** The mesh that is currently pointed at (can be null) */
  52695. meshUnderPointer,
  52696. /** the original (browser) event that triggered the ActionEvent */
  52697. sourceEvent,
  52698. /** additional data for the event */
  52699. additionalData) {
  52700. this.source = source;
  52701. this.pointerX = pointerX;
  52702. this.pointerY = pointerY;
  52703. this.meshUnderPointer = meshUnderPointer;
  52704. this.sourceEvent = sourceEvent;
  52705. this.additionalData = additionalData;
  52706. }
  52707. /**
  52708. * Helper function to auto-create an ActionEvent from a source mesh.
  52709. * @param source The source mesh that triggered the event
  52710. * @param evt The original (browser) event
  52711. * @param additionalData additional data for the event
  52712. * @returns the new ActionEvent
  52713. */
  52714. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52715. var scene = source.getScene();
  52716. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52717. };
  52718. /**
  52719. * Helper function to auto-create an ActionEvent from a source sprite
  52720. * @param source The source sprite that triggered the event
  52721. * @param scene Scene associated with the sprite
  52722. * @param evt The original (browser) event
  52723. * @param additionalData additional data for the event
  52724. * @returns the new ActionEvent
  52725. */
  52726. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52727. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52728. };
  52729. /**
  52730. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52731. * @param scene the scene where the event occurred
  52732. * @param evt The original (browser) event
  52733. * @returns the new ActionEvent
  52734. */
  52735. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52736. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52737. };
  52738. /**
  52739. * Helper function to auto-create an ActionEvent from a primitive
  52740. * @param prim defines the target primitive
  52741. * @param pointerPos defines the pointer position
  52742. * @param evt The original (browser) event
  52743. * @param additionalData additional data for the event
  52744. * @returns the new ActionEvent
  52745. */
  52746. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52747. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52748. };
  52749. return ActionEvent;
  52750. }());
  52751. BABYLON.ActionEvent = ActionEvent;
  52752. /**
  52753. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52754. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52755. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52756. */
  52757. var ActionManager = /** @class */ (function () {
  52758. /**
  52759. * Creates a new action manager
  52760. * @param scene defines the hosting scene
  52761. */
  52762. function ActionManager(scene) {
  52763. // Members
  52764. /** Gets the list of actions */
  52765. this.actions = new Array();
  52766. /** Gets the cursor to use when hovering items */
  52767. this.hoverCursor = '';
  52768. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52769. scene.actionManagers.push(this);
  52770. }
  52771. Object.defineProperty(ActionManager, "NothingTrigger", {
  52772. /**
  52773. * Nothing
  52774. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52775. */
  52776. get: function () {
  52777. return ActionManager._NothingTrigger;
  52778. },
  52779. enumerable: true,
  52780. configurable: true
  52781. });
  52782. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52783. /**
  52784. * On pick
  52785. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52786. */
  52787. get: function () {
  52788. return ActionManager._OnPickTrigger;
  52789. },
  52790. enumerable: true,
  52791. configurable: true
  52792. });
  52793. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52794. /**
  52795. * On left pick
  52796. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52797. */
  52798. get: function () {
  52799. return ActionManager._OnLeftPickTrigger;
  52800. },
  52801. enumerable: true,
  52802. configurable: true
  52803. });
  52804. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52805. /**
  52806. * On right pick
  52807. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52808. */
  52809. get: function () {
  52810. return ActionManager._OnRightPickTrigger;
  52811. },
  52812. enumerable: true,
  52813. configurable: true
  52814. });
  52815. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52816. /**
  52817. * On center pick
  52818. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52819. */
  52820. get: function () {
  52821. return ActionManager._OnCenterPickTrigger;
  52822. },
  52823. enumerable: true,
  52824. configurable: true
  52825. });
  52826. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52827. /**
  52828. * On pick down
  52829. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52830. */
  52831. get: function () {
  52832. return ActionManager._OnPickDownTrigger;
  52833. },
  52834. enumerable: true,
  52835. configurable: true
  52836. });
  52837. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52838. /**
  52839. * On double pick
  52840. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52841. */
  52842. get: function () {
  52843. return ActionManager._OnDoublePickTrigger;
  52844. },
  52845. enumerable: true,
  52846. configurable: true
  52847. });
  52848. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52849. /**
  52850. * On pick up
  52851. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52852. */
  52853. get: function () {
  52854. return ActionManager._OnPickUpTrigger;
  52855. },
  52856. enumerable: true,
  52857. configurable: true
  52858. });
  52859. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52860. /**
  52861. * On pick out.
  52862. * This trigger will only be raised if you also declared a OnPickDown
  52863. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52864. */
  52865. get: function () {
  52866. return ActionManager._OnPickOutTrigger;
  52867. },
  52868. enumerable: true,
  52869. configurable: true
  52870. });
  52871. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52872. /**
  52873. * On long press
  52874. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52875. */
  52876. get: function () {
  52877. return ActionManager._OnLongPressTrigger;
  52878. },
  52879. enumerable: true,
  52880. configurable: true
  52881. });
  52882. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52883. /**
  52884. * On pointer over
  52885. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52886. */
  52887. get: function () {
  52888. return ActionManager._OnPointerOverTrigger;
  52889. },
  52890. enumerable: true,
  52891. configurable: true
  52892. });
  52893. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52894. /**
  52895. * On pointer out
  52896. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52897. */
  52898. get: function () {
  52899. return ActionManager._OnPointerOutTrigger;
  52900. },
  52901. enumerable: true,
  52902. configurable: true
  52903. });
  52904. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52905. /**
  52906. * On every frame
  52907. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52908. */
  52909. get: function () {
  52910. return ActionManager._OnEveryFrameTrigger;
  52911. },
  52912. enumerable: true,
  52913. configurable: true
  52914. });
  52915. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52916. /**
  52917. * On intersection enter
  52918. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52919. */
  52920. get: function () {
  52921. return ActionManager._OnIntersectionEnterTrigger;
  52922. },
  52923. enumerable: true,
  52924. configurable: true
  52925. });
  52926. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52927. /**
  52928. * On intersection exit
  52929. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52930. */
  52931. get: function () {
  52932. return ActionManager._OnIntersectionExitTrigger;
  52933. },
  52934. enumerable: true,
  52935. configurable: true
  52936. });
  52937. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52938. /**
  52939. * On key down
  52940. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52941. */
  52942. get: function () {
  52943. return ActionManager._OnKeyDownTrigger;
  52944. },
  52945. enumerable: true,
  52946. configurable: true
  52947. });
  52948. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52949. /**
  52950. * On key up
  52951. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52952. */
  52953. get: function () {
  52954. return ActionManager._OnKeyUpTrigger;
  52955. },
  52956. enumerable: true,
  52957. configurable: true
  52958. });
  52959. // Methods
  52960. /**
  52961. * Releases all associated resources
  52962. */
  52963. ActionManager.prototype.dispose = function () {
  52964. var index = this._scene.actionManagers.indexOf(this);
  52965. for (var i = 0; i < this.actions.length; i++) {
  52966. var action = this.actions[i];
  52967. ActionManager.Triggers[action.trigger]--;
  52968. if (ActionManager.Triggers[action.trigger] === 0) {
  52969. delete ActionManager.Triggers[action.trigger];
  52970. }
  52971. }
  52972. if (index > -1) {
  52973. this._scene.actionManagers.splice(index, 1);
  52974. }
  52975. };
  52976. /**
  52977. * Gets hosting scene
  52978. * @returns the hosting scene
  52979. */
  52980. ActionManager.prototype.getScene = function () {
  52981. return this._scene;
  52982. };
  52983. /**
  52984. * Does this action manager handles actions of any of the given triggers
  52985. * @param triggers defines the triggers to be tested
  52986. * @return a boolean indicating whether one (or more) of the triggers is handled
  52987. */
  52988. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52989. for (var index = 0; index < this.actions.length; index++) {
  52990. var action = this.actions[index];
  52991. if (triggers.indexOf(action.trigger) > -1) {
  52992. return true;
  52993. }
  52994. }
  52995. return false;
  52996. };
  52997. /**
  52998. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  52999. * speed.
  53000. * @param triggerA defines the trigger to be tested
  53001. * @param triggerB defines the trigger to be tested
  53002. * @return a boolean indicating whether one (or more) of the triggers is handled
  53003. */
  53004. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  53005. for (var index = 0; index < this.actions.length; index++) {
  53006. var action = this.actions[index];
  53007. if (triggerA == action.trigger || triggerB == action.trigger) {
  53008. return true;
  53009. }
  53010. }
  53011. return false;
  53012. };
  53013. /**
  53014. * Does this action manager handles actions of a given trigger
  53015. * @param trigger defines the trigger to be tested
  53016. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53017. * @return whether the trigger is handled
  53018. */
  53019. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53020. for (var index = 0; index < this.actions.length; index++) {
  53021. var action = this.actions[index];
  53022. if (action.trigger === trigger) {
  53023. if (parameterPredicate) {
  53024. if (parameterPredicate(action.getTriggerParameter())) {
  53025. return true;
  53026. }
  53027. }
  53028. else {
  53029. return true;
  53030. }
  53031. }
  53032. }
  53033. return false;
  53034. };
  53035. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53036. /**
  53037. * Does this action manager has pointer triggers
  53038. */
  53039. get: function () {
  53040. for (var index = 0; index < this.actions.length; index++) {
  53041. var action = this.actions[index];
  53042. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53043. return true;
  53044. }
  53045. }
  53046. return false;
  53047. },
  53048. enumerable: true,
  53049. configurable: true
  53050. });
  53051. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53052. /**
  53053. * Does this action manager has pick triggers
  53054. */
  53055. get: function () {
  53056. for (var index = 0; index < this.actions.length; index++) {
  53057. var action = this.actions[index];
  53058. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53059. return true;
  53060. }
  53061. }
  53062. return false;
  53063. },
  53064. enumerable: true,
  53065. configurable: true
  53066. });
  53067. Object.defineProperty(ActionManager, "HasTriggers", {
  53068. /**
  53069. * Does exist one action manager with at least one trigger
  53070. **/
  53071. get: function () {
  53072. for (var t in ActionManager.Triggers) {
  53073. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53074. return true;
  53075. }
  53076. }
  53077. return false;
  53078. },
  53079. enumerable: true,
  53080. configurable: true
  53081. });
  53082. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53083. /**
  53084. * Does exist one action manager with at least one pick trigger
  53085. **/
  53086. get: function () {
  53087. for (var t in ActionManager.Triggers) {
  53088. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53089. var t_int = parseInt(t);
  53090. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53091. return true;
  53092. }
  53093. }
  53094. }
  53095. return false;
  53096. },
  53097. enumerable: true,
  53098. configurable: true
  53099. });
  53100. /**
  53101. * Does exist one action manager that handles actions of a given trigger
  53102. * @param trigger defines the trigger to be tested
  53103. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53104. **/
  53105. ActionManager.HasSpecificTrigger = function (trigger) {
  53106. for (var t in ActionManager.Triggers) {
  53107. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53108. var t_int = parseInt(t);
  53109. if (t_int === trigger) {
  53110. return true;
  53111. }
  53112. }
  53113. }
  53114. return false;
  53115. };
  53116. /**
  53117. * Registers an action to this action manager
  53118. * @param action defines the action to be registered
  53119. * @return the action amended (prepared) after registration
  53120. */
  53121. ActionManager.prototype.registerAction = function (action) {
  53122. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53123. if (this.getScene().actionManager !== this) {
  53124. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53125. return null;
  53126. }
  53127. }
  53128. this.actions.push(action);
  53129. if (ActionManager.Triggers[action.trigger]) {
  53130. ActionManager.Triggers[action.trigger]++;
  53131. }
  53132. else {
  53133. ActionManager.Triggers[action.trigger] = 1;
  53134. }
  53135. action._actionManager = this;
  53136. action._prepare();
  53137. return action;
  53138. };
  53139. /**
  53140. * Unregisters an action to this action manager
  53141. * @param action defines the action to be unregistered
  53142. * @return a boolean indicating whether the action has been unregistered
  53143. */
  53144. ActionManager.prototype.unregisterAction = function (action) {
  53145. var index = this.actions.indexOf(action);
  53146. if (index !== -1) {
  53147. this.actions.splice(index, 1);
  53148. ActionManager.Triggers[action.trigger] -= 1;
  53149. if (ActionManager.Triggers[action.trigger] === 0) {
  53150. delete ActionManager.Triggers[action.trigger];
  53151. }
  53152. delete action._actionManager;
  53153. return true;
  53154. }
  53155. return false;
  53156. };
  53157. /**
  53158. * Process a specific trigger
  53159. * @param trigger defines the trigger to process
  53160. * @param evt defines the event details to be processed
  53161. */
  53162. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53163. for (var index = 0; index < this.actions.length; index++) {
  53164. var action = this.actions[index];
  53165. if (action.trigger === trigger) {
  53166. if (evt) {
  53167. if (trigger === ActionManager.OnKeyUpTrigger
  53168. || trigger === ActionManager.OnKeyDownTrigger) {
  53169. var parameter = action.getTriggerParameter();
  53170. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53171. if (!parameter.toLowerCase) {
  53172. continue;
  53173. }
  53174. var lowerCase = parameter.toLowerCase();
  53175. if (lowerCase !== evt.sourceEvent.key) {
  53176. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53177. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53178. if (actualkey !== lowerCase) {
  53179. continue;
  53180. }
  53181. }
  53182. }
  53183. }
  53184. }
  53185. action._executeCurrent(evt);
  53186. }
  53187. }
  53188. };
  53189. /** @hidden */
  53190. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53191. var properties = propertyPath.split(".");
  53192. for (var index = 0; index < properties.length - 1; index++) {
  53193. target = target[properties[index]];
  53194. }
  53195. return target;
  53196. };
  53197. /** @hidden */
  53198. ActionManager.prototype._getProperty = function (propertyPath) {
  53199. var properties = propertyPath.split(".");
  53200. return properties[properties.length - 1];
  53201. };
  53202. /**
  53203. * Serialize this manager to a JSON object
  53204. * @param name defines the property name to store this manager
  53205. * @returns a JSON representation of this manager
  53206. */
  53207. ActionManager.prototype.serialize = function (name) {
  53208. var root = {
  53209. children: new Array(),
  53210. name: name,
  53211. type: 3,
  53212. properties: new Array() // Empty for root but required
  53213. };
  53214. for (var i = 0; i < this.actions.length; i++) {
  53215. var triggerObject = {
  53216. type: 0,
  53217. children: new Array(),
  53218. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53219. properties: new Array()
  53220. };
  53221. var triggerOptions = this.actions[i].triggerOptions;
  53222. if (triggerOptions && typeof triggerOptions !== "number") {
  53223. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53224. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53225. }
  53226. else {
  53227. var parameter = {};
  53228. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53229. if (triggerOptions.parameter.mesh) {
  53230. parameter._meshId = triggerOptions.parameter.mesh.id;
  53231. }
  53232. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53233. }
  53234. }
  53235. // Serialize child action, recursively
  53236. this.actions[i].serialize(triggerObject);
  53237. // Add serialized trigger
  53238. root.children.push(triggerObject);
  53239. }
  53240. return root;
  53241. };
  53242. /**
  53243. * Creates a new ActionManager from a JSON data
  53244. * @param parsedActions defines the JSON data to read from
  53245. * @param object defines the hosting mesh
  53246. * @param scene defines the hosting scene
  53247. */
  53248. ActionManager.Parse = function (parsedActions, object, scene) {
  53249. var actionManager = new ActionManager(scene);
  53250. if (object === null)
  53251. scene.actionManager = actionManager;
  53252. else
  53253. object.actionManager = actionManager;
  53254. // instanciate a new object
  53255. var instanciate = function (name, params) {
  53256. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53257. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53258. newInstance.constructor.apply(newInstance, params);
  53259. return newInstance;
  53260. };
  53261. var parseParameter = function (name, value, target, propertyPath) {
  53262. if (propertyPath === null) {
  53263. // String, boolean or float
  53264. var floatValue = parseFloat(value);
  53265. if (value === "true" || value === "false")
  53266. return value === "true";
  53267. else
  53268. return isNaN(floatValue) ? value : floatValue;
  53269. }
  53270. var effectiveTarget = propertyPath.split(".");
  53271. var values = value.split(",");
  53272. // Get effective Target
  53273. for (var i = 0; i < effectiveTarget.length; i++) {
  53274. target = target[effectiveTarget[i]];
  53275. }
  53276. // Return appropriate value with its type
  53277. if (typeof (target) === "boolean")
  53278. return values[0] === "true";
  53279. if (typeof (target) === "string")
  53280. return values[0];
  53281. // Parameters with multiple values such as Vector3 etc.
  53282. var split = new Array();
  53283. for (var i = 0; i < values.length; i++)
  53284. split.push(parseFloat(values[i]));
  53285. if (target instanceof BABYLON.Vector3)
  53286. return BABYLON.Vector3.FromArray(split);
  53287. if (target instanceof BABYLON.Vector4)
  53288. return BABYLON.Vector4.FromArray(split);
  53289. if (target instanceof BABYLON.Color3)
  53290. return BABYLON.Color3.FromArray(split);
  53291. if (target instanceof BABYLON.Color4)
  53292. return BABYLON.Color4.FromArray(split);
  53293. return parseFloat(values[0]);
  53294. };
  53295. // traverse graph per trigger
  53296. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53297. if (combineArray === void 0) { combineArray = null; }
  53298. if (parsedAction.detached)
  53299. return;
  53300. var parameters = new Array();
  53301. var target = null;
  53302. var propertyPath = null;
  53303. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53304. // Parameters
  53305. if (parsedAction.type === 2)
  53306. parameters.push(actionManager);
  53307. else
  53308. parameters.push(trigger);
  53309. if (combine) {
  53310. var actions = new Array();
  53311. for (var j = 0; j < parsedAction.combine.length; j++) {
  53312. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53313. }
  53314. parameters.push(actions);
  53315. }
  53316. else {
  53317. for (var i = 0; i < parsedAction.properties.length; i++) {
  53318. var value = parsedAction.properties[i].value;
  53319. var name = parsedAction.properties[i].name;
  53320. var targetType = parsedAction.properties[i].targetType;
  53321. if (name === "target")
  53322. if (targetType !== null && targetType === "SceneProperties")
  53323. value = target = scene;
  53324. else
  53325. value = target = scene.getNodeByName(value);
  53326. else if (name === "parent")
  53327. value = scene.getNodeByName(value);
  53328. else if (name === "sound")
  53329. value = scene.getSoundByName(value);
  53330. else if (name !== "propertyPath") {
  53331. if (parsedAction.type === 2 && name === "operator")
  53332. value = BABYLON.ValueCondition[value];
  53333. else
  53334. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53335. }
  53336. else {
  53337. propertyPath = value;
  53338. }
  53339. parameters.push(value);
  53340. }
  53341. }
  53342. if (combineArray === null) {
  53343. parameters.push(condition);
  53344. }
  53345. else {
  53346. parameters.push(null);
  53347. }
  53348. // If interpolate value action
  53349. if (parsedAction.name === "InterpolateValueAction") {
  53350. var param = parameters[parameters.length - 2];
  53351. parameters[parameters.length - 1] = param;
  53352. parameters[parameters.length - 2] = condition;
  53353. }
  53354. // Action or condition(s) and not CombineAction
  53355. var newAction = instanciate(parsedAction.name, parameters);
  53356. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53357. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53358. if (action)
  53359. action.then(nothing);
  53360. else
  53361. actionManager.registerAction(nothing);
  53362. action = nothing;
  53363. }
  53364. if (combineArray === null) {
  53365. if (newAction instanceof BABYLON.Condition) {
  53366. condition = newAction;
  53367. newAction = action;
  53368. }
  53369. else {
  53370. condition = null;
  53371. if (action)
  53372. action.then(newAction);
  53373. else
  53374. actionManager.registerAction(newAction);
  53375. }
  53376. }
  53377. else {
  53378. combineArray.push(newAction);
  53379. }
  53380. for (var i = 0; i < parsedAction.children.length; i++)
  53381. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53382. };
  53383. // triggers
  53384. for (var i = 0; i < parsedActions.children.length; i++) {
  53385. var triggerParams;
  53386. var trigger = parsedActions.children[i];
  53387. if (trigger.properties.length > 0) {
  53388. var param = trigger.properties[0].value;
  53389. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53390. if (value._meshId) {
  53391. value.mesh = scene.getMeshByID(value._meshId);
  53392. }
  53393. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53394. }
  53395. else
  53396. triggerParams = ActionManager[trigger.name];
  53397. for (var j = 0; j < trigger.children.length; j++) {
  53398. if (!trigger.detached)
  53399. traverse(trigger.children[j], triggerParams, null, null);
  53400. }
  53401. }
  53402. };
  53403. /**
  53404. * Get a trigger name by index
  53405. * @param trigger defines the trigger index
  53406. * @returns a trigger name
  53407. */
  53408. ActionManager.GetTriggerName = function (trigger) {
  53409. switch (trigger) {
  53410. case 0: return "NothingTrigger";
  53411. case 1: return "OnPickTrigger";
  53412. case 2: return "OnLeftPickTrigger";
  53413. case 3: return "OnRightPickTrigger";
  53414. case 4: return "OnCenterPickTrigger";
  53415. case 5: return "OnPickDownTrigger";
  53416. case 6: return "OnPickUpTrigger";
  53417. case 7: return "OnLongPressTrigger";
  53418. case 8: return "OnPointerOverTrigger";
  53419. case 9: return "OnPointerOutTrigger";
  53420. case 10: return "OnEveryFrameTrigger";
  53421. case 11: return "OnIntersectionEnterTrigger";
  53422. case 12: return "OnIntersectionExitTrigger";
  53423. case 13: return "OnKeyDownTrigger";
  53424. case 14: return "OnKeyUpTrigger";
  53425. case 15: return "OnPickOutTrigger";
  53426. default: return "";
  53427. }
  53428. };
  53429. // Statics
  53430. ActionManager._NothingTrigger = 0;
  53431. ActionManager._OnPickTrigger = 1;
  53432. ActionManager._OnLeftPickTrigger = 2;
  53433. ActionManager._OnRightPickTrigger = 3;
  53434. ActionManager._OnCenterPickTrigger = 4;
  53435. ActionManager._OnPickDownTrigger = 5;
  53436. ActionManager._OnDoublePickTrigger = 6;
  53437. ActionManager._OnPickUpTrigger = 7;
  53438. ActionManager._OnLongPressTrigger = 8;
  53439. ActionManager._OnPointerOverTrigger = 9;
  53440. ActionManager._OnPointerOutTrigger = 10;
  53441. ActionManager._OnEveryFrameTrigger = 11;
  53442. ActionManager._OnIntersectionEnterTrigger = 12;
  53443. ActionManager._OnIntersectionExitTrigger = 13;
  53444. ActionManager._OnKeyDownTrigger = 14;
  53445. ActionManager._OnKeyUpTrigger = 15;
  53446. ActionManager._OnPickOutTrigger = 16;
  53447. /** Gets the list of active triggers */
  53448. ActionManager.Triggers = {};
  53449. return ActionManager;
  53450. }());
  53451. BABYLON.ActionManager = ActionManager;
  53452. })(BABYLON || (BABYLON = {}));
  53453. //# sourceMappingURL=babylon.actionManager.js.map
  53454. var BABYLON;
  53455. (function (BABYLON) {
  53456. var InterpolateValueAction = /** @class */ (function (_super) {
  53457. __extends(InterpolateValueAction, _super);
  53458. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53459. if (duration === void 0) { duration = 1000; }
  53460. var _this = _super.call(this, triggerOptions, condition) || this;
  53461. _this.propertyPath = propertyPath;
  53462. _this.value = value;
  53463. _this.duration = duration;
  53464. _this.stopOtherAnimations = stopOtherAnimations;
  53465. _this.onInterpolationDone = onInterpolationDone;
  53466. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53467. _this._target = _this._effectiveTarget = target;
  53468. return _this;
  53469. }
  53470. /** @hidden */
  53471. InterpolateValueAction.prototype._prepare = function () {
  53472. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53473. this._property = this._getProperty(this.propertyPath);
  53474. };
  53475. InterpolateValueAction.prototype.execute = function () {
  53476. var _this = this;
  53477. var scene = this._actionManager.getScene();
  53478. var keys = [
  53479. {
  53480. frame: 0,
  53481. value: this._effectiveTarget[this._property]
  53482. }, {
  53483. frame: 100,
  53484. value: this.value
  53485. }
  53486. ];
  53487. var dataType;
  53488. if (typeof this.value === "number") {
  53489. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53490. }
  53491. else if (this.value instanceof BABYLON.Color3) {
  53492. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53493. }
  53494. else if (this.value instanceof BABYLON.Vector3) {
  53495. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53496. }
  53497. else if (this.value instanceof BABYLON.Matrix) {
  53498. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53499. }
  53500. else if (this.value instanceof BABYLON.Quaternion) {
  53501. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53502. }
  53503. else {
  53504. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53505. return;
  53506. }
  53507. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53508. animation.setKeys(keys);
  53509. if (this.stopOtherAnimations) {
  53510. scene.stopAnimation(this._effectiveTarget);
  53511. }
  53512. var wrapper = function () {
  53513. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53514. if (_this.onInterpolationDone) {
  53515. _this.onInterpolationDone();
  53516. }
  53517. };
  53518. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53519. };
  53520. InterpolateValueAction.prototype.serialize = function (parent) {
  53521. return _super.prototype._serialize.call(this, {
  53522. name: "InterpolateValueAction",
  53523. properties: [
  53524. BABYLON.Action._GetTargetProperty(this._target),
  53525. { name: "propertyPath", value: this.propertyPath },
  53526. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53527. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53528. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53529. ]
  53530. }, parent);
  53531. };
  53532. return InterpolateValueAction;
  53533. }(BABYLON.Action));
  53534. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53535. })(BABYLON || (BABYLON = {}));
  53536. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53537. var BABYLON;
  53538. (function (BABYLON) {
  53539. var SwitchBooleanAction = /** @class */ (function (_super) {
  53540. __extends(SwitchBooleanAction, _super);
  53541. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53542. var _this = _super.call(this, triggerOptions, condition) || this;
  53543. _this.propertyPath = propertyPath;
  53544. _this._target = _this._effectiveTarget = target;
  53545. return _this;
  53546. }
  53547. /** @hidden */
  53548. SwitchBooleanAction.prototype._prepare = function () {
  53549. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53550. this._property = this._getProperty(this.propertyPath);
  53551. };
  53552. SwitchBooleanAction.prototype.execute = function () {
  53553. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53554. };
  53555. SwitchBooleanAction.prototype.serialize = function (parent) {
  53556. return _super.prototype._serialize.call(this, {
  53557. name: "SwitchBooleanAction",
  53558. properties: [
  53559. BABYLON.Action._GetTargetProperty(this._target),
  53560. { name: "propertyPath", value: this.propertyPath }
  53561. ]
  53562. }, parent);
  53563. };
  53564. return SwitchBooleanAction;
  53565. }(BABYLON.Action));
  53566. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53567. var SetStateAction = /** @class */ (function (_super) {
  53568. __extends(SetStateAction, _super);
  53569. function SetStateAction(triggerOptions, target, value, condition) {
  53570. var _this = _super.call(this, triggerOptions, condition) || this;
  53571. _this.value = value;
  53572. _this._target = target;
  53573. return _this;
  53574. }
  53575. SetStateAction.prototype.execute = function () {
  53576. this._target.state = this.value;
  53577. };
  53578. SetStateAction.prototype.serialize = function (parent) {
  53579. return _super.prototype._serialize.call(this, {
  53580. name: "SetStateAction",
  53581. properties: [
  53582. BABYLON.Action._GetTargetProperty(this._target),
  53583. { name: "value", value: this.value }
  53584. ]
  53585. }, parent);
  53586. };
  53587. return SetStateAction;
  53588. }(BABYLON.Action));
  53589. BABYLON.SetStateAction = SetStateAction;
  53590. var SetValueAction = /** @class */ (function (_super) {
  53591. __extends(SetValueAction, _super);
  53592. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53593. var _this = _super.call(this, triggerOptions, condition) || this;
  53594. _this.propertyPath = propertyPath;
  53595. _this.value = value;
  53596. _this._target = _this._effectiveTarget = target;
  53597. return _this;
  53598. }
  53599. /** @hidden */
  53600. SetValueAction.prototype._prepare = function () {
  53601. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53602. this._property = this._getProperty(this.propertyPath);
  53603. };
  53604. SetValueAction.prototype.execute = function () {
  53605. this._effectiveTarget[this._property] = this.value;
  53606. if (this._target.markAsDirty) {
  53607. this._target.markAsDirty(this._property);
  53608. }
  53609. };
  53610. SetValueAction.prototype.serialize = function (parent) {
  53611. return _super.prototype._serialize.call(this, {
  53612. name: "SetValueAction",
  53613. properties: [
  53614. BABYLON.Action._GetTargetProperty(this._target),
  53615. { name: "propertyPath", value: this.propertyPath },
  53616. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53617. ]
  53618. }, parent);
  53619. };
  53620. return SetValueAction;
  53621. }(BABYLON.Action));
  53622. BABYLON.SetValueAction = SetValueAction;
  53623. var IncrementValueAction = /** @class */ (function (_super) {
  53624. __extends(IncrementValueAction, _super);
  53625. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53626. var _this = _super.call(this, triggerOptions, condition) || this;
  53627. _this.propertyPath = propertyPath;
  53628. _this.value = value;
  53629. _this._target = _this._effectiveTarget = target;
  53630. return _this;
  53631. }
  53632. /** @hidden */
  53633. IncrementValueAction.prototype._prepare = function () {
  53634. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53635. this._property = this._getProperty(this.propertyPath);
  53636. if (typeof this._effectiveTarget[this._property] !== "number") {
  53637. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53638. }
  53639. };
  53640. IncrementValueAction.prototype.execute = function () {
  53641. this._effectiveTarget[this._property] += this.value;
  53642. if (this._target.markAsDirty) {
  53643. this._target.markAsDirty(this._property);
  53644. }
  53645. };
  53646. IncrementValueAction.prototype.serialize = function (parent) {
  53647. return _super.prototype._serialize.call(this, {
  53648. name: "IncrementValueAction",
  53649. properties: [
  53650. BABYLON.Action._GetTargetProperty(this._target),
  53651. { name: "propertyPath", value: this.propertyPath },
  53652. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53653. ]
  53654. }, parent);
  53655. };
  53656. return IncrementValueAction;
  53657. }(BABYLON.Action));
  53658. BABYLON.IncrementValueAction = IncrementValueAction;
  53659. var PlayAnimationAction = /** @class */ (function (_super) {
  53660. __extends(PlayAnimationAction, _super);
  53661. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53662. var _this = _super.call(this, triggerOptions, condition) || this;
  53663. _this.from = from;
  53664. _this.to = to;
  53665. _this.loop = loop;
  53666. _this._target = target;
  53667. return _this;
  53668. }
  53669. /** @hidden */
  53670. PlayAnimationAction.prototype._prepare = function () {
  53671. };
  53672. PlayAnimationAction.prototype.execute = function () {
  53673. var scene = this._actionManager.getScene();
  53674. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53675. };
  53676. PlayAnimationAction.prototype.serialize = function (parent) {
  53677. return _super.prototype._serialize.call(this, {
  53678. name: "PlayAnimationAction",
  53679. properties: [
  53680. BABYLON.Action._GetTargetProperty(this._target),
  53681. { name: "from", value: String(this.from) },
  53682. { name: "to", value: String(this.to) },
  53683. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53684. ]
  53685. }, parent);
  53686. };
  53687. return PlayAnimationAction;
  53688. }(BABYLON.Action));
  53689. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53690. var StopAnimationAction = /** @class */ (function (_super) {
  53691. __extends(StopAnimationAction, _super);
  53692. function StopAnimationAction(triggerOptions, target, condition) {
  53693. var _this = _super.call(this, triggerOptions, condition) || this;
  53694. _this._target = target;
  53695. return _this;
  53696. }
  53697. /** @hidden */
  53698. StopAnimationAction.prototype._prepare = function () {
  53699. };
  53700. StopAnimationAction.prototype.execute = function () {
  53701. var scene = this._actionManager.getScene();
  53702. scene.stopAnimation(this._target);
  53703. };
  53704. StopAnimationAction.prototype.serialize = function (parent) {
  53705. return _super.prototype._serialize.call(this, {
  53706. name: "StopAnimationAction",
  53707. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53708. }, parent);
  53709. };
  53710. return StopAnimationAction;
  53711. }(BABYLON.Action));
  53712. BABYLON.StopAnimationAction = StopAnimationAction;
  53713. var DoNothingAction = /** @class */ (function (_super) {
  53714. __extends(DoNothingAction, _super);
  53715. function DoNothingAction(triggerOptions, condition) {
  53716. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53717. return _super.call(this, triggerOptions, condition) || this;
  53718. }
  53719. DoNothingAction.prototype.execute = function () {
  53720. };
  53721. DoNothingAction.prototype.serialize = function (parent) {
  53722. return _super.prototype._serialize.call(this, {
  53723. name: "DoNothingAction",
  53724. properties: []
  53725. }, parent);
  53726. };
  53727. return DoNothingAction;
  53728. }(BABYLON.Action));
  53729. BABYLON.DoNothingAction = DoNothingAction;
  53730. var CombineAction = /** @class */ (function (_super) {
  53731. __extends(CombineAction, _super);
  53732. function CombineAction(triggerOptions, children, condition) {
  53733. var _this = _super.call(this, triggerOptions, condition) || this;
  53734. _this.children = children;
  53735. return _this;
  53736. }
  53737. /** @hidden */
  53738. CombineAction.prototype._prepare = function () {
  53739. for (var index = 0; index < this.children.length; index++) {
  53740. this.children[index]._actionManager = this._actionManager;
  53741. this.children[index]._prepare();
  53742. }
  53743. };
  53744. CombineAction.prototype.execute = function (evt) {
  53745. for (var index = 0; index < this.children.length; index++) {
  53746. this.children[index].execute(evt);
  53747. }
  53748. };
  53749. CombineAction.prototype.serialize = function (parent) {
  53750. var serializationObject = _super.prototype._serialize.call(this, {
  53751. name: "CombineAction",
  53752. properties: [],
  53753. combine: []
  53754. }, parent);
  53755. for (var i = 0; i < this.children.length; i++) {
  53756. serializationObject.combine.push(this.children[i].serialize(null));
  53757. }
  53758. return serializationObject;
  53759. };
  53760. return CombineAction;
  53761. }(BABYLON.Action));
  53762. BABYLON.CombineAction = CombineAction;
  53763. var ExecuteCodeAction = /** @class */ (function (_super) {
  53764. __extends(ExecuteCodeAction, _super);
  53765. function ExecuteCodeAction(triggerOptions, func, condition) {
  53766. var _this = _super.call(this, triggerOptions, condition) || this;
  53767. _this.func = func;
  53768. return _this;
  53769. }
  53770. ExecuteCodeAction.prototype.execute = function (evt) {
  53771. this.func(evt);
  53772. };
  53773. return ExecuteCodeAction;
  53774. }(BABYLON.Action));
  53775. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53776. var SetParentAction = /** @class */ (function (_super) {
  53777. __extends(SetParentAction, _super);
  53778. function SetParentAction(triggerOptions, target, parent, condition) {
  53779. var _this = _super.call(this, triggerOptions, condition) || this;
  53780. _this._target = target;
  53781. _this._parent = parent;
  53782. return _this;
  53783. }
  53784. /** @hidden */
  53785. SetParentAction.prototype._prepare = function () {
  53786. };
  53787. SetParentAction.prototype.execute = function () {
  53788. if (this._target.parent === this._parent) {
  53789. return;
  53790. }
  53791. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53792. invertParentWorldMatrix.invert();
  53793. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53794. this._target.parent = this._parent;
  53795. };
  53796. SetParentAction.prototype.serialize = function (parent) {
  53797. return _super.prototype._serialize.call(this, {
  53798. name: "SetParentAction",
  53799. properties: [
  53800. BABYLON.Action._GetTargetProperty(this._target),
  53801. BABYLON.Action._GetTargetProperty(this._parent),
  53802. ]
  53803. }, parent);
  53804. };
  53805. return SetParentAction;
  53806. }(BABYLON.Action));
  53807. BABYLON.SetParentAction = SetParentAction;
  53808. var PlaySoundAction = /** @class */ (function (_super) {
  53809. __extends(PlaySoundAction, _super);
  53810. function PlaySoundAction(triggerOptions, sound, condition) {
  53811. var _this = _super.call(this, triggerOptions, condition) || this;
  53812. _this._sound = sound;
  53813. return _this;
  53814. }
  53815. /** @hidden */
  53816. PlaySoundAction.prototype._prepare = function () {
  53817. };
  53818. PlaySoundAction.prototype.execute = function () {
  53819. if (this._sound !== undefined)
  53820. this._sound.play();
  53821. };
  53822. PlaySoundAction.prototype.serialize = function (parent) {
  53823. return _super.prototype._serialize.call(this, {
  53824. name: "PlaySoundAction",
  53825. properties: [{ name: "sound", value: this._sound.name }]
  53826. }, parent);
  53827. };
  53828. return PlaySoundAction;
  53829. }(BABYLON.Action));
  53830. BABYLON.PlaySoundAction = PlaySoundAction;
  53831. var StopSoundAction = /** @class */ (function (_super) {
  53832. __extends(StopSoundAction, _super);
  53833. function StopSoundAction(triggerOptions, sound, condition) {
  53834. var _this = _super.call(this, triggerOptions, condition) || this;
  53835. _this._sound = sound;
  53836. return _this;
  53837. }
  53838. /** @hidden */
  53839. StopSoundAction.prototype._prepare = function () {
  53840. };
  53841. StopSoundAction.prototype.execute = function () {
  53842. if (this._sound !== undefined)
  53843. this._sound.stop();
  53844. };
  53845. StopSoundAction.prototype.serialize = function (parent) {
  53846. return _super.prototype._serialize.call(this, {
  53847. name: "StopSoundAction",
  53848. properties: [{ name: "sound", value: this._sound.name }]
  53849. }, parent);
  53850. };
  53851. return StopSoundAction;
  53852. }(BABYLON.Action));
  53853. BABYLON.StopSoundAction = StopSoundAction;
  53854. })(BABYLON || (BABYLON = {}));
  53855. //# sourceMappingURL=babylon.directActions.js.map
  53856. var BABYLON;
  53857. (function (BABYLON) {
  53858. var SpriteManager = /** @class */ (function () {
  53859. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53860. if (epsilon === void 0) { epsilon = 0.01; }
  53861. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53862. this.name = name;
  53863. this.sprites = new Array();
  53864. this.renderingGroupId = 0;
  53865. this.layerMask = 0x0FFFFFFF;
  53866. this.fogEnabled = true;
  53867. this.isPickable = false;
  53868. /**
  53869. * An event triggered when the manager is disposed.
  53870. */
  53871. this.onDisposeObservable = new BABYLON.Observable();
  53872. this._vertexBuffers = {};
  53873. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  53874. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  53875. }
  53876. this._capacity = capacity;
  53877. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53878. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53879. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53880. if (cellSize.width && cellSize.height) {
  53881. this.cellWidth = cellSize.width;
  53882. this.cellHeight = cellSize.height;
  53883. }
  53884. else if (cellSize !== undefined) {
  53885. this.cellWidth = cellSize;
  53886. this.cellHeight = cellSize;
  53887. }
  53888. else {
  53889. return;
  53890. }
  53891. this._epsilon = epsilon;
  53892. this._scene = scene;
  53893. this._scene.spriteManagers.push(this);
  53894. var indices = [];
  53895. var index = 0;
  53896. for (var count = 0; count < capacity; count++) {
  53897. indices.push(index);
  53898. indices.push(index + 1);
  53899. indices.push(index + 2);
  53900. indices.push(index);
  53901. indices.push(index + 2);
  53902. indices.push(index + 3);
  53903. index += 4;
  53904. }
  53905. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53906. // VBO
  53907. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53908. this._vertexData = new Float32Array(capacity * 16 * 4);
  53909. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53910. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53911. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53912. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53913. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53914. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53915. this._vertexBuffers["options"] = options;
  53916. this._vertexBuffers["cellInfo"] = cellInfo;
  53917. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53918. // Effects
  53919. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53920. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53921. }
  53922. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53923. set: function (callback) {
  53924. if (this._onDisposeObserver) {
  53925. this.onDisposeObservable.remove(this._onDisposeObserver);
  53926. }
  53927. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53928. },
  53929. enumerable: true,
  53930. configurable: true
  53931. });
  53932. Object.defineProperty(SpriteManager.prototype, "texture", {
  53933. get: function () {
  53934. return this._spriteTexture;
  53935. },
  53936. set: function (value) {
  53937. this._spriteTexture = value;
  53938. },
  53939. enumerable: true,
  53940. configurable: true
  53941. });
  53942. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53943. var arrayOffset = index * 16;
  53944. if (offsetX === 0)
  53945. offsetX = this._epsilon;
  53946. else if (offsetX === 1)
  53947. offsetX = 1 - this._epsilon;
  53948. if (offsetY === 0)
  53949. offsetY = this._epsilon;
  53950. else if (offsetY === 1)
  53951. offsetY = 1 - this._epsilon;
  53952. this._vertexData[arrayOffset] = sprite.position.x;
  53953. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53954. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53955. this._vertexData[arrayOffset + 3] = sprite.angle;
  53956. this._vertexData[arrayOffset + 4] = sprite.width;
  53957. this._vertexData[arrayOffset + 5] = sprite.height;
  53958. this._vertexData[arrayOffset + 6] = offsetX;
  53959. this._vertexData[arrayOffset + 7] = offsetY;
  53960. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53961. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53962. var offset = (sprite.cellIndex / rowSize) >> 0;
  53963. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53964. this._vertexData[arrayOffset + 11] = offset;
  53965. // Color
  53966. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53967. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53968. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53969. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53970. };
  53971. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53972. var count = Math.min(this._capacity, this.sprites.length);
  53973. var min = BABYLON.Vector3.Zero();
  53974. var max = BABYLON.Vector3.Zero();
  53975. var distance = Number.MAX_VALUE;
  53976. var currentSprite = null;
  53977. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53978. var cameraView = camera.getViewMatrix();
  53979. for (var index = 0; index < count; index++) {
  53980. var sprite = this.sprites[index];
  53981. if (!sprite) {
  53982. continue;
  53983. }
  53984. if (predicate) {
  53985. if (!predicate(sprite)) {
  53986. continue;
  53987. }
  53988. }
  53989. else if (!sprite.isPickable) {
  53990. continue;
  53991. }
  53992. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53993. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53994. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53995. if (ray.intersectsBoxMinMax(min, max)) {
  53996. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53997. if (distance > currentDistance) {
  53998. distance = currentDistance;
  53999. currentSprite = sprite;
  54000. if (fastCheck) {
  54001. break;
  54002. }
  54003. }
  54004. }
  54005. }
  54006. if (currentSprite) {
  54007. var result = new BABYLON.PickingInfo();
  54008. result.hit = true;
  54009. result.pickedSprite = currentSprite;
  54010. result.distance = distance;
  54011. return result;
  54012. }
  54013. return null;
  54014. };
  54015. SpriteManager.prototype.render = function () {
  54016. // Check
  54017. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54018. return;
  54019. var engine = this._scene.getEngine();
  54020. var baseSize = this._spriteTexture.getBaseSize();
  54021. // Sprites
  54022. var deltaTime = engine.getDeltaTime();
  54023. var max = Math.min(this._capacity, this.sprites.length);
  54024. var rowSize = baseSize.width / this.cellWidth;
  54025. var offset = 0;
  54026. for (var index = 0; index < max; index++) {
  54027. var sprite = this.sprites[index];
  54028. if (!sprite || !sprite.isVisible) {
  54029. continue;
  54030. }
  54031. sprite._animate(deltaTime);
  54032. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54033. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54034. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54035. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54036. }
  54037. this._buffer.update(this._vertexData);
  54038. // Render
  54039. var effect = this._effectBase;
  54040. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54041. effect = this._effectFog;
  54042. }
  54043. engine.enableEffect(effect);
  54044. var viewMatrix = this._scene.getViewMatrix();
  54045. effect.setTexture("diffuseSampler", this._spriteTexture);
  54046. effect.setMatrix("view", viewMatrix);
  54047. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54048. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54049. // Fog
  54050. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54051. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54052. effect.setColor3("vFogColor", this._scene.fogColor);
  54053. }
  54054. // VBOs
  54055. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54056. // Draw order
  54057. engine.setDepthFunctionToLessOrEqual();
  54058. effect.setBool("alphaTest", true);
  54059. engine.setColorWrite(false);
  54060. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54061. engine.setColorWrite(true);
  54062. effect.setBool("alphaTest", false);
  54063. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54064. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54065. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54066. };
  54067. SpriteManager.prototype.dispose = function () {
  54068. if (this._buffer) {
  54069. this._buffer.dispose();
  54070. this._buffer = null;
  54071. }
  54072. if (this._indexBuffer) {
  54073. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54074. this._indexBuffer = null;
  54075. }
  54076. if (this._spriteTexture) {
  54077. this._spriteTexture.dispose();
  54078. this._spriteTexture = null;
  54079. }
  54080. // Remove from scene
  54081. var index = this._scene.spriteManagers.indexOf(this);
  54082. this._scene.spriteManagers.splice(index, 1);
  54083. // Callback
  54084. this.onDisposeObservable.notifyObservers(this);
  54085. this.onDisposeObservable.clear();
  54086. };
  54087. return SpriteManager;
  54088. }());
  54089. BABYLON.SpriteManager = SpriteManager;
  54090. })(BABYLON || (BABYLON = {}));
  54091. //# sourceMappingURL=babylon.spriteManager.js.map
  54092. var BABYLON;
  54093. (function (BABYLON) {
  54094. var Sprite = /** @class */ (function () {
  54095. function Sprite(name, manager) {
  54096. this.name = name;
  54097. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54098. this.width = 1.0;
  54099. this.height = 1.0;
  54100. this.angle = 0;
  54101. this.cellIndex = 0;
  54102. this.invertU = 0;
  54103. this.invertV = 0;
  54104. this.animations = new Array();
  54105. this.isPickable = false;
  54106. this._animationStarted = false;
  54107. this._loopAnimation = false;
  54108. this._fromIndex = 0;
  54109. this._toIndex = 0;
  54110. this._delay = 0;
  54111. this._direction = 1;
  54112. this._time = 0;
  54113. /**
  54114. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54115. */
  54116. this.isVisible = true;
  54117. this._manager = manager;
  54118. this._manager.sprites.push(this);
  54119. this.position = BABYLON.Vector3.Zero();
  54120. }
  54121. Object.defineProperty(Sprite.prototype, "size", {
  54122. get: function () {
  54123. return this.width;
  54124. },
  54125. set: function (value) {
  54126. this.width = value;
  54127. this.height = value;
  54128. },
  54129. enumerable: true,
  54130. configurable: true
  54131. });
  54132. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54133. this._fromIndex = from;
  54134. this._toIndex = to;
  54135. this._loopAnimation = loop;
  54136. this._delay = delay;
  54137. this._animationStarted = true;
  54138. this._direction = from < to ? 1 : -1;
  54139. this.cellIndex = from;
  54140. this._time = 0;
  54141. this._onAnimationEnd = onAnimationEnd;
  54142. };
  54143. Sprite.prototype.stopAnimation = function () {
  54144. this._animationStarted = false;
  54145. };
  54146. /** @hidden */
  54147. Sprite.prototype._animate = function (deltaTime) {
  54148. if (!this._animationStarted)
  54149. return;
  54150. this._time += deltaTime;
  54151. if (this._time > this._delay) {
  54152. this._time = this._time % this._delay;
  54153. this.cellIndex += this._direction;
  54154. if (this.cellIndex > this._toIndex) {
  54155. if (this._loopAnimation) {
  54156. this.cellIndex = this._fromIndex;
  54157. }
  54158. else {
  54159. this.cellIndex = this._toIndex;
  54160. this._animationStarted = false;
  54161. if (this._onAnimationEnd) {
  54162. this._onAnimationEnd();
  54163. }
  54164. if (this.disposeWhenFinishedAnimating) {
  54165. this.dispose();
  54166. }
  54167. }
  54168. }
  54169. }
  54170. };
  54171. Sprite.prototype.dispose = function () {
  54172. for (var i = 0; i < this._manager.sprites.length; i++) {
  54173. if (this._manager.sprites[i] == this) {
  54174. this._manager.sprites.splice(i, 1);
  54175. }
  54176. }
  54177. };
  54178. return Sprite;
  54179. }());
  54180. BABYLON.Sprite = Sprite;
  54181. })(BABYLON || (BABYLON = {}));
  54182. //# sourceMappingURL=babylon.sprite.js.map
  54183. var BABYLON;
  54184. (function (BABYLON) {
  54185. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  54186. if (!BABYLON.PickingInfo) {
  54187. return null;
  54188. }
  54189. var pickingInfo = null;
  54190. if (!camera) {
  54191. if (!this.activeCamera) {
  54192. return null;
  54193. }
  54194. camera = this.activeCamera;
  54195. }
  54196. if (this.spriteManagers.length > 0) {
  54197. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  54198. var spriteManager = this.spriteManagers[spriteIndex];
  54199. if (!spriteManager.isPickable) {
  54200. continue;
  54201. }
  54202. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  54203. if (!result || !result.hit)
  54204. continue;
  54205. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  54206. continue;
  54207. pickingInfo = result;
  54208. if (fastCheck) {
  54209. break;
  54210. }
  54211. }
  54212. }
  54213. return pickingInfo || new BABYLON.PickingInfo();
  54214. };
  54215. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  54216. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  54217. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54218. };
  54219. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  54220. if (!this._tempSpritePickingRay) {
  54221. return null;
  54222. }
  54223. if (!camera) {
  54224. if (!this.activeCamera) {
  54225. return null;
  54226. }
  54227. camera = this.activeCamera;
  54228. }
  54229. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  54230. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54231. };
  54232. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  54233. if (this._pointerOverSprite === sprite) {
  54234. return;
  54235. }
  54236. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  54237. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  54238. }
  54239. this._pointerOverSprite = sprite;
  54240. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  54241. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  54242. }
  54243. };
  54244. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  54245. return this._pointerOverSprite;
  54246. };
  54247. /**
  54248. * Defines the sprite scene component responsible to manage sprites
  54249. * in a given scene.
  54250. */
  54251. var SpriteSceneComponent = /** @class */ (function () {
  54252. /**
  54253. * Creates a new instance of the component for the given scene
  54254. * @param scene Defines the scene to register the component in
  54255. */
  54256. function SpriteSceneComponent(scene) {
  54257. /**
  54258. * The component name helpfull to identify the component in the list of scene components.
  54259. */
  54260. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  54261. this.scene = scene;
  54262. this.scene.spriteManagers = new Array();
  54263. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  54264. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  54265. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  54266. this._spritePredicate = function (sprite) {
  54267. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  54268. };
  54269. }
  54270. /**
  54271. * Registers the component in a given scene
  54272. */
  54273. SpriteSceneComponent.prototype.register = function () {
  54274. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  54275. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  54276. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  54277. };
  54278. /**
  54279. * Rebuilds the elements related to this component in case of
  54280. * context lost for instance.
  54281. */
  54282. SpriteSceneComponent.prototype.rebuild = function () {
  54283. /** Nothing to do for sprites */
  54284. };
  54285. /**
  54286. * Disposes the component and the associated ressources.
  54287. */
  54288. SpriteSceneComponent.prototype.dispose = function () {
  54289. this.scene.onBeforeSpritesRenderingObservable.clear();
  54290. this.scene.onAfterSpritesRenderingObservable.clear();
  54291. var spriteManagers = this.scene.spriteManagers;
  54292. while (spriteManagers.length) {
  54293. spriteManagers[0].dispose();
  54294. }
  54295. };
  54296. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  54297. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  54298. if (result) {
  54299. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  54300. }
  54301. return result;
  54302. };
  54303. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  54304. var scene = this.scene;
  54305. if (isMeshPicked) {
  54306. scene.setPointerOverSprite(null);
  54307. }
  54308. else {
  54309. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  54310. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  54311. scene.setPointerOverSprite(pickResult.pickedSprite);
  54312. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  54313. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  54314. }
  54315. else {
  54316. canvas.style.cursor = scene.hoverCursor;
  54317. }
  54318. }
  54319. else {
  54320. scene.setPointerOverSprite(null);
  54321. // Restore pointer
  54322. canvas.style.cursor = scene.defaultCursor;
  54323. }
  54324. }
  54325. return pickResult;
  54326. };
  54327. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54328. var scene = this.scene;
  54329. scene._pickedDownSprite = null;
  54330. if (scene.spriteManagers.length > 0) {
  54331. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54332. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  54333. if (pickResult.pickedSprite.actionManager) {
  54334. scene._pickedDownSprite = pickResult.pickedSprite;
  54335. switch (evt.button) {
  54336. case 0:
  54337. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54338. break;
  54339. case 1:
  54340. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54341. break;
  54342. case 2:
  54343. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54344. break;
  54345. }
  54346. if (pickResult.pickedSprite.actionManager) {
  54347. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54348. }
  54349. }
  54350. }
  54351. }
  54352. return pickResult;
  54353. };
  54354. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54355. var scene = this.scene;
  54356. if (scene.spriteManagers.length > 0) {
  54357. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54358. if (spritePickResult) {
  54359. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  54360. if (spritePickResult.pickedSprite.actionManager) {
  54361. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54362. if (spritePickResult.pickedSprite.actionManager) {
  54363. if (!this.scene._isPointerSwiping()) {
  54364. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54365. }
  54366. }
  54367. }
  54368. }
  54369. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  54370. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  54371. }
  54372. }
  54373. }
  54374. return pickResult;
  54375. };
  54376. return SpriteSceneComponent;
  54377. }());
  54378. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  54379. })(BABYLON || (BABYLON = {}));
  54380. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  54381. var BABYLON;
  54382. (function (BABYLON) {
  54383. var IntersectionInfo = /** @class */ (function () {
  54384. function IntersectionInfo(bu, bv, distance) {
  54385. this.bu = bu;
  54386. this.bv = bv;
  54387. this.distance = distance;
  54388. this.faceId = 0;
  54389. this.subMeshId = 0;
  54390. }
  54391. return IntersectionInfo;
  54392. }());
  54393. BABYLON.IntersectionInfo = IntersectionInfo;
  54394. /**
  54395. * Information about the result of picking within a scene
  54396. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54397. */
  54398. var PickingInfo = /** @class */ (function () {
  54399. function PickingInfo() {
  54400. /**
  54401. * If the pick collided with an object
  54402. */
  54403. this.hit = false;
  54404. /**
  54405. * Distance away where the pick collided
  54406. */
  54407. this.distance = 0;
  54408. /**
  54409. * The location of pick collision
  54410. */
  54411. this.pickedPoint = null;
  54412. /**
  54413. * The mesh corresponding the the pick collision
  54414. */
  54415. this.pickedMesh = null;
  54416. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54417. this.bu = 0;
  54418. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54419. this.bv = 0;
  54420. /** The id of the face on the mesh that was picked */
  54421. this.faceId = -1;
  54422. /** Id of the the submesh that was picked */
  54423. this.subMeshId = 0;
  54424. /** If a sprite was picked, this will be the sprite the pick collided with */
  54425. this.pickedSprite = null;
  54426. /**
  54427. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54428. */
  54429. this.originMesh = null;
  54430. /**
  54431. * The ray that was used to perform the picking.
  54432. */
  54433. this.ray = null;
  54434. }
  54435. /**
  54436. * Gets the normal correspodning to the face the pick collided with
  54437. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54438. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54439. * @returns The normal correspodning to the face the pick collided with
  54440. */
  54441. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54442. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54443. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54444. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54445. return null;
  54446. }
  54447. var indices = this.pickedMesh.getIndices();
  54448. if (!indices) {
  54449. return null;
  54450. }
  54451. var result;
  54452. if (useVerticesNormals) {
  54453. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54454. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54455. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54456. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54457. normal0 = normal0.scale(this.bu);
  54458. normal1 = normal1.scale(this.bv);
  54459. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54460. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54461. }
  54462. else {
  54463. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54464. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54465. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54466. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54467. var p1p2 = vertex1.subtract(vertex2);
  54468. var p3p2 = vertex3.subtract(vertex2);
  54469. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54470. }
  54471. if (useWorldCoordinates) {
  54472. var wm = this.pickedMesh.getWorldMatrix();
  54473. if (this.pickedMesh.nonUniformScaling) {
  54474. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54475. wm = BABYLON.Tmp.Matrix[0];
  54476. wm.setTranslationFromFloats(0, 0, 0);
  54477. wm.invert();
  54478. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54479. wm = BABYLON.Tmp.Matrix[1];
  54480. }
  54481. result = BABYLON.Vector3.TransformNormal(result, wm);
  54482. }
  54483. result.normalize();
  54484. return result;
  54485. };
  54486. /**
  54487. * Gets the texture coordinates of where the pick occured
  54488. * @returns the vector containing the coordnates of the texture
  54489. */
  54490. PickingInfo.prototype.getTextureCoordinates = function () {
  54491. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54492. return null;
  54493. }
  54494. var indices = this.pickedMesh.getIndices();
  54495. if (!indices) {
  54496. return null;
  54497. }
  54498. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54499. if (!uvs) {
  54500. return null;
  54501. }
  54502. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54503. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54504. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54505. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54506. uv1 = uv1.scale(this.bu);
  54507. uv2 = uv2.scale(this.bv);
  54508. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54509. };
  54510. return PickingInfo;
  54511. }());
  54512. BABYLON.PickingInfo = PickingInfo;
  54513. })(BABYLON || (BABYLON = {}));
  54514. //# sourceMappingURL=babylon.pickingInfo.js.map
  54515. var BABYLON;
  54516. (function (BABYLON) {
  54517. var Ray = /** @class */ (function () {
  54518. function Ray(origin, direction, length) {
  54519. if (length === void 0) { length = Number.MAX_VALUE; }
  54520. this.origin = origin;
  54521. this.direction = direction;
  54522. this.length = length;
  54523. }
  54524. // Methods
  54525. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54526. var d = 0.0;
  54527. var maxValue = Number.MAX_VALUE;
  54528. var inv;
  54529. var min;
  54530. var max;
  54531. var temp;
  54532. if (Math.abs(this.direction.x) < 0.0000001) {
  54533. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54534. return false;
  54535. }
  54536. }
  54537. else {
  54538. inv = 1.0 / this.direction.x;
  54539. min = (minimum.x - this.origin.x) * inv;
  54540. max = (maximum.x - this.origin.x) * inv;
  54541. if (max === -Infinity) {
  54542. max = Infinity;
  54543. }
  54544. if (min > max) {
  54545. temp = min;
  54546. min = max;
  54547. max = temp;
  54548. }
  54549. d = Math.max(min, d);
  54550. maxValue = Math.min(max, maxValue);
  54551. if (d > maxValue) {
  54552. return false;
  54553. }
  54554. }
  54555. if (Math.abs(this.direction.y) < 0.0000001) {
  54556. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54557. return false;
  54558. }
  54559. }
  54560. else {
  54561. inv = 1.0 / this.direction.y;
  54562. min = (minimum.y - this.origin.y) * inv;
  54563. max = (maximum.y - this.origin.y) * inv;
  54564. if (max === -Infinity) {
  54565. max = Infinity;
  54566. }
  54567. if (min > max) {
  54568. temp = min;
  54569. min = max;
  54570. max = temp;
  54571. }
  54572. d = Math.max(min, d);
  54573. maxValue = Math.min(max, maxValue);
  54574. if (d > maxValue) {
  54575. return false;
  54576. }
  54577. }
  54578. if (Math.abs(this.direction.z) < 0.0000001) {
  54579. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54580. return false;
  54581. }
  54582. }
  54583. else {
  54584. inv = 1.0 / this.direction.z;
  54585. min = (minimum.z - this.origin.z) * inv;
  54586. max = (maximum.z - this.origin.z) * inv;
  54587. if (max === -Infinity) {
  54588. max = Infinity;
  54589. }
  54590. if (min > max) {
  54591. temp = min;
  54592. min = max;
  54593. max = temp;
  54594. }
  54595. d = Math.max(min, d);
  54596. maxValue = Math.min(max, maxValue);
  54597. if (d > maxValue) {
  54598. return false;
  54599. }
  54600. }
  54601. return true;
  54602. };
  54603. Ray.prototype.intersectsBox = function (box) {
  54604. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54605. };
  54606. Ray.prototype.intersectsSphere = function (sphere) {
  54607. var x = sphere.center.x - this.origin.x;
  54608. var y = sphere.center.y - this.origin.y;
  54609. var z = sphere.center.z - this.origin.z;
  54610. var pyth = (x * x) + (y * y) + (z * z);
  54611. var rr = sphere.radius * sphere.radius;
  54612. if (pyth <= rr) {
  54613. return true;
  54614. }
  54615. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54616. if (dot < 0.0) {
  54617. return false;
  54618. }
  54619. var temp = pyth - (dot * dot);
  54620. return temp <= rr;
  54621. };
  54622. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54623. if (!this._edge1) {
  54624. this._edge1 = BABYLON.Vector3.Zero();
  54625. this._edge2 = BABYLON.Vector3.Zero();
  54626. this._pvec = BABYLON.Vector3.Zero();
  54627. this._tvec = BABYLON.Vector3.Zero();
  54628. this._qvec = BABYLON.Vector3.Zero();
  54629. }
  54630. vertex1.subtractToRef(vertex0, this._edge1);
  54631. vertex2.subtractToRef(vertex0, this._edge2);
  54632. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54633. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54634. if (det === 0) {
  54635. return null;
  54636. }
  54637. var invdet = 1 / det;
  54638. this.origin.subtractToRef(vertex0, this._tvec);
  54639. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54640. if (bu < 0 || bu > 1.0) {
  54641. return null;
  54642. }
  54643. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54644. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54645. if (bv < 0 || bu + bv > 1.0) {
  54646. return null;
  54647. }
  54648. //check if the distance is longer than the predefined length.
  54649. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54650. if (distance > this.length) {
  54651. return null;
  54652. }
  54653. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54654. };
  54655. Ray.prototype.intersectsPlane = function (plane) {
  54656. var distance;
  54657. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54658. if (Math.abs(result1) < 9.99999997475243E-07) {
  54659. return null;
  54660. }
  54661. else {
  54662. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54663. distance = (-plane.d - result2) / result1;
  54664. if (distance < 0.0) {
  54665. if (distance < -9.99999997475243E-07) {
  54666. return null;
  54667. }
  54668. else {
  54669. return 0;
  54670. }
  54671. }
  54672. return distance;
  54673. }
  54674. };
  54675. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54676. var tm = BABYLON.Tmp.Matrix[0];
  54677. mesh.getWorldMatrix().invertToRef(tm);
  54678. if (this._tmpRay) {
  54679. Ray.TransformToRef(this, tm, this._tmpRay);
  54680. }
  54681. else {
  54682. this._tmpRay = Ray.Transform(this, tm);
  54683. }
  54684. return mesh.intersects(this._tmpRay, fastCheck);
  54685. };
  54686. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54687. if (results) {
  54688. results.length = 0;
  54689. }
  54690. else {
  54691. results = [];
  54692. }
  54693. for (var i = 0; i < meshes.length; i++) {
  54694. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54695. if (pickInfo.hit) {
  54696. results.push(pickInfo);
  54697. }
  54698. }
  54699. results.sort(this._comparePickingInfo);
  54700. return results;
  54701. };
  54702. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54703. if (pickingInfoA.distance < pickingInfoB.distance) {
  54704. return -1;
  54705. }
  54706. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54707. return 1;
  54708. }
  54709. else {
  54710. return 0;
  54711. }
  54712. };
  54713. /**
  54714. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54715. * @param sega the first point of the segment to test the intersection against
  54716. * @param segb the second point of the segment to test the intersection against
  54717. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54718. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54719. */
  54720. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54721. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54722. var u = segb.subtract(sega);
  54723. var v = rsegb.subtract(this.origin);
  54724. var w = sega.subtract(this.origin);
  54725. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54726. var b = BABYLON.Vector3.Dot(u, v);
  54727. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54728. var d = BABYLON.Vector3.Dot(u, w);
  54729. var e = BABYLON.Vector3.Dot(v, w);
  54730. var D = a * c - b * b; // always >= 0
  54731. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54732. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54733. // compute the line parameters of the two closest points
  54734. if (D < Ray.smallnum) { // the lines are almost parallel
  54735. sN = 0.0; // force using point P0 on segment S1
  54736. sD = 1.0; // to prevent possible division by 0.0 later
  54737. tN = e;
  54738. tD = c;
  54739. }
  54740. else { // get the closest points on the infinite lines
  54741. sN = (b * e - c * d);
  54742. tN = (a * e - b * d);
  54743. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54744. sN = 0.0;
  54745. tN = e;
  54746. tD = c;
  54747. }
  54748. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54749. sN = sD;
  54750. tN = e + b;
  54751. tD = c;
  54752. }
  54753. }
  54754. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54755. tN = 0.0;
  54756. // recompute sc for this edge
  54757. if (-d < 0.0) {
  54758. sN = 0.0;
  54759. }
  54760. else if (-d > a)
  54761. sN = sD;
  54762. else {
  54763. sN = -d;
  54764. sD = a;
  54765. }
  54766. }
  54767. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54768. tN = tD;
  54769. // recompute sc for this edge
  54770. if ((-d + b) < 0.0) {
  54771. sN = 0;
  54772. }
  54773. else if ((-d + b) > a) {
  54774. sN = sD;
  54775. }
  54776. else {
  54777. sN = (-d + b);
  54778. sD = a;
  54779. }
  54780. }
  54781. // finally do the division to get sc and tc
  54782. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54783. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54784. // get the difference of the two closest points
  54785. var qtc = v.multiplyByFloats(tc, tc, tc);
  54786. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54787. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54788. if (isIntersected) {
  54789. return qtc.length();
  54790. }
  54791. return -1;
  54792. };
  54793. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54794. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54795. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54796. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54797. this.direction.normalize();
  54798. return this;
  54799. };
  54800. // Statics
  54801. Ray.Zero = function () {
  54802. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54803. };
  54804. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54805. var result = Ray.Zero();
  54806. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54807. };
  54808. /**
  54809. * 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
  54810. * transformed to the given world matrix.
  54811. * @param origin The origin point
  54812. * @param end The end point
  54813. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54814. */
  54815. Ray.CreateNewFromTo = function (origin, end, world) {
  54816. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54817. var direction = end.subtract(origin);
  54818. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54819. direction.normalize();
  54820. return Ray.Transform(new Ray(origin, direction, length), world);
  54821. };
  54822. Ray.Transform = function (ray, matrix) {
  54823. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54824. Ray.TransformToRef(ray, matrix, result);
  54825. return result;
  54826. };
  54827. Ray.TransformToRef = function (ray, matrix, result) {
  54828. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54829. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54830. result.length = ray.length;
  54831. var dir = result.direction;
  54832. var len = dir.length();
  54833. if (!(len === 0 || len === 1)) {
  54834. var num = 1.0 / len;
  54835. dir.x *= num;
  54836. dir.y *= num;
  54837. dir.z *= num;
  54838. result.length *= len;
  54839. }
  54840. };
  54841. Ray.smallnum = 0.00000001;
  54842. Ray.rayl = 10e8;
  54843. return Ray;
  54844. }());
  54845. BABYLON.Ray = Ray;
  54846. })(BABYLON || (BABYLON = {}));
  54847. //# sourceMappingURL=babylon.ray.js.map
  54848. var BABYLON;
  54849. (function (BABYLON) {
  54850. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54851. if (boxMin.x > sphereCenter.x + sphereRadius)
  54852. return false;
  54853. if (sphereCenter.x - sphereRadius > boxMax.x)
  54854. return false;
  54855. if (boxMin.y > sphereCenter.y + sphereRadius)
  54856. return false;
  54857. if (sphereCenter.y - sphereRadius > boxMax.y)
  54858. return false;
  54859. if (boxMin.z > sphereCenter.z + sphereRadius)
  54860. return false;
  54861. if (sphereCenter.z - sphereRadius > boxMax.z)
  54862. return false;
  54863. return true;
  54864. };
  54865. var getLowestRoot = (function () {
  54866. var result = { root: 0, found: false };
  54867. return function (a, b, c, maxR) {
  54868. result.root = 0;
  54869. result.found = false;
  54870. var determinant = b * b - 4.0 * a * c;
  54871. if (determinant < 0)
  54872. return result;
  54873. var sqrtD = Math.sqrt(determinant);
  54874. var r1 = (-b - sqrtD) / (2.0 * a);
  54875. var r2 = (-b + sqrtD) / (2.0 * a);
  54876. if (r1 > r2) {
  54877. var temp = r2;
  54878. r2 = r1;
  54879. r1 = temp;
  54880. }
  54881. if (r1 > 0 && r1 < maxR) {
  54882. result.root = r1;
  54883. result.found = true;
  54884. return result;
  54885. }
  54886. if (r2 > 0 && r2 < maxR) {
  54887. result.root = r2;
  54888. result.found = true;
  54889. return result;
  54890. }
  54891. return result;
  54892. };
  54893. })();
  54894. var Collider = /** @class */ (function () {
  54895. function Collider() {
  54896. this._collisionPoint = BABYLON.Vector3.Zero();
  54897. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54898. this._tempVector = BABYLON.Vector3.Zero();
  54899. this._tempVector2 = BABYLON.Vector3.Zero();
  54900. this._tempVector3 = BABYLON.Vector3.Zero();
  54901. this._tempVector4 = BABYLON.Vector3.Zero();
  54902. this._edge = BABYLON.Vector3.Zero();
  54903. this._baseToVertex = BABYLON.Vector3.Zero();
  54904. this._destinationPoint = BABYLON.Vector3.Zero();
  54905. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54906. this._displacementVector = BABYLON.Vector3.Zero();
  54907. /** @hidden */
  54908. this._radius = BABYLON.Vector3.One();
  54909. /** @hidden */
  54910. this._retry = 0;
  54911. /** @hidden */
  54912. this._basePointWorld = BABYLON.Vector3.Zero();
  54913. this._velocityWorld = BABYLON.Vector3.Zero();
  54914. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54915. this._collisionMask = -1;
  54916. }
  54917. Object.defineProperty(Collider.prototype, "collisionMask", {
  54918. get: function () {
  54919. return this._collisionMask;
  54920. },
  54921. set: function (mask) {
  54922. this._collisionMask = !isNaN(mask) ? mask : -1;
  54923. },
  54924. enumerable: true,
  54925. configurable: true
  54926. });
  54927. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54928. /**
  54929. * Gets the plane normal used to compute the sliding response (in local space)
  54930. */
  54931. get: function () {
  54932. return this._slidePlaneNormal;
  54933. },
  54934. enumerable: true,
  54935. configurable: true
  54936. });
  54937. // Methods
  54938. /** @hidden */
  54939. Collider.prototype._initialize = function (source, dir, e) {
  54940. this._velocity = dir;
  54941. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54942. this._basePoint = source;
  54943. source.multiplyToRef(this._radius, this._basePointWorld);
  54944. dir.multiplyToRef(this._radius, this._velocityWorld);
  54945. this._velocityWorldLength = this._velocityWorld.length();
  54946. this._epsilon = e;
  54947. this.collisionFound = false;
  54948. };
  54949. /** @hidden */
  54950. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54951. pa.subtractToRef(point, this._tempVector);
  54952. pb.subtractToRef(point, this._tempVector2);
  54953. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54954. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54955. if (d < 0)
  54956. return false;
  54957. pc.subtractToRef(point, this._tempVector3);
  54958. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54959. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54960. if (d < 0)
  54961. return false;
  54962. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54963. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54964. return d >= 0;
  54965. };
  54966. /** @hidden */
  54967. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54968. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54969. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54970. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54971. return false;
  54972. }
  54973. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54974. return false;
  54975. return true;
  54976. };
  54977. /** @hidden */
  54978. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54979. var t0;
  54980. var embeddedInPlane = false;
  54981. //defensive programming, actually not needed.
  54982. if (!trianglePlaneArray) {
  54983. trianglePlaneArray = [];
  54984. }
  54985. if (!trianglePlaneArray[faceIndex]) {
  54986. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54987. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54988. }
  54989. var trianglePlane = trianglePlaneArray[faceIndex];
  54990. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54991. return;
  54992. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54993. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54994. if (normalDotVelocity == 0) {
  54995. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54996. return;
  54997. embeddedInPlane = true;
  54998. t0 = 0;
  54999. }
  55000. else {
  55001. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55002. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55003. if (t0 > t1) {
  55004. var temp = t1;
  55005. t1 = t0;
  55006. t0 = temp;
  55007. }
  55008. if (t0 > 1.0 || t1 < 0.0)
  55009. return;
  55010. if (t0 < 0)
  55011. t0 = 0;
  55012. if (t0 > 1.0)
  55013. t0 = 1.0;
  55014. }
  55015. this._collisionPoint.copyFromFloats(0, 0, 0);
  55016. var found = false;
  55017. var t = 1.0;
  55018. if (!embeddedInPlane) {
  55019. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55020. this._velocity.scaleToRef(t0, this._tempVector);
  55021. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55022. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55023. found = true;
  55024. t = t0;
  55025. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55026. }
  55027. }
  55028. if (!found) {
  55029. var velocitySquaredLength = this._velocity.lengthSquared();
  55030. var a = velocitySquaredLength;
  55031. this._basePoint.subtractToRef(p1, this._tempVector);
  55032. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55033. var c = this._tempVector.lengthSquared() - 1.0;
  55034. var lowestRoot = getLowestRoot(a, b, c, t);
  55035. if (lowestRoot.found) {
  55036. t = lowestRoot.root;
  55037. found = true;
  55038. this._collisionPoint.copyFrom(p1);
  55039. }
  55040. this._basePoint.subtractToRef(p2, this._tempVector);
  55041. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55042. c = this._tempVector.lengthSquared() - 1.0;
  55043. lowestRoot = getLowestRoot(a, b, c, t);
  55044. if (lowestRoot.found) {
  55045. t = lowestRoot.root;
  55046. found = true;
  55047. this._collisionPoint.copyFrom(p2);
  55048. }
  55049. this._basePoint.subtractToRef(p3, this._tempVector);
  55050. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55051. c = this._tempVector.lengthSquared() - 1.0;
  55052. lowestRoot = getLowestRoot(a, b, c, t);
  55053. if (lowestRoot.found) {
  55054. t = lowestRoot.root;
  55055. found = true;
  55056. this._collisionPoint.copyFrom(p3);
  55057. }
  55058. p2.subtractToRef(p1, this._edge);
  55059. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55060. var edgeSquaredLength = this._edge.lengthSquared();
  55061. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55062. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55063. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55064. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55065. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55066. lowestRoot = getLowestRoot(a, b, c, t);
  55067. if (lowestRoot.found) {
  55068. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55069. if (f >= 0.0 && f <= 1.0) {
  55070. t = lowestRoot.root;
  55071. found = true;
  55072. this._edge.scaleInPlace(f);
  55073. p1.addToRef(this._edge, this._collisionPoint);
  55074. }
  55075. }
  55076. p3.subtractToRef(p2, this._edge);
  55077. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55078. edgeSquaredLength = this._edge.lengthSquared();
  55079. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55080. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55081. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55082. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55083. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55084. lowestRoot = getLowestRoot(a, b, c, t);
  55085. if (lowestRoot.found) {
  55086. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55087. if (f >= 0.0 && f <= 1.0) {
  55088. t = lowestRoot.root;
  55089. found = true;
  55090. this._edge.scaleInPlace(f);
  55091. p2.addToRef(this._edge, this._collisionPoint);
  55092. }
  55093. }
  55094. p1.subtractToRef(p3, this._edge);
  55095. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55096. edgeSquaredLength = this._edge.lengthSquared();
  55097. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55098. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55099. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55100. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55101. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55102. lowestRoot = getLowestRoot(a, b, c, t);
  55103. if (lowestRoot.found) {
  55104. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55105. if (f >= 0.0 && f <= 1.0) {
  55106. t = lowestRoot.root;
  55107. found = true;
  55108. this._edge.scaleInPlace(f);
  55109. p3.addToRef(this._edge, this._collisionPoint);
  55110. }
  55111. }
  55112. }
  55113. if (found) {
  55114. var distToCollision = t * this._velocity.length();
  55115. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55116. if (!this.intersectionPoint) {
  55117. this.intersectionPoint = this._collisionPoint.clone();
  55118. }
  55119. else {
  55120. this.intersectionPoint.copyFrom(this._collisionPoint);
  55121. }
  55122. this._nearestDistance = distToCollision;
  55123. this.collisionFound = true;
  55124. }
  55125. }
  55126. };
  55127. /** @hidden */
  55128. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55129. for (var i = indexStart; i < indexEnd; i += 3) {
  55130. var p1 = pts[indices[i] - decal];
  55131. var p2 = pts[indices[i + 1] - decal];
  55132. var p3 = pts[indices[i + 2] - decal];
  55133. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55134. }
  55135. };
  55136. /** @hidden */
  55137. Collider.prototype._getResponse = function (pos, vel) {
  55138. pos.addToRef(vel, this._destinationPoint);
  55139. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55140. this._basePoint.addToRef(vel, pos);
  55141. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55142. this._slidePlaneNormal.normalize();
  55143. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55144. pos.addInPlace(this._displacementVector);
  55145. this.intersectionPoint.addInPlace(this._displacementVector);
  55146. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55147. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55148. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55149. };
  55150. return Collider;
  55151. }());
  55152. BABYLON.Collider = Collider;
  55153. })(BABYLON || (BABYLON = {}));
  55154. //# sourceMappingURL=babylon.collider.js.map
  55155. var BABYLON;
  55156. (function (BABYLON) {
  55157. //WebWorker code will be inserted to this variable.
  55158. BABYLON.CollisionWorker = "";
  55159. /** Defines supported task for worker process */
  55160. var WorkerTaskType;
  55161. (function (WorkerTaskType) {
  55162. /** Initialization */
  55163. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55164. /** Update of geometry */
  55165. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55166. /** Evaluate collision */
  55167. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55168. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55169. /** Defines kind of replies returned by worker */
  55170. var WorkerReplyType;
  55171. (function (WorkerReplyType) {
  55172. /** Success */
  55173. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55174. /** Unkown error */
  55175. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55176. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55177. var CollisionCoordinatorWorker = /** @class */ (function () {
  55178. function CollisionCoordinatorWorker() {
  55179. var _this = this;
  55180. this._scaledPosition = BABYLON.Vector3.Zero();
  55181. this._scaledVelocity = BABYLON.Vector3.Zero();
  55182. this.onMeshUpdated = function (transformNode) {
  55183. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55184. };
  55185. this.onGeometryUpdated = function (geometry) {
  55186. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55187. };
  55188. this._afterRender = function () {
  55189. if (!_this._init)
  55190. return;
  55191. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55192. return;
  55193. }
  55194. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55195. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55196. if (_this._runningUpdated > 4) {
  55197. return;
  55198. }
  55199. ++_this._runningUpdated;
  55200. var payload = {
  55201. updatedMeshes: _this._addUpdateMeshesList,
  55202. updatedGeometries: _this._addUpdateGeometriesList,
  55203. removedGeometries: _this._toRemoveGeometryArray,
  55204. removedMeshes: _this._toRemoveMeshesArray
  55205. };
  55206. var message = {
  55207. payload: payload,
  55208. taskType: WorkerTaskType.UPDATE
  55209. };
  55210. var serializable = [];
  55211. for (var id in payload.updatedGeometries) {
  55212. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55213. //prepare transferables
  55214. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55215. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55216. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55217. }
  55218. }
  55219. _this._worker.postMessage(message, serializable);
  55220. _this._addUpdateMeshesList = {};
  55221. _this._addUpdateGeometriesList = {};
  55222. _this._toRemoveGeometryArray = [];
  55223. _this._toRemoveMeshesArray = [];
  55224. };
  55225. this._onMessageFromWorker = function (e) {
  55226. var returnData = e.data;
  55227. if (returnData.error != WorkerReplyType.SUCCESS) {
  55228. //TODO what errors can be returned from the worker?
  55229. BABYLON.Tools.Warn("error returned from worker!");
  55230. return;
  55231. }
  55232. switch (returnData.taskType) {
  55233. case WorkerTaskType.INIT:
  55234. _this._init = true;
  55235. //Update the worked with ALL of the scene's current state
  55236. _this._scene.meshes.forEach(function (mesh) {
  55237. _this.onMeshAdded(mesh);
  55238. });
  55239. _this._scene.getGeometries().forEach(function (geometry) {
  55240. _this.onGeometryAdded(geometry);
  55241. });
  55242. break;
  55243. case WorkerTaskType.UPDATE:
  55244. _this._runningUpdated--;
  55245. break;
  55246. case WorkerTaskType.COLLIDE:
  55247. var returnPayload = returnData.payload;
  55248. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55249. return;
  55250. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55251. if (callback) {
  55252. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55253. if (mesh) {
  55254. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55255. }
  55256. }
  55257. //cleanup
  55258. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55259. break;
  55260. }
  55261. };
  55262. this._collisionsCallbackArray = [];
  55263. this._init = false;
  55264. this._runningUpdated = 0;
  55265. this._addUpdateMeshesList = {};
  55266. this._addUpdateGeometriesList = {};
  55267. this._toRemoveGeometryArray = [];
  55268. this._toRemoveMeshesArray = [];
  55269. }
  55270. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55271. if (!this._init)
  55272. return;
  55273. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55274. return;
  55275. position.divideToRef(collider._radius, this._scaledPosition);
  55276. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55277. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55278. var payload = {
  55279. collider: {
  55280. position: this._scaledPosition.asArray(),
  55281. velocity: this._scaledVelocity.asArray(),
  55282. radius: collider._radius.asArray()
  55283. },
  55284. collisionId: collisionIndex,
  55285. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55286. maximumRetry: maximumRetry
  55287. };
  55288. var message = {
  55289. payload: payload,
  55290. taskType: WorkerTaskType.COLLIDE
  55291. };
  55292. this._worker.postMessage(message);
  55293. };
  55294. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55295. this._scene = scene;
  55296. this._scene.registerAfterRender(this._afterRender);
  55297. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55298. this._worker = new Worker(workerUrl);
  55299. this._worker.onmessage = this._onMessageFromWorker;
  55300. var message = {
  55301. payload: {},
  55302. taskType: WorkerTaskType.INIT
  55303. };
  55304. this._worker.postMessage(message);
  55305. };
  55306. CollisionCoordinatorWorker.prototype.destroy = function () {
  55307. this._scene.unregisterAfterRender(this._afterRender);
  55308. this._worker.terminate();
  55309. };
  55310. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55311. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55312. this.onMeshUpdated(mesh);
  55313. };
  55314. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55315. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55316. };
  55317. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55318. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55319. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55320. this.onGeometryUpdated(geometry);
  55321. };
  55322. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55323. this._toRemoveGeometryArray.push(geometry.id);
  55324. };
  55325. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55326. var submeshes = [];
  55327. if (mesh.subMeshes) {
  55328. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55329. var boundingInfo = sm.getBoundingInfo();
  55330. return {
  55331. position: idx,
  55332. verticesStart: sm.verticesStart,
  55333. verticesCount: sm.verticesCount,
  55334. indexStart: sm.indexStart,
  55335. indexCount: sm.indexCount,
  55336. hasMaterial: !!sm.getMaterial(),
  55337. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55338. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55339. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55340. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55341. };
  55342. });
  55343. }
  55344. var geometryId = null;
  55345. if (mesh instanceof BABYLON.Mesh) {
  55346. var geometry = mesh.geometry;
  55347. geometryId = geometry ? geometry.id : null;
  55348. }
  55349. else if (mesh instanceof BABYLON.InstancedMesh) {
  55350. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55351. geometryId = geometry ? geometry.id : null;
  55352. }
  55353. var boundingInfo = mesh.getBoundingInfo();
  55354. return {
  55355. uniqueId: mesh.uniqueId,
  55356. id: mesh.id,
  55357. name: mesh.name,
  55358. geometryId: geometryId,
  55359. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55360. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55361. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55362. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55363. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55364. subMeshes: submeshes,
  55365. checkCollisions: mesh.checkCollisions
  55366. };
  55367. };
  55368. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55369. return {
  55370. id: geometry.id,
  55371. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55372. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55373. indices: new Uint32Array(geometry.getIndices() || []),
  55374. };
  55375. };
  55376. return CollisionCoordinatorWorker;
  55377. }());
  55378. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55379. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55380. function CollisionCoordinatorLegacy() {
  55381. this._scaledPosition = BABYLON.Vector3.Zero();
  55382. this._scaledVelocity = BABYLON.Vector3.Zero();
  55383. this._finalPosition = BABYLON.Vector3.Zero();
  55384. }
  55385. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55386. position.divideToRef(collider._radius, this._scaledPosition);
  55387. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55388. collider.collidedMesh = null;
  55389. collider._retry = 0;
  55390. collider._initialVelocity = this._scaledVelocity;
  55391. collider._initialPosition = this._scaledPosition;
  55392. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55393. this._finalPosition.multiplyInPlace(collider._radius);
  55394. //run the callback
  55395. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55396. };
  55397. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55398. this._scene = scene;
  55399. };
  55400. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55401. //Legacy need no destruction method.
  55402. };
  55403. //No update in legacy mode
  55404. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55405. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55406. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55407. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55408. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55409. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55410. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55411. if (excludedMesh === void 0) { excludedMesh = null; }
  55412. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55413. if (collider._retry >= maximumRetry) {
  55414. finalPosition.copyFrom(position);
  55415. return;
  55416. }
  55417. // Check if this is a mesh else camera or -1
  55418. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55419. collider._initialize(position, velocity, closeDistance);
  55420. // Check all meshes
  55421. for (var index = 0; index < this._scene.meshes.length; index++) {
  55422. var mesh = this._scene.meshes[index];
  55423. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55424. mesh._checkCollision(collider);
  55425. }
  55426. }
  55427. if (!collider.collisionFound) {
  55428. position.addToRef(velocity, finalPosition);
  55429. return;
  55430. }
  55431. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55432. collider._getResponse(position, velocity);
  55433. }
  55434. if (velocity.length() <= closeDistance) {
  55435. finalPosition.copyFrom(position);
  55436. return;
  55437. }
  55438. collider._retry++;
  55439. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55440. };
  55441. return CollisionCoordinatorLegacy;
  55442. }());
  55443. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55444. })(BABYLON || (BABYLON = {}));
  55445. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55446. var BABYLON;
  55447. (function (BABYLON) {
  55448. /**
  55449. * A particle represents one of the element emitted by a particle system.
  55450. * This is mainly define by its coordinates, direction, velocity and age.
  55451. */
  55452. var Particle = /** @class */ (function () {
  55453. /**
  55454. * Creates a new instance Particle
  55455. * @param particleSystem the particle system the particle belongs to
  55456. */
  55457. function Particle(
  55458. /**
  55459. * The particle system the particle belongs to.
  55460. */
  55461. particleSystem) {
  55462. this.particleSystem = particleSystem;
  55463. /**
  55464. * The world position of the particle in the scene.
  55465. */
  55466. this.position = BABYLON.Vector3.Zero();
  55467. /**
  55468. * The world direction of the particle in the scene.
  55469. */
  55470. this.direction = BABYLON.Vector3.Zero();
  55471. /**
  55472. * The color of the particle.
  55473. */
  55474. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55475. /**
  55476. * The color change of the particle per step.
  55477. */
  55478. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55479. /**
  55480. * Defines how long will the life of the particle be.
  55481. */
  55482. this.lifeTime = 1.0;
  55483. /**
  55484. * The current age of the particle.
  55485. */
  55486. this.age = 0;
  55487. /**
  55488. * The current size of the particle.
  55489. */
  55490. this.size = 0;
  55491. /**
  55492. * The current scale of the particle.
  55493. */
  55494. this.scale = new BABYLON.Vector2(1, 1);
  55495. /**
  55496. * The current angle of the particle.
  55497. */
  55498. this.angle = 0;
  55499. /**
  55500. * Defines how fast is the angle changing.
  55501. */
  55502. this.angularSpeed = 0;
  55503. /**
  55504. * Defines the cell index used by the particle to be rendered from a sprite.
  55505. */
  55506. this.cellIndex = 0;
  55507. /** @hidden */
  55508. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55509. /** @hidden */
  55510. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55511. /** @hidden */
  55512. this._currentSize1 = 0;
  55513. /** @hidden */
  55514. this._currentSize2 = 0;
  55515. /** @hidden */
  55516. this._currentAngularSpeed1 = 0;
  55517. /** @hidden */
  55518. this._currentAngularSpeed2 = 0;
  55519. /** @hidden */
  55520. this._currentVelocity1 = 0;
  55521. /** @hidden */
  55522. this._currentVelocity2 = 0;
  55523. /** @hidden */
  55524. this._currentLimitVelocity1 = 0;
  55525. /** @hidden */
  55526. this._currentLimitVelocity2 = 0;
  55527. /** @hidden */
  55528. this._currentDrag1 = 0;
  55529. /** @hidden */
  55530. this._currentDrag2 = 0;
  55531. if (!this.particleSystem.isAnimationSheetEnabled) {
  55532. return;
  55533. }
  55534. this.updateCellInfoFromSystem();
  55535. }
  55536. Particle.prototype.updateCellInfoFromSystem = function () {
  55537. this.cellIndex = this.particleSystem.startSpriteCellID;
  55538. };
  55539. /**
  55540. * Defines how the sprite cell index is updated for the particle
  55541. */
  55542. Particle.prototype.updateCellIndex = function () {
  55543. var offsetAge = this.age;
  55544. if (this.particleSystem.spriteRandomStartCell) {
  55545. if (this._randomCellOffset === undefined) {
  55546. this._randomCellOffset = Math.random() * this.lifeTime;
  55547. }
  55548. offsetAge += this._randomCellOffset;
  55549. }
  55550. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55551. var ratio = BABYLON.Scalar.Clamp(((offsetAge * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55552. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55553. };
  55554. /** @hidden */
  55555. Particle.prototype._reset = function () {
  55556. this.age = 0;
  55557. this._currentColorGradient = null;
  55558. this._currentSizeGradient = null;
  55559. this._currentAngularSpeedGradient = null;
  55560. this._currentVelocityGradient = null;
  55561. this._currentLimitVelocityGradient = null;
  55562. this._currentDragGradient = null;
  55563. this.cellIndex = this.particleSystem.startSpriteCellID;
  55564. this._randomCellOffset = undefined;
  55565. };
  55566. /**
  55567. * Copy the properties of particle to another one.
  55568. * @param other the particle to copy the information to.
  55569. */
  55570. Particle.prototype.copyTo = function (other) {
  55571. other.position.copyFrom(this.position);
  55572. if (this._initialDirection) {
  55573. if (other._initialDirection) {
  55574. other._initialDirection.copyFrom(this._initialDirection);
  55575. }
  55576. else {
  55577. other._initialDirection = this._initialDirection.clone();
  55578. }
  55579. }
  55580. else {
  55581. other._initialDirection = null;
  55582. }
  55583. other.direction.copyFrom(this.direction);
  55584. other.color.copyFrom(this.color);
  55585. other.colorStep.copyFrom(this.colorStep);
  55586. other.lifeTime = this.lifeTime;
  55587. other.age = this.age;
  55588. other._randomCellOffset = undefined;
  55589. other.size = this.size;
  55590. other.scale.copyFrom(this.scale);
  55591. other.angle = this.angle;
  55592. other.angularSpeed = this.angularSpeed;
  55593. other.particleSystem = this.particleSystem;
  55594. other.cellIndex = this.cellIndex;
  55595. if (this._currentColorGradient) {
  55596. other._currentColorGradient = this._currentColorGradient;
  55597. other._currentColor1.copyFrom(this._currentColor1);
  55598. other._currentColor2.copyFrom(this._currentColor2);
  55599. }
  55600. if (this._currentSizeGradient) {
  55601. other._currentSizeGradient = this._currentSizeGradient;
  55602. other._currentSize1 = this._currentSize1;
  55603. other._currentSize2 = this._currentSize2;
  55604. }
  55605. if (this._currentAngularSpeedGradient) {
  55606. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55607. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55608. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55609. }
  55610. if (this._currentVelocityGradient) {
  55611. other._currentVelocityGradient = this._currentVelocityGradient;
  55612. other._currentVelocity1 = this._currentVelocity1;
  55613. other._currentVelocity2 = this._currentVelocity2;
  55614. }
  55615. if (this._currentLimitVelocityGradient) {
  55616. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55617. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55618. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55619. }
  55620. if (this._currentDragGradient) {
  55621. other._currentDragGradient = this._currentDragGradient;
  55622. other._currentDrag1 = this._currentDrag1;
  55623. other._currentDrag2 = this._currentDrag2;
  55624. }
  55625. if (this.particleSystem.isAnimationSheetEnabled) {
  55626. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55627. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55628. }
  55629. };
  55630. return Particle;
  55631. }());
  55632. BABYLON.Particle = Particle;
  55633. })(BABYLON || (BABYLON = {}));
  55634. //# sourceMappingURL=babylon.particle.js.map
  55635. var BABYLON;
  55636. (function (BABYLON) {
  55637. /**
  55638. * This represents the base class for particle system in Babylon.
  55639. * 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.
  55640. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55641. * @example https://doc.babylonjs.com/babylon101/particles
  55642. */
  55643. var BaseParticleSystem = /** @class */ (function () {
  55644. /**
  55645. * Instantiates a particle system.
  55646. * 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.
  55647. * @param name The name of the particle system
  55648. */
  55649. function BaseParticleSystem(name) {
  55650. /**
  55651. * List of animations used by the particle system.
  55652. */
  55653. this.animations = [];
  55654. /**
  55655. * The rendering group used by the Particle system to chose when to render.
  55656. */
  55657. this.renderingGroupId = 0;
  55658. /**
  55659. * The emitter represents the Mesh or position we are attaching the particle system to.
  55660. */
  55661. this.emitter = null;
  55662. /**
  55663. * The maximum number of particles to emit per frame
  55664. */
  55665. this.emitRate = 10;
  55666. /**
  55667. * If you want to launch only a few particles at once, that can be done, as well.
  55668. */
  55669. this.manualEmitCount = -1;
  55670. /**
  55671. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55672. */
  55673. this.updateSpeed = 0.01;
  55674. /**
  55675. * The amount of time the particle system is running (depends of the overall update speed).
  55676. */
  55677. this.targetStopDuration = 0;
  55678. /**
  55679. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55680. */
  55681. this.disposeOnStop = false;
  55682. /**
  55683. * Minimum power of emitting particles.
  55684. */
  55685. this.minEmitPower = 1;
  55686. /**
  55687. * Maximum power of emitting particles.
  55688. */
  55689. this.maxEmitPower = 1;
  55690. /**
  55691. * Minimum life time of emitting particles.
  55692. */
  55693. this.minLifeTime = 1;
  55694. /**
  55695. * Maximum life time of emitting particles.
  55696. */
  55697. this.maxLifeTime = 1;
  55698. /**
  55699. * Minimum Size of emitting particles.
  55700. */
  55701. this.minSize = 1;
  55702. /**
  55703. * Maximum Size of emitting particles.
  55704. */
  55705. this.maxSize = 1;
  55706. /**
  55707. * Minimum scale of emitting particles on X axis.
  55708. */
  55709. this.minScaleX = 1;
  55710. /**
  55711. * Maximum scale of emitting particles on X axis.
  55712. */
  55713. this.maxScaleX = 1;
  55714. /**
  55715. * Minimum scale of emitting particles on Y axis.
  55716. */
  55717. this.minScaleY = 1;
  55718. /**
  55719. * Maximum scale of emitting particles on Y axis.
  55720. */
  55721. this.maxScaleY = 1;
  55722. /**
  55723. * Gets or sets the minimal initial rotation in radians.
  55724. */
  55725. this.minInitialRotation = 0;
  55726. /**
  55727. * Gets or sets the maximal initial rotation in radians.
  55728. */
  55729. this.maxInitialRotation = 0;
  55730. /**
  55731. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55732. */
  55733. this.minAngularSpeed = 0;
  55734. /**
  55735. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55736. */
  55737. this.maxAngularSpeed = 0;
  55738. /**
  55739. * The layer mask we are rendering the particles through.
  55740. */
  55741. this.layerMask = 0x0FFFFFFF;
  55742. /**
  55743. * This can help using your own shader to render the particle system.
  55744. * The according effect will be created
  55745. */
  55746. this.customShader = null;
  55747. /**
  55748. * By default particle system starts as soon as they are created. This prevents the
  55749. * automatic start to happen and let you decide when to start emitting particles.
  55750. */
  55751. this.preventAutoStart = false;
  55752. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55753. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55754. /**
  55755. * Callback triggered when the particle animation is ending.
  55756. */
  55757. this.onAnimationEnd = null;
  55758. /**
  55759. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55760. */
  55761. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55762. /**
  55763. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55764. * to override the particles.
  55765. */
  55766. this.forceDepthWrite = false;
  55767. /** 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 */
  55768. this.preWarmCycles = 0;
  55769. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55770. this.preWarmStepOffset = 1;
  55771. /**
  55772. * 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)
  55773. */
  55774. this.spriteCellChangeSpeed = 1;
  55775. /**
  55776. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55777. */
  55778. this.startSpriteCellID = 0;
  55779. /**
  55780. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55781. */
  55782. this.endSpriteCellID = 0;
  55783. /**
  55784. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55785. */
  55786. this.spriteCellWidth = 0;
  55787. /**
  55788. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55789. */
  55790. this.spriteCellHeight = 0;
  55791. /**
  55792. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  55793. */
  55794. this.spriteRandomStartCell = false;
  55795. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55796. this.translationPivot = new BABYLON.Vector2(0, 0);
  55797. /**
  55798. * You can use gravity if you want to give an orientation to your particles.
  55799. */
  55800. this.gravity = BABYLON.Vector3.Zero();
  55801. this._colorGradients = null;
  55802. this._sizeGradients = null;
  55803. this._lifeTimeGradients = null;
  55804. this._angularSpeedGradients = null;
  55805. this._velocityGradients = null;
  55806. this._limitVelocityGradients = null;
  55807. this._dragGradients = null;
  55808. this._emitRateGradients = null;
  55809. this._startSizeGradients = null;
  55810. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55811. this.limitVelocityDamping = 0.4;
  55812. /**
  55813. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55814. */
  55815. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55816. /**
  55817. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55818. */
  55819. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55820. /**
  55821. * Color the particle will have at the end of its lifetime
  55822. */
  55823. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55824. /**
  55825. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55826. */
  55827. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55828. /**
  55829. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55830. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55831. */
  55832. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55833. this._isBillboardBased = true;
  55834. /**
  55835. * Local cache of defines for image processing.
  55836. */
  55837. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55838. this.id = name;
  55839. this.name = name;
  55840. }
  55841. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55842. /**
  55843. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55844. */
  55845. get: function () {
  55846. return this._isAnimationSheetEnabled;
  55847. },
  55848. set: function (value) {
  55849. if (this._isAnimationSheetEnabled == value) {
  55850. return;
  55851. }
  55852. this._isAnimationSheetEnabled = value;
  55853. this._reset();
  55854. },
  55855. enumerable: true,
  55856. configurable: true
  55857. });
  55858. /**
  55859. * Get hosting scene
  55860. * @returns the scene
  55861. */
  55862. BaseParticleSystem.prototype.getScene = function () {
  55863. return this._scene;
  55864. };
  55865. /**
  55866. * Gets the current list of drag gradients.
  55867. * You must use addDragGradient and removeDragGradient to udpate this list
  55868. * @returns the list of drag gradients
  55869. */
  55870. BaseParticleSystem.prototype.getDragGradients = function () {
  55871. return this._dragGradients;
  55872. };
  55873. /**
  55874. * Gets the current list of limit velocity gradients.
  55875. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55876. * @returns the list of limit velocity gradients
  55877. */
  55878. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55879. return this._limitVelocityGradients;
  55880. };
  55881. /**
  55882. * Gets the current list of color gradients.
  55883. * You must use addColorGradient and removeColorGradient to udpate this list
  55884. * @returns the list of color gradients
  55885. */
  55886. BaseParticleSystem.prototype.getColorGradients = function () {
  55887. return this._colorGradients;
  55888. };
  55889. /**
  55890. * Gets the current list of size gradients.
  55891. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55892. * @returns the list of size gradients
  55893. */
  55894. BaseParticleSystem.prototype.getSizeGradients = function () {
  55895. return this._sizeGradients;
  55896. };
  55897. /**
  55898. * Gets the current list of life time gradients.
  55899. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55900. * @returns the list of life time gradients
  55901. */
  55902. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55903. return this._lifeTimeGradients;
  55904. };
  55905. /**
  55906. * Gets the current list of angular speed gradients.
  55907. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55908. * @returns the list of angular speed gradients
  55909. */
  55910. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55911. return this._angularSpeedGradients;
  55912. };
  55913. /**
  55914. * Gets the current list of velocity gradients.
  55915. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55916. * @returns the list of velocity gradients
  55917. */
  55918. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55919. return this._velocityGradients;
  55920. };
  55921. /**
  55922. * Gets the current list of start size gradients.
  55923. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  55924. * @returns the list of start size gradients
  55925. */
  55926. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  55927. return this._startSizeGradients;
  55928. };
  55929. /**
  55930. * Gets the current list of emit rate gradients.
  55931. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  55932. * @returns the list of emit rate gradients
  55933. */
  55934. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  55935. return this._emitRateGradients;
  55936. };
  55937. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55938. /**
  55939. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55940. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55941. */
  55942. get: function () {
  55943. if (this.particleEmitterType.direction1) {
  55944. return this.particleEmitterType.direction1;
  55945. }
  55946. return BABYLON.Vector3.Zero();
  55947. },
  55948. set: function (value) {
  55949. if (this.particleEmitterType.direction1) {
  55950. this.particleEmitterType.direction1 = value;
  55951. }
  55952. },
  55953. enumerable: true,
  55954. configurable: true
  55955. });
  55956. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55957. /**
  55958. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55959. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55960. */
  55961. get: function () {
  55962. if (this.particleEmitterType.direction2) {
  55963. return this.particleEmitterType.direction2;
  55964. }
  55965. return BABYLON.Vector3.Zero();
  55966. },
  55967. set: function (value) {
  55968. if (this.particleEmitterType.direction2) {
  55969. this.particleEmitterType.direction2 = value;
  55970. }
  55971. },
  55972. enumerable: true,
  55973. configurable: true
  55974. });
  55975. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55976. /**
  55977. * 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.
  55978. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55979. */
  55980. get: function () {
  55981. if (this.particleEmitterType.minEmitBox) {
  55982. return this.particleEmitterType.minEmitBox;
  55983. }
  55984. return BABYLON.Vector3.Zero();
  55985. },
  55986. set: function (value) {
  55987. if (this.particleEmitterType.minEmitBox) {
  55988. this.particleEmitterType.minEmitBox = value;
  55989. }
  55990. },
  55991. enumerable: true,
  55992. configurable: true
  55993. });
  55994. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55995. /**
  55996. * 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.
  55997. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55998. */
  55999. get: function () {
  56000. if (this.particleEmitterType.maxEmitBox) {
  56001. return this.particleEmitterType.maxEmitBox;
  56002. }
  56003. return BABYLON.Vector3.Zero();
  56004. },
  56005. set: function (value) {
  56006. if (this.particleEmitterType.maxEmitBox) {
  56007. this.particleEmitterType.maxEmitBox = value;
  56008. }
  56009. },
  56010. enumerable: true,
  56011. configurable: true
  56012. });
  56013. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  56014. /**
  56015. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  56016. */
  56017. get: function () {
  56018. return this._isBillboardBased;
  56019. },
  56020. set: function (value) {
  56021. if (this._isBillboardBased === value) {
  56022. return;
  56023. }
  56024. this._isBillboardBased = value;
  56025. this._reset();
  56026. },
  56027. enumerable: true,
  56028. configurable: true
  56029. });
  56030. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  56031. /**
  56032. * Gets the image processing configuration used either in this material.
  56033. */
  56034. get: function () {
  56035. return this._imageProcessingConfiguration;
  56036. },
  56037. /**
  56038. * Sets the Default image processing configuration used either in the this material.
  56039. *
  56040. * If sets to null, the scene one is in use.
  56041. */
  56042. set: function (value) {
  56043. this._attachImageProcessingConfiguration(value);
  56044. },
  56045. enumerable: true,
  56046. configurable: true
  56047. });
  56048. /**
  56049. * Attaches a new image processing configuration to the Standard Material.
  56050. * @param configuration
  56051. */
  56052. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  56053. if (configuration === this._imageProcessingConfiguration) {
  56054. return;
  56055. }
  56056. // Pick the scene configuration if needed.
  56057. if (!configuration) {
  56058. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  56059. }
  56060. else {
  56061. this._imageProcessingConfiguration = configuration;
  56062. }
  56063. };
  56064. /** @hidden */
  56065. BaseParticleSystem.prototype._reset = function () {
  56066. };
  56067. /**
  56068. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  56069. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56070. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56071. * @returns the emitter
  56072. */
  56073. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  56074. var particleEmitter = new BABYLON.PointParticleEmitter();
  56075. particleEmitter.direction1 = direction1;
  56076. particleEmitter.direction2 = direction2;
  56077. this.particleEmitterType = particleEmitter;
  56078. return particleEmitter;
  56079. };
  56080. /**
  56081. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  56082. * @param radius The radius of the hemisphere to emit from
  56083. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56084. * @returns the emitter
  56085. */
  56086. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  56087. if (radius === void 0) { radius = 1; }
  56088. if (radiusRange === void 0) { radiusRange = 1; }
  56089. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  56090. this.particleEmitterType = particleEmitter;
  56091. return particleEmitter;
  56092. };
  56093. /**
  56094. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  56095. * @param radius The radius of the sphere to emit from
  56096. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56097. * @returns the emitter
  56098. */
  56099. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56100. if (radius === void 0) { radius = 1; }
  56101. if (radiusRange === void 0) { radiusRange = 1; }
  56102. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56103. this.particleEmitterType = particleEmitter;
  56104. return particleEmitter;
  56105. };
  56106. /**
  56107. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  56108. * @param radius The radius of the sphere to emit from
  56109. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56110. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56111. * @returns the emitter
  56112. */
  56113. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56114. if (radius === void 0) { radius = 1; }
  56115. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56116. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56117. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56118. this.particleEmitterType = particleEmitter;
  56119. return particleEmitter;
  56120. };
  56121. /**
  56122. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  56123. * @param radius The radius of the emission cylinder
  56124. * @param height The height of the emission cylinder
  56125. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  56126. * @param directionRandomizer How much to randomize the particle direction [0-1]
  56127. * @returns the emitter
  56128. */
  56129. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  56130. if (radius === void 0) { radius = 1; }
  56131. if (height === void 0) { height = 1; }
  56132. if (radiusRange === void 0) { radiusRange = 1; }
  56133. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56134. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  56135. this.particleEmitterType = particleEmitter;
  56136. return particleEmitter;
  56137. };
  56138. /**
  56139. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  56140. * @param radius The radius of the cylinder to emit from
  56141. * @param height The height of the emission cylinder
  56142. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  56143. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  56144. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  56145. * @returns the emitter
  56146. */
  56147. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  56148. if (radius === void 0) { radius = 1; }
  56149. if (height === void 0) { height = 1; }
  56150. if (radiusRange === void 0) { radiusRange = 1; }
  56151. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56152. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56153. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  56154. this.particleEmitterType = particleEmitter;
  56155. return particleEmitter;
  56156. };
  56157. /**
  56158. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  56159. * @param radius The radius of the cone to emit from
  56160. * @param angle The base angle of the cone
  56161. * @returns the emitter
  56162. */
  56163. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56164. if (radius === void 0) { radius = 1; }
  56165. if (angle === void 0) { angle = Math.PI / 4; }
  56166. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56167. this.particleEmitterType = particleEmitter;
  56168. return particleEmitter;
  56169. };
  56170. /**
  56171. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56172. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56173. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56174. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56175. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56176. * @returns the emitter
  56177. */
  56178. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56179. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56180. this.particleEmitterType = particleEmitter;
  56181. this.direction1 = direction1;
  56182. this.direction2 = direction2;
  56183. this.minEmitBox = minEmitBox;
  56184. this.maxEmitBox = maxEmitBox;
  56185. return particleEmitter;
  56186. };
  56187. /**
  56188. * Source color is added to the destination color without alpha affecting the result.
  56189. */
  56190. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  56191. /**
  56192. * Blend current color and particle color using particle’s alpha.
  56193. */
  56194. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  56195. /**
  56196. * Add current color and particle color multiplied by particle’s alpha.
  56197. */
  56198. BaseParticleSystem.BLENDMODE_ADD = 2;
  56199. /**
  56200. * Multiply current color with particle color
  56201. */
  56202. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  56203. return BaseParticleSystem;
  56204. }());
  56205. BABYLON.BaseParticleSystem = BaseParticleSystem;
  56206. })(BABYLON || (BABYLON = {}));
  56207. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  56208. var BABYLON;
  56209. (function (BABYLON) {
  56210. /**
  56211. * This represents a particle system in Babylon.
  56212. * 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.
  56213. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56214. * @example https://doc.babylonjs.com/babylon101/particles
  56215. */
  56216. var ParticleSystem = /** @class */ (function (_super) {
  56217. __extends(ParticleSystem, _super);
  56218. /**
  56219. * Instantiates a particle system.
  56220. * 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.
  56221. * @param name The name of the particle system
  56222. * @param capacity The max number of particles alive at the same time
  56223. * @param scene The scene the particle system belongs to
  56224. * @param customEffect a custom effect used to change the way particles are rendered by default
  56225. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56226. * @param epsilon Offset used to render the particles
  56227. */
  56228. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56229. if (customEffect === void 0) { customEffect = null; }
  56230. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56231. if (epsilon === void 0) { epsilon = 0.01; }
  56232. var _this = _super.call(this, name) || this;
  56233. /**
  56234. * An event triggered when the system is disposed
  56235. */
  56236. _this.onDisposeObservable = new BABYLON.Observable();
  56237. _this._particles = new Array();
  56238. _this._stockParticles = new Array();
  56239. _this._newPartsExcess = 0;
  56240. _this._vertexBuffers = {};
  56241. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56242. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56243. _this._scaledDirection = BABYLON.Vector3.Zero();
  56244. _this._scaledGravity = BABYLON.Vector3.Zero();
  56245. _this._currentRenderId = -1;
  56246. _this._useInstancing = false;
  56247. _this._started = false;
  56248. _this._stopped = false;
  56249. _this._actualFrame = 0;
  56250. /** @hidden */
  56251. _this._currentEmitRate1 = 0;
  56252. /** @hidden */
  56253. _this._currentEmitRate2 = 0;
  56254. /** @hidden */
  56255. _this._currentStartSize1 = 0;
  56256. /** @hidden */
  56257. _this._currentStartSize2 = 0;
  56258. // start of sub system methods
  56259. /**
  56260. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56261. * Its lifetime will start back at 0.
  56262. */
  56263. _this.recycleParticle = function (particle) {
  56264. var lastParticle = _this._particles.pop();
  56265. if (lastParticle !== particle) {
  56266. lastParticle.copyTo(particle);
  56267. }
  56268. _this._stockParticles.push(lastParticle);
  56269. };
  56270. _this._createParticle = function () {
  56271. var particle;
  56272. if (_this._stockParticles.length !== 0) {
  56273. particle = _this._stockParticles.pop();
  56274. particle._reset();
  56275. }
  56276. else {
  56277. particle = new BABYLON.Particle(_this);
  56278. }
  56279. return particle;
  56280. };
  56281. _this._emitFromParticle = function (particle) {
  56282. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56283. return;
  56284. }
  56285. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56286. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56287. subSystem._rootParticleSystem = _this;
  56288. _this.activeSubSystems.push(subSystem);
  56289. subSystem.start();
  56290. };
  56291. _this._capacity = capacity;
  56292. _this._epsilon = epsilon;
  56293. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56294. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56295. // Setup the default processing configuration to the scene.
  56296. _this._attachImageProcessingConfiguration(null);
  56297. _this._customEffect = customEffect;
  56298. _this._scene.particleSystems.push(_this);
  56299. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56300. _this._createIndexBuffer();
  56301. _this._createVertexBuffers();
  56302. // Default emitter type
  56303. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56304. _this.updateFunction = function (particles) {
  56305. var noiseTextureData = null;
  56306. var noiseTextureSize = null;
  56307. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56308. noiseTextureData = (_this.noiseTexture.readPixels());
  56309. noiseTextureSize = _this.noiseTexture.getSize();
  56310. }
  56311. var _loop_1 = function () {
  56312. particle = particles[index];
  56313. particle.age += _this._scaledUpdateSpeed;
  56314. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56315. _this._emitFromParticle(particle);
  56316. _this.recycleParticle(particle);
  56317. index--;
  56318. return "continue";
  56319. }
  56320. else {
  56321. var ratio = particle.age / particle.lifeTime;
  56322. // Color
  56323. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56324. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56325. if (currentGradient !== particle._currentColorGradient) {
  56326. particle._currentColor1.copyFrom(particle._currentColor2);
  56327. nextGradient.getColorToRef(particle._currentColor2);
  56328. particle._currentColorGradient = currentGradient;
  56329. }
  56330. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56331. });
  56332. }
  56333. else {
  56334. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56335. particle.color.addInPlace(_this._scaledColorStep);
  56336. if (particle.color.a < 0) {
  56337. particle.color.a = 0;
  56338. }
  56339. }
  56340. // Angular speed
  56341. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56342. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56343. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56344. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56345. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56346. particle._currentAngularSpeedGradient = currentGradient;
  56347. }
  56348. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56349. });
  56350. }
  56351. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56352. // Direction
  56353. var directionScale_1 = _this._scaledUpdateSpeed;
  56354. /// Velocity
  56355. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56356. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56357. if (currentGradient !== particle._currentVelocityGradient) {
  56358. particle._currentVelocity1 = particle._currentVelocity2;
  56359. particle._currentVelocity2 = nextGradient.getFactor();
  56360. particle._currentVelocityGradient = currentGradient;
  56361. }
  56362. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56363. });
  56364. }
  56365. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56366. /// Limit velocity
  56367. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56368. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56369. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56370. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56371. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56372. particle._currentLimitVelocityGradient = currentGradient;
  56373. }
  56374. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56375. var currentVelocity = particle.direction.length();
  56376. if (currentVelocity > limitVelocity) {
  56377. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56378. }
  56379. });
  56380. }
  56381. /// Drag
  56382. if (_this._dragGradients && _this._dragGradients.length > 0) {
  56383. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  56384. if (currentGradient !== particle._currentDragGradient) {
  56385. particle._currentDrag1 = particle._currentDrag2;
  56386. particle._currentDrag2 = nextGradient.getFactor();
  56387. particle._currentDragGradient = currentGradient;
  56388. }
  56389. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  56390. _this._scaledDirection.scaleInPlace(1.0 - drag);
  56391. });
  56392. }
  56393. particle.position.addInPlace(_this._scaledDirection);
  56394. // Noise
  56395. if (noiseTextureData && noiseTextureSize) {
  56396. var localPosition = BABYLON.Tmp.Vector3[0];
  56397. var emitterPosition = BABYLON.Tmp.Vector3[1];
  56398. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  56399. particle.position.subtractToRef(emitterPosition, localPosition);
  56400. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56401. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56402. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56403. var force = BABYLON.Tmp.Vector3[0];
  56404. var scaledForce = BABYLON.Tmp.Vector3[1];
  56405. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56406. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56407. particle.direction.addInPlace(scaledForce);
  56408. }
  56409. // Gravity
  56410. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56411. particle.direction.addInPlace(_this._scaledGravity);
  56412. // Size
  56413. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56414. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56415. if (currentGradient !== particle._currentSizeGradient) {
  56416. particle._currentSize1 = particle._currentSize2;
  56417. particle._currentSize2 = nextGradient.getFactor();
  56418. particle._currentSizeGradient = currentGradient;
  56419. }
  56420. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56421. });
  56422. }
  56423. if (_this._isAnimationSheetEnabled) {
  56424. particle.updateCellIndex();
  56425. }
  56426. }
  56427. };
  56428. var particle;
  56429. for (var index = 0; index < particles.length; index++) {
  56430. _loop_1();
  56431. }
  56432. };
  56433. return _this;
  56434. }
  56435. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56436. /**
  56437. * Sets a callback that will be triggered when the system is disposed
  56438. */
  56439. set: function (callback) {
  56440. if (this._onDisposeObserver) {
  56441. this.onDisposeObservable.remove(this._onDisposeObserver);
  56442. }
  56443. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56444. },
  56445. enumerable: true,
  56446. configurable: true
  56447. });
  56448. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56449. //end of Sub-emitter
  56450. /**
  56451. * Gets the current list of active particles
  56452. */
  56453. get: function () {
  56454. return this._particles;
  56455. },
  56456. enumerable: true,
  56457. configurable: true
  56458. });
  56459. /**
  56460. * Returns the string "ParticleSystem"
  56461. * @returns a string containing the class name
  56462. */
  56463. ParticleSystem.prototype.getClassName = function () {
  56464. return "ParticleSystem";
  56465. };
  56466. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56467. var newGradient = new BABYLON.FactorGradient();
  56468. newGradient.gradient = gradient;
  56469. newGradient.factor1 = factor;
  56470. newGradient.factor2 = factor2;
  56471. factorGradients.push(newGradient);
  56472. factorGradients.sort(function (a, b) {
  56473. if (a.gradient < b.gradient) {
  56474. return -1;
  56475. }
  56476. else if (a.gradient > b.gradient) {
  56477. return 1;
  56478. }
  56479. return 0;
  56480. });
  56481. };
  56482. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56483. if (!factorGradients) {
  56484. return;
  56485. }
  56486. var index = 0;
  56487. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56488. var factorGradient = factorGradients_1[_i];
  56489. if (factorGradient.gradient === gradient) {
  56490. factorGradients.splice(index, 1);
  56491. break;
  56492. }
  56493. index++;
  56494. }
  56495. };
  56496. /**
  56497. * Adds a new life time gradient
  56498. * @param gradient defines the gradient to use (between 0 and 1)
  56499. * @param factor defines the life time factor to affect to the specified gradient
  56500. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56501. * @returns the current particle system
  56502. */
  56503. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56504. if (!this._lifeTimeGradients) {
  56505. this._lifeTimeGradients = [];
  56506. }
  56507. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56508. return this;
  56509. };
  56510. /**
  56511. * Remove a specific life time gradient
  56512. * @param gradient defines the gradient to remove
  56513. * @returns the current particle system
  56514. */
  56515. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56516. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56517. return this;
  56518. };
  56519. /**
  56520. * Adds a new size gradient
  56521. * @param gradient defines the gradient to use (between 0 and 1)
  56522. * @param factor defines the size factor to affect to the specified gradient
  56523. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56524. * @returns the current particle system
  56525. */
  56526. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56527. if (!this._sizeGradients) {
  56528. this._sizeGradients = [];
  56529. }
  56530. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56531. return this;
  56532. };
  56533. /**
  56534. * Remove a specific size gradient
  56535. * @param gradient defines the gradient to remove
  56536. * @returns the current particle system
  56537. */
  56538. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56539. this._removeFactorGradient(this._sizeGradients, gradient);
  56540. return this;
  56541. };
  56542. /**
  56543. * Adds a new angular speed gradient
  56544. * @param gradient defines the gradient to use (between 0 and 1)
  56545. * @param factor defines the angular speed to affect to the specified gradient
  56546. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56547. * @returns the current particle system
  56548. */
  56549. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56550. if (!this._angularSpeedGradients) {
  56551. this._angularSpeedGradients = [];
  56552. }
  56553. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56554. return this;
  56555. };
  56556. /**
  56557. * Remove a specific angular speed gradient
  56558. * @param gradient defines the gradient to remove
  56559. * @returns the current particle system
  56560. */
  56561. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56562. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56563. return this;
  56564. };
  56565. /**
  56566. * Adds a new velocity gradient
  56567. * @param gradient defines the gradient to use (between 0 and 1)
  56568. * @param factor defines the velocity to affect to the specified gradient
  56569. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56570. * @returns the current particle system
  56571. */
  56572. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56573. if (!this._velocityGradients) {
  56574. this._velocityGradients = [];
  56575. }
  56576. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56577. return this;
  56578. };
  56579. /**
  56580. * Remove a specific velocity gradient
  56581. * @param gradient defines the gradient to remove
  56582. * @returns the current particle system
  56583. */
  56584. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56585. this._removeFactorGradient(this._velocityGradients, gradient);
  56586. return this;
  56587. };
  56588. /**
  56589. * Adds a new limit velocity gradient
  56590. * @param gradient defines the gradient to use (between 0 and 1)
  56591. * @param factor defines the limit velocity value to affect to the specified gradient
  56592. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56593. * @returns the current particle system
  56594. */
  56595. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56596. if (!this._limitVelocityGradients) {
  56597. this._limitVelocityGradients = [];
  56598. }
  56599. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56600. return this;
  56601. };
  56602. /**
  56603. * Remove a specific limit velocity gradient
  56604. * @param gradient defines the gradient to remove
  56605. * @returns the current particle system
  56606. */
  56607. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56608. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56609. return this;
  56610. };
  56611. /**
  56612. * Adds a new drag gradient
  56613. * @param gradient defines the gradient to use (between 0 and 1)
  56614. * @param factor defines the drag value to affect to the specified gradient
  56615. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56616. * @returns the current particle system
  56617. */
  56618. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  56619. if (!this._dragGradients) {
  56620. this._dragGradients = [];
  56621. }
  56622. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  56623. return this;
  56624. };
  56625. /**
  56626. * Remove a specific drag gradient
  56627. * @param gradient defines the gradient to remove
  56628. * @returns the current particle system
  56629. */
  56630. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  56631. this._removeFactorGradient(this._dragGradients, gradient);
  56632. return this;
  56633. };
  56634. /**
  56635. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  56636. * @param gradient defines the gradient to use (between 0 and 1)
  56637. * @param factor defines the emit rate value to affect to the specified gradient
  56638. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56639. * @returns the current particle system
  56640. */
  56641. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  56642. if (!this._emitRateGradients) {
  56643. this._emitRateGradients = [];
  56644. }
  56645. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  56646. if (!this._currentEmitRateGradient) {
  56647. this._currentEmitRateGradient = this._emitRateGradients[0];
  56648. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  56649. this._currentEmitRate2 = this._currentEmitRate1;
  56650. }
  56651. if (this._emitRateGradients.length === 2) {
  56652. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  56653. }
  56654. return this;
  56655. };
  56656. /**
  56657. * Remove a specific emit rate gradient
  56658. * @param gradient defines the gradient to remove
  56659. * @returns the current particle system
  56660. */
  56661. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  56662. this._removeFactorGradient(this._emitRateGradients, gradient);
  56663. return this;
  56664. };
  56665. /**
  56666. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  56667. * @param gradient defines the gradient to use (between 0 and 1)
  56668. * @param factor defines the start size value to affect to the specified gradient
  56669. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56670. * @returns the current particle system
  56671. */
  56672. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  56673. if (!this._startSizeGradients) {
  56674. this._startSizeGradients = [];
  56675. }
  56676. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  56677. if (!this._currentStartSizeGradient) {
  56678. this._currentStartSizeGradient = this._startSizeGradients[0];
  56679. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  56680. this._currentStartSize2 = this._currentStartSize1;
  56681. }
  56682. if (this._startSizeGradients.length === 2) {
  56683. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  56684. }
  56685. return this;
  56686. };
  56687. /**
  56688. * Remove a specific start size gradient
  56689. * @param gradient defines the gradient to remove
  56690. * @returns the current particle system
  56691. */
  56692. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  56693. this._removeFactorGradient(this._emitRateGradients, gradient);
  56694. return this;
  56695. };
  56696. /**
  56697. * Adds a new color gradient
  56698. * @param gradient defines the gradient to use (between 0 and 1)
  56699. * @param color defines the color to affect to the specified gradient
  56700. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56701. */
  56702. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56703. if (!this._colorGradients) {
  56704. this._colorGradients = [];
  56705. }
  56706. var colorGradient = new BABYLON.ColorGradient();
  56707. colorGradient.gradient = gradient;
  56708. colorGradient.color1 = color;
  56709. colorGradient.color2 = color2;
  56710. this._colorGradients.push(colorGradient);
  56711. this._colorGradients.sort(function (a, b) {
  56712. if (a.gradient < b.gradient) {
  56713. return -1;
  56714. }
  56715. else if (a.gradient > b.gradient) {
  56716. return 1;
  56717. }
  56718. return 0;
  56719. });
  56720. return this;
  56721. };
  56722. /**
  56723. * Remove a specific color gradient
  56724. * @param gradient defines the gradient to remove
  56725. */
  56726. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56727. if (!this._colorGradients) {
  56728. return this;
  56729. }
  56730. var index = 0;
  56731. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56732. var colorGradient = _a[_i];
  56733. if (colorGradient.gradient === gradient) {
  56734. this._colorGradients.splice(index, 1);
  56735. break;
  56736. }
  56737. index++;
  56738. }
  56739. return this;
  56740. };
  56741. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56742. u = Math.abs(u) * 0.5 + 0.5;
  56743. v = Math.abs(v) * 0.5 + 0.5;
  56744. var wrappedU = ((u * width) % width) | 0;
  56745. var wrappedV = ((v * height) % height) | 0;
  56746. var position = (wrappedU + wrappedV * width) * 4;
  56747. return pixels[position] / 255;
  56748. };
  56749. ParticleSystem.prototype._reset = function () {
  56750. this._resetEffect();
  56751. };
  56752. ParticleSystem.prototype._resetEffect = function () {
  56753. if (this._vertexBuffer) {
  56754. this._vertexBuffer.dispose();
  56755. this._vertexBuffer = null;
  56756. }
  56757. if (this._spriteBuffer) {
  56758. this._spriteBuffer.dispose();
  56759. this._spriteBuffer = null;
  56760. }
  56761. this._createVertexBuffers();
  56762. };
  56763. ParticleSystem.prototype._createVertexBuffers = function () {
  56764. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56765. if (this._isAnimationSheetEnabled) {
  56766. this._vertexBufferSize += 1;
  56767. }
  56768. if (!this._isBillboardBased) {
  56769. this._vertexBufferSize += 3;
  56770. }
  56771. var engine = this._scene.getEngine();
  56772. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56773. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56774. var dataOffset = 0;
  56775. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56776. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56777. dataOffset += 3;
  56778. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56779. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56780. dataOffset += 4;
  56781. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56782. this._vertexBuffers["angle"] = options;
  56783. dataOffset += 1;
  56784. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56785. this._vertexBuffers["size"] = size;
  56786. dataOffset += 2;
  56787. if (this._isAnimationSheetEnabled) {
  56788. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56789. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56790. dataOffset += 1;
  56791. }
  56792. if (!this._isBillboardBased) {
  56793. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56794. this._vertexBuffers["direction"] = directionBuffer;
  56795. dataOffset += 3;
  56796. }
  56797. var offsets;
  56798. if (this._useInstancing) {
  56799. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56800. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56801. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56802. }
  56803. else {
  56804. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56805. dataOffset += 2;
  56806. }
  56807. this._vertexBuffers["offset"] = offsets;
  56808. };
  56809. ParticleSystem.prototype._createIndexBuffer = function () {
  56810. if (this._useInstancing) {
  56811. return;
  56812. }
  56813. var indices = [];
  56814. var index = 0;
  56815. for (var count = 0; count < this._capacity; count++) {
  56816. indices.push(index);
  56817. indices.push(index + 1);
  56818. indices.push(index + 2);
  56819. indices.push(index);
  56820. indices.push(index + 2);
  56821. indices.push(index + 3);
  56822. index += 4;
  56823. }
  56824. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56825. };
  56826. /**
  56827. * Gets the maximum number of particles active at the same time.
  56828. * @returns The max number of active particles.
  56829. */
  56830. ParticleSystem.prototype.getCapacity = function () {
  56831. return this._capacity;
  56832. };
  56833. /**
  56834. * Gets whether there are still active particles in the system.
  56835. * @returns True if it is alive, otherwise false.
  56836. */
  56837. ParticleSystem.prototype.isAlive = function () {
  56838. return this._alive;
  56839. };
  56840. /**
  56841. * Gets if the system has been started. (Note: this will still be true after stop is called)
  56842. * @returns True if it has been started, otherwise false.
  56843. */
  56844. ParticleSystem.prototype.isStarted = function () {
  56845. return this._started;
  56846. };
  56847. /**
  56848. * Starts the particle system and begins to emit
  56849. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  56850. */
  56851. ParticleSystem.prototype.start = function (delay) {
  56852. var _this = this;
  56853. if (delay === void 0) { delay = 0; }
  56854. if (delay) {
  56855. setTimeout(function () {
  56856. _this.start(0);
  56857. }, delay);
  56858. return;
  56859. }
  56860. this._started = true;
  56861. this._stopped = false;
  56862. this._actualFrame = 0;
  56863. if (this.subEmitters && this.subEmitters.length != 0) {
  56864. this.activeSubSystems = new Array();
  56865. }
  56866. if (this.preWarmCycles) {
  56867. for (var index = 0; index < this.preWarmCycles; index++) {
  56868. this.animate(true);
  56869. }
  56870. }
  56871. };
  56872. /**
  56873. * Stops the particle system.
  56874. * @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.
  56875. */
  56876. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56877. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56878. this._stopped = true;
  56879. if (stopSubEmitters) {
  56880. this._stopSubEmitters();
  56881. }
  56882. };
  56883. // animation sheet
  56884. /**
  56885. * Remove all active particles
  56886. */
  56887. ParticleSystem.prototype.reset = function () {
  56888. this._stockParticles = [];
  56889. this._particles = [];
  56890. };
  56891. /**
  56892. * @hidden (for internal use only)
  56893. */
  56894. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56895. var offset = index * this._vertexBufferSize;
  56896. this._vertexData[offset++] = particle.position.x;
  56897. this._vertexData[offset++] = particle.position.y;
  56898. this._vertexData[offset++] = particle.position.z;
  56899. this._vertexData[offset++] = particle.color.r;
  56900. this._vertexData[offset++] = particle.color.g;
  56901. this._vertexData[offset++] = particle.color.b;
  56902. this._vertexData[offset++] = particle.color.a;
  56903. this._vertexData[offset++] = particle.angle;
  56904. this._vertexData[offset++] = particle.scale.x * particle.size;
  56905. this._vertexData[offset++] = particle.scale.y * particle.size;
  56906. if (this._isAnimationSheetEnabled) {
  56907. this._vertexData[offset++] = particle.cellIndex;
  56908. }
  56909. if (!this._isBillboardBased) {
  56910. if (particle._initialDirection) {
  56911. this._vertexData[offset++] = particle._initialDirection.x;
  56912. this._vertexData[offset++] = particle._initialDirection.y;
  56913. this._vertexData[offset++] = particle._initialDirection.z;
  56914. }
  56915. else {
  56916. this._vertexData[offset++] = particle.direction.x;
  56917. this._vertexData[offset++] = particle.direction.y;
  56918. this._vertexData[offset++] = particle.direction.z;
  56919. }
  56920. }
  56921. if (!this._useInstancing) {
  56922. if (this._isAnimationSheetEnabled) {
  56923. if (offsetX === 0)
  56924. offsetX = this._epsilon;
  56925. else if (offsetX === 1)
  56926. offsetX = 1 - this._epsilon;
  56927. if (offsetY === 0)
  56928. offsetY = this._epsilon;
  56929. else if (offsetY === 1)
  56930. offsetY = 1 - this._epsilon;
  56931. }
  56932. this._vertexData[offset++] = offsetX;
  56933. this._vertexData[offset++] = offsetY;
  56934. }
  56935. };
  56936. ParticleSystem.prototype._stopSubEmitters = function () {
  56937. if (!this.activeSubSystems) {
  56938. return;
  56939. }
  56940. this.activeSubSystems.forEach(function (subSystem) {
  56941. subSystem.stop(true);
  56942. });
  56943. this.activeSubSystems = new Array();
  56944. };
  56945. ParticleSystem.prototype._removeFromRoot = function () {
  56946. if (!this._rootParticleSystem) {
  56947. return;
  56948. }
  56949. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56950. if (index !== -1) {
  56951. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56952. }
  56953. };
  56954. // End of sub system methods
  56955. ParticleSystem.prototype._update = function (newParticles) {
  56956. var _this = this;
  56957. // Update current
  56958. this._alive = this._particles.length > 0;
  56959. if (this.emitter.position) {
  56960. var emitterMesh = this.emitter;
  56961. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  56962. }
  56963. else {
  56964. var emitterPosition = this.emitter;
  56965. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56966. }
  56967. this.updateFunction(this._particles);
  56968. // Add new ones
  56969. var particle;
  56970. var _loop_2 = function () {
  56971. if (this_1._particles.length === this_1._capacity) {
  56972. return "break";
  56973. }
  56974. particle = this_1._createParticle();
  56975. this_1._particles.push(particle);
  56976. // Emitter
  56977. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  56978. if (this_1.startPositionFunction) {
  56979. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56980. }
  56981. else {
  56982. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56983. }
  56984. if (this_1.startDirectionFunction) {
  56985. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56986. }
  56987. else {
  56988. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56989. }
  56990. if (emitPower === 0) {
  56991. if (!particle._initialDirection) {
  56992. particle._initialDirection = particle.direction.clone();
  56993. }
  56994. else {
  56995. particle._initialDirection.copyFrom(particle.direction);
  56996. }
  56997. }
  56998. else {
  56999. particle._initialDirection = null;
  57000. }
  57001. particle.direction.scaleInPlace(emitPower);
  57002. // Life time
  57003. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  57004. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  57005. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  57006. var factorGradient1 = currentGradient;
  57007. var factorGradient2 = nextGradient;
  57008. var lifeTime1 = factorGradient1.getFactor();
  57009. var lifeTime2 = factorGradient2.getFactor();
  57010. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  57011. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  57012. });
  57013. }
  57014. else {
  57015. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  57016. }
  57017. // Size
  57018. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  57019. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  57020. }
  57021. else {
  57022. particle._currentSizeGradient = this_1._sizeGradients[0];
  57023. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  57024. particle.size = particle._currentSize1;
  57025. if (this_1._sizeGradients.length > 1) {
  57026. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  57027. }
  57028. else {
  57029. particle._currentSize2 = particle._currentSize1;
  57030. }
  57031. }
  57032. // Size and scale
  57033. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  57034. // Adjust scale by start size
  57035. if (this_1._startSizeGradients && this_1._startSizeGradients[0]) {
  57036. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  57037. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  57038. if (currentGradient !== _this._currentStartSizeGradient) {
  57039. _this._currentStartSize1 = _this._currentStartSize2;
  57040. _this._currentStartSize2 = nextGradient.getFactor();
  57041. _this._currentStartSizeGradient = currentGradient;
  57042. }
  57043. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  57044. particle.scale.scaleInPlace(value);
  57045. });
  57046. }
  57047. // Angle
  57048. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  57049. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  57050. }
  57051. else {
  57052. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  57053. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  57054. particle._currentAngularSpeed1 = particle.angularSpeed;
  57055. if (this_1._angularSpeedGradients.length > 1) {
  57056. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  57057. }
  57058. else {
  57059. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  57060. }
  57061. }
  57062. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  57063. // Velocity
  57064. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  57065. particle._currentVelocityGradient = this_1._velocityGradients[0];
  57066. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  57067. if (this_1._velocityGradients.length > 1) {
  57068. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  57069. }
  57070. else {
  57071. particle._currentVelocity2 = particle._currentVelocity1;
  57072. }
  57073. }
  57074. // Limit velocity
  57075. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  57076. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  57077. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  57078. if (this_1._limitVelocityGradients.length > 1) {
  57079. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  57080. }
  57081. else {
  57082. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  57083. }
  57084. }
  57085. // Drag
  57086. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  57087. particle._currentDragGradient = this_1._dragGradients[0];
  57088. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  57089. if (this_1._dragGradients.length > 1) {
  57090. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  57091. }
  57092. else {
  57093. particle._currentDrag2 = particle._currentDrag1;
  57094. }
  57095. }
  57096. // Color
  57097. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  57098. step = BABYLON.Scalar.RandomRange(0, 1.0);
  57099. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  57100. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  57101. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  57102. }
  57103. else {
  57104. particle._currentColorGradient = this_1._colorGradients[0];
  57105. particle._currentColorGradient.getColorToRef(particle.color);
  57106. particle._currentColor1.copyFrom(particle.color);
  57107. if (this_1._colorGradients.length > 1) {
  57108. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  57109. }
  57110. else {
  57111. particle._currentColor2.copyFrom(particle.color);
  57112. }
  57113. }
  57114. // Sheet
  57115. if (this_1._isAnimationSheetEnabled) {
  57116. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  57117. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  57118. }
  57119. };
  57120. var this_1 = this, step;
  57121. for (var index = 0; index < newParticles; index++) {
  57122. var state_1 = _loop_2();
  57123. if (state_1 === "break")
  57124. break;
  57125. }
  57126. };
  57127. /** @hidden */
  57128. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  57129. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57130. if (isBillboardBased === void 0) { isBillboardBased = false; }
  57131. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  57132. if (isAnimationSheetEnabled) {
  57133. attributeNamesOrOptions.push("cellIndex");
  57134. }
  57135. if (!isBillboardBased) {
  57136. attributeNamesOrOptions.push("direction");
  57137. }
  57138. return attributeNamesOrOptions;
  57139. };
  57140. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  57141. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57142. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  57143. if (isAnimationSheetEnabled) {
  57144. effectCreationOption.push("particlesInfos");
  57145. }
  57146. return effectCreationOption;
  57147. };
  57148. ParticleSystem.prototype._getEffect = function () {
  57149. if (this._customEffect) {
  57150. return this._customEffect;
  57151. }
  57152. ;
  57153. var defines = [];
  57154. if (this._scene.clipPlane) {
  57155. defines.push("#define CLIPPLANE");
  57156. }
  57157. if (this._scene.clipPlane2) {
  57158. defines.push("#define CLIPPLANE2");
  57159. }
  57160. if (this._scene.clipPlane3) {
  57161. defines.push("#define CLIPPLANE3");
  57162. }
  57163. if (this._scene.clipPlane4) {
  57164. defines.push("#define CLIPPLANE4");
  57165. }
  57166. if (this._isAnimationSheetEnabled) {
  57167. defines.push("#define ANIMATESHEET");
  57168. }
  57169. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  57170. defines.push("#define BLENDMULTIPLYMODE");
  57171. }
  57172. if (this._isBillboardBased) {
  57173. defines.push("#define BILLBOARD");
  57174. switch (this.billboardMode) {
  57175. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57176. defines.push("#define BILLBOARDY");
  57177. break;
  57178. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57179. default:
  57180. break;
  57181. }
  57182. }
  57183. if (this._imageProcessingConfiguration) {
  57184. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  57185. defines.push(this._imageProcessingConfigurationDefines.toString());
  57186. }
  57187. // Effect
  57188. var join = defines.join("\n");
  57189. if (this._cachedDefines !== join) {
  57190. this._cachedDefines = join;
  57191. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  57192. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  57193. var samplers = ["diffuseSampler"];
  57194. if (BABYLON.ImageProcessingConfiguration) {
  57195. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  57196. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  57197. }
  57198. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  57199. }
  57200. return this._effect;
  57201. };
  57202. /**
  57203. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57204. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  57205. */
  57206. ParticleSystem.prototype.animate = function (preWarmOnly) {
  57207. var _this = this;
  57208. if (preWarmOnly === void 0) { preWarmOnly = false; }
  57209. if (!this._started)
  57210. return;
  57211. if (!preWarmOnly) {
  57212. var effect = this._getEffect();
  57213. // Check
  57214. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  57215. return;
  57216. if (this._currentRenderId === this._scene.getRenderId()) {
  57217. return;
  57218. }
  57219. this._currentRenderId = this._scene.getRenderId();
  57220. }
  57221. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57222. // Determine the number of particles we need to create
  57223. var newParticles;
  57224. if (this.manualEmitCount > -1) {
  57225. newParticles = this.manualEmitCount;
  57226. this._newPartsExcess = 0;
  57227. this.manualEmitCount = 0;
  57228. }
  57229. else {
  57230. var rate_1 = this.emitRate;
  57231. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  57232. var ratio = this._actualFrame / this.targetStopDuration;
  57233. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  57234. if (currentGradient !== _this._currentEmitRateGradient) {
  57235. _this._currentEmitRate1 = _this._currentEmitRate2;
  57236. _this._currentEmitRate2 = nextGradient.getFactor();
  57237. _this._currentEmitRateGradient = currentGradient;
  57238. }
  57239. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  57240. });
  57241. }
  57242. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  57243. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  57244. }
  57245. if (this._newPartsExcess > 1.0) {
  57246. newParticles += this._newPartsExcess >> 0;
  57247. this._newPartsExcess -= this._newPartsExcess >> 0;
  57248. }
  57249. this._alive = false;
  57250. if (!this._stopped) {
  57251. this._actualFrame += this._scaledUpdateSpeed;
  57252. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  57253. this.stop();
  57254. }
  57255. else {
  57256. newParticles = 0;
  57257. }
  57258. this._update(newParticles);
  57259. // Stopped?
  57260. if (this._stopped) {
  57261. if (!this._alive) {
  57262. this._started = false;
  57263. if (this.onAnimationEnd) {
  57264. this.onAnimationEnd();
  57265. }
  57266. if (this.disposeOnStop) {
  57267. this._scene._toBeDisposed.push(this);
  57268. }
  57269. }
  57270. }
  57271. if (!preWarmOnly) {
  57272. // Update VBO
  57273. var offset = 0;
  57274. for (var index = 0; index < this._particles.length; index++) {
  57275. var particle = this._particles[index];
  57276. this._appendParticleVertices(offset, particle);
  57277. offset += this._useInstancing ? 1 : 4;
  57278. }
  57279. if (this._vertexBuffer) {
  57280. this._vertexBuffer.update(this._vertexData);
  57281. }
  57282. }
  57283. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57284. this.stop();
  57285. }
  57286. };
  57287. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57288. this._appendParticleVertex(offset++, particle, 0, 0);
  57289. if (!this._useInstancing) {
  57290. this._appendParticleVertex(offset++, particle, 1, 0);
  57291. this._appendParticleVertex(offset++, particle, 1, 1);
  57292. this._appendParticleVertex(offset++, particle, 0, 1);
  57293. }
  57294. };
  57295. /**
  57296. * Rebuilds the particle system.
  57297. */
  57298. ParticleSystem.prototype.rebuild = function () {
  57299. this._createIndexBuffer();
  57300. if (this._vertexBuffer) {
  57301. this._vertexBuffer._rebuild();
  57302. }
  57303. };
  57304. /**
  57305. * Is this system ready to be used/rendered
  57306. * @return true if the system is ready
  57307. */
  57308. ParticleSystem.prototype.isReady = function () {
  57309. var effect = this._getEffect();
  57310. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57311. return false;
  57312. }
  57313. return true;
  57314. };
  57315. /**
  57316. * Renders the particle system in its current state.
  57317. * @returns the current number of particles
  57318. */
  57319. ParticleSystem.prototype.render = function () {
  57320. var effect = this._getEffect();
  57321. // Check
  57322. if (!this.isReady() || !this._particles.length) {
  57323. return 0;
  57324. }
  57325. var engine = this._scene.getEngine();
  57326. // Render
  57327. engine.enableEffect(effect);
  57328. engine.setState(false);
  57329. var viewMatrix = this._scene.getViewMatrix();
  57330. effect.setTexture("diffuseSampler", this.particleTexture);
  57331. effect.setMatrix("view", viewMatrix);
  57332. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57333. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57334. var baseSize = this.particleTexture.getBaseSize();
  57335. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57336. }
  57337. effect.setVector2("translationPivot", this.translationPivot);
  57338. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57339. if (this._isBillboardBased) {
  57340. var camera = this._scene.activeCamera;
  57341. effect.setVector3("eyePosition", camera.globalPosition);
  57342. }
  57343. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57344. var invView = viewMatrix.clone();
  57345. invView.invert();
  57346. effect.setMatrix("invView", invView);
  57347. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57348. }
  57349. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57350. // image processing
  57351. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57352. this._imageProcessingConfiguration.bind(effect);
  57353. }
  57354. // Draw order
  57355. switch (this.blendMode) {
  57356. case ParticleSystem.BLENDMODE_ADD:
  57357. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57358. break;
  57359. case ParticleSystem.BLENDMODE_ONEONE:
  57360. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57361. break;
  57362. case ParticleSystem.BLENDMODE_STANDARD:
  57363. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57364. break;
  57365. case ParticleSystem.BLENDMODE_MULTIPLY:
  57366. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  57367. break;
  57368. }
  57369. if (this.forceDepthWrite) {
  57370. engine.setDepthWrite(true);
  57371. }
  57372. if (this._useInstancing) {
  57373. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57374. engine.unbindInstanceAttributes();
  57375. }
  57376. else {
  57377. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57378. }
  57379. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57380. return this._particles.length;
  57381. };
  57382. /**
  57383. * Disposes the particle system and free the associated resources
  57384. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57385. */
  57386. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57387. if (disposeTexture === void 0) { disposeTexture = true; }
  57388. if (this._vertexBuffer) {
  57389. this._vertexBuffer.dispose();
  57390. this._vertexBuffer = null;
  57391. }
  57392. if (this._spriteBuffer) {
  57393. this._spriteBuffer.dispose();
  57394. this._spriteBuffer = null;
  57395. }
  57396. if (this._indexBuffer) {
  57397. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57398. this._indexBuffer = null;
  57399. }
  57400. if (disposeTexture && this.particleTexture) {
  57401. this.particleTexture.dispose();
  57402. this.particleTexture = null;
  57403. }
  57404. if (disposeTexture && this.noiseTexture) {
  57405. this.noiseTexture.dispose();
  57406. this.noiseTexture = null;
  57407. }
  57408. this._removeFromRoot();
  57409. // Remove from scene
  57410. var index = this._scene.particleSystems.indexOf(this);
  57411. if (index > -1) {
  57412. this._scene.particleSystems.splice(index, 1);
  57413. }
  57414. // Callback
  57415. this.onDisposeObservable.notifyObservers(this);
  57416. this.onDisposeObservable.clear();
  57417. };
  57418. // Clone
  57419. /**
  57420. * Clones the particle system.
  57421. * @param name The name of the cloned object
  57422. * @param newEmitter The new emitter to use
  57423. * @returns the cloned particle system
  57424. */
  57425. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57426. var custom = null;
  57427. var program = null;
  57428. if (this.customShader != null) {
  57429. program = this.customShader;
  57430. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57431. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57432. }
  57433. else if (this._customEffect) {
  57434. custom = this._customEffect;
  57435. }
  57436. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57437. result.customShader = program;
  57438. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57439. if (newEmitter === undefined) {
  57440. newEmitter = this.emitter;
  57441. }
  57442. result.emitter = newEmitter;
  57443. if (this.particleTexture) {
  57444. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57445. }
  57446. if (!this.preventAutoStart) {
  57447. result.start();
  57448. }
  57449. return result;
  57450. };
  57451. /**
  57452. * Serializes the particle system to a JSON object.
  57453. * @returns the JSON object
  57454. */
  57455. ParticleSystem.prototype.serialize = function () {
  57456. var serializationObject = {};
  57457. ParticleSystem._Serialize(serializationObject, this);
  57458. serializationObject.textureMask = this.textureMask.asArray();
  57459. serializationObject.customShader = this.customShader;
  57460. serializationObject.preventAutoStart = this.preventAutoStart;
  57461. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57462. return serializationObject;
  57463. };
  57464. /** @hidden */
  57465. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57466. serializationObject.name = particleSystem.name;
  57467. serializationObject.id = particleSystem.id;
  57468. serializationObject.capacity = particleSystem.getCapacity();
  57469. // Emitter
  57470. if (particleSystem.emitter.position) {
  57471. var emitterMesh = particleSystem.emitter;
  57472. serializationObject.emitterId = emitterMesh.id;
  57473. }
  57474. else {
  57475. var emitterPosition = particleSystem.emitter;
  57476. serializationObject.emitter = emitterPosition.asArray();
  57477. }
  57478. // Emitter
  57479. if (particleSystem.particleEmitterType) {
  57480. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57481. }
  57482. if (particleSystem.particleTexture) {
  57483. serializationObject.textureName = particleSystem.particleTexture.name;
  57484. }
  57485. // Animations
  57486. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57487. // Particle system
  57488. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57489. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57490. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57491. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57492. serializationObject.minSize = particleSystem.minSize;
  57493. serializationObject.maxSize = particleSystem.maxSize;
  57494. serializationObject.minScaleX = particleSystem.minScaleX;
  57495. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57496. serializationObject.minScaleY = particleSystem.minScaleY;
  57497. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57498. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57499. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57500. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57501. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57502. serializationObject.emitRate = particleSystem.emitRate;
  57503. serializationObject.gravity = particleSystem.gravity.asArray();
  57504. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57505. serializationObject.color1 = particleSystem.color1.asArray();
  57506. serializationObject.color2 = particleSystem.color2.asArray();
  57507. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57508. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57509. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57510. serializationObject.blendMode = particleSystem.blendMode;
  57511. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57512. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57513. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57514. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57515. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57516. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57517. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57518. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57519. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57520. var colorGradients = particleSystem.getColorGradients();
  57521. if (colorGradients) {
  57522. serializationObject.colorGradients = [];
  57523. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57524. var colorGradient = colorGradients_1[_i];
  57525. var serializedGradient = {
  57526. gradient: colorGradient.gradient,
  57527. color1: colorGradient.color1.asArray()
  57528. };
  57529. if (colorGradient.color2) {
  57530. serializedGradient.color2 = colorGradient.color2.asArray();
  57531. }
  57532. serializationObject.colorGradients.push(serializedGradient);
  57533. }
  57534. }
  57535. var sizeGradients = particleSystem.getSizeGradients();
  57536. if (sizeGradients) {
  57537. serializationObject.sizeGradients = [];
  57538. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  57539. var sizeGradient = sizeGradients_1[_a];
  57540. var serializedGradient = {
  57541. gradient: sizeGradient.gradient,
  57542. factor1: sizeGradient.factor1
  57543. };
  57544. if (sizeGradient.factor2 !== undefined) {
  57545. serializedGradient.factor2 = sizeGradient.factor2;
  57546. }
  57547. serializationObject.sizeGradients.push(serializedGradient);
  57548. }
  57549. }
  57550. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57551. if (angularSpeedGradients) {
  57552. serializationObject.angularSpeedGradients = [];
  57553. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  57554. var angularSpeedGradient = angularSpeedGradients_1[_b];
  57555. var serializedGradient = {
  57556. gradient: angularSpeedGradient.gradient,
  57557. factor1: angularSpeedGradient.factor1
  57558. };
  57559. if (angularSpeedGradient.factor2 !== undefined) {
  57560. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57561. }
  57562. serializationObject.angularSpeedGradients.push(serializedGradient);
  57563. }
  57564. }
  57565. var velocityGradients = particleSystem.getVelocityGradients();
  57566. if (velocityGradients) {
  57567. serializationObject.velocityGradients = [];
  57568. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  57569. var velocityGradient = velocityGradients_1[_c];
  57570. var serializedGradient = {
  57571. gradient: velocityGradient.gradient,
  57572. factor1: velocityGradient.factor1
  57573. };
  57574. if (velocityGradient.factor2 !== undefined) {
  57575. serializedGradient.factor2 = velocityGradient.factor2;
  57576. }
  57577. serializationObject.velocityGradients.push(serializedGradient);
  57578. }
  57579. }
  57580. var dragGradients = particleSystem.getDragGradients();
  57581. if (dragGradients) {
  57582. serializationObject.dragyGradients = [];
  57583. for (var _d = 0, dragGradients_1 = dragGradients; _d < dragGradients_1.length; _d++) {
  57584. var dragGradient = dragGradients_1[_d];
  57585. var serializedGradient = {
  57586. gradient: dragGradient.gradient,
  57587. factor1: dragGradient.factor1
  57588. };
  57589. if (dragGradient.factor2 !== undefined) {
  57590. serializedGradient.factor2 = dragGradient.factor2;
  57591. }
  57592. serializationObject.dragGradients.push(serializedGradient);
  57593. }
  57594. }
  57595. var emitRateGradients = particleSystem.getEmitRateGradients();
  57596. if (emitRateGradients) {
  57597. serializationObject.emitRateGradients = [];
  57598. for (var _e = 0, emitRateGradients_1 = emitRateGradients; _e < emitRateGradients_1.length; _e++) {
  57599. var emitRateGradient = emitRateGradients_1[_e];
  57600. var serializedGradient = {
  57601. gradient: emitRateGradient.gradient,
  57602. factor1: emitRateGradient.factor1
  57603. };
  57604. if (emitRateGradient.factor2 !== undefined) {
  57605. serializedGradient.factor2 = emitRateGradient.factor2;
  57606. }
  57607. serializationObject.emitRateGradients.push(serializedGradient);
  57608. }
  57609. }
  57610. var startSizeGradients = particleSystem.getStartSizeGradients();
  57611. if (startSizeGradients) {
  57612. serializationObject.startSizeGradients = [];
  57613. for (var _f = 0, startSizeGradients_1 = startSizeGradients; _f < startSizeGradients_1.length; _f++) {
  57614. var startSizeGradient = startSizeGradients_1[_f];
  57615. var serializedGradient = {
  57616. gradient: startSizeGradient.gradient,
  57617. factor1: startSizeGradient.factor1
  57618. };
  57619. if (startSizeGradient.factor2 !== undefined) {
  57620. serializedGradient.factor2 = startSizeGradient.factor2;
  57621. }
  57622. serializationObject.startSizeGradients.push(serializedGradient);
  57623. }
  57624. }
  57625. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57626. if (limitVelocityGradients) {
  57627. serializationObject.limitVelocityGradients = [];
  57628. for (var _g = 0, limitVelocityGradients_1 = limitVelocityGradients; _g < limitVelocityGradients_1.length; _g++) {
  57629. var limitVelocityGradient = limitVelocityGradients_1[_g];
  57630. var serializedGradient = {
  57631. gradient: limitVelocityGradient.gradient,
  57632. factor1: limitVelocityGradient.factor1
  57633. };
  57634. if (limitVelocityGradient.factor2 !== undefined) {
  57635. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57636. }
  57637. serializationObject.limitVelocityGradients.push(serializedGradient);
  57638. }
  57639. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57640. }
  57641. if (BABYLON.ProceduralTexture && particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  57642. var noiseTexture = particleSystem.noiseTexture;
  57643. serializationObject.noiseTexture = noiseTexture.serialize();
  57644. }
  57645. };
  57646. /** @hidden */
  57647. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  57648. // Texture
  57649. if (parsedParticleSystem.textureName) {
  57650. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57651. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57652. }
  57653. // Emitter
  57654. if (parsedParticleSystem.emitterId === undefined) {
  57655. particleSystem.emitter = BABYLON.Vector3.Zero();
  57656. }
  57657. else if (parsedParticleSystem.emitterId) {
  57658. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57659. }
  57660. else {
  57661. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57662. }
  57663. // Misc.
  57664. if (parsedParticleSystem.renderingGroupId !== undefined) {
  57665. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  57666. }
  57667. if (parsedParticleSystem.isBillboardBased !== undefined) {
  57668. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  57669. }
  57670. // Animations
  57671. if (parsedParticleSystem.animations) {
  57672. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57673. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57674. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57675. }
  57676. }
  57677. if (parsedParticleSystem.autoAnimate) {
  57678. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57679. }
  57680. // Particle system
  57681. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57682. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57683. particleSystem.minSize = parsedParticleSystem.minSize;
  57684. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57685. if (parsedParticleSystem.minScaleX) {
  57686. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57687. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57688. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57689. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57690. }
  57691. if (parsedParticleSystem.preWarmCycles !== undefined) {
  57692. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  57693. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  57694. }
  57695. if (parsedParticleSystem.minInitialRotation !== undefined) {
  57696. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  57697. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  57698. }
  57699. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57700. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57701. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57702. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57703. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57704. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57705. if (parsedParticleSystem.noiseStrength) {
  57706. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  57707. }
  57708. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57709. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57710. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57711. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57712. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57713. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57714. if (parsedParticleSystem.colorGradients) {
  57715. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  57716. var colorGradient = _a[_i];
  57717. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  57718. }
  57719. }
  57720. if (parsedParticleSystem.sizeGradients) {
  57721. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  57722. var sizeGradient = _c[_b];
  57723. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57724. }
  57725. }
  57726. if (parsedParticleSystem.angularSpeedGradients) {
  57727. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  57728. var angularSpeedGradient = _e[_d];
  57729. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  57730. }
  57731. }
  57732. if (parsedParticleSystem.velocityGradients) {
  57733. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  57734. var velocityGradient = _g[_f];
  57735. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  57736. }
  57737. }
  57738. if (parsedParticleSystem.dragGradients) {
  57739. for (var _h = 0, _j = parsedParticleSystem.dragGradients; _h < _j.length; _h++) {
  57740. var dragGradient = _j[_h];
  57741. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  57742. }
  57743. }
  57744. if (parsedParticleSystem.emitRateGradients) {
  57745. for (var _k = 0, _l = parsedParticleSystem.emitRateGradients; _k < _l.length; _k++) {
  57746. var emitRateGradient = _l[_k];
  57747. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  57748. }
  57749. }
  57750. if (parsedParticleSystem.startSizeGradients) {
  57751. for (var _m = 0, _o = parsedParticleSystem.startSizeGradients; _m < _o.length; _m++) {
  57752. var startSizeGradient = _o[_m];
  57753. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  57754. }
  57755. }
  57756. if (parsedParticleSystem.limitVelocityGradients) {
  57757. for (var _p = 0, _q = parsedParticleSystem.limitVelocityGradients; _p < _q.length; _p++) {
  57758. var limitVelocityGradient = _q[_p];
  57759. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  57760. }
  57761. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  57762. }
  57763. if (parsedParticleSystem.noiseTexture) {
  57764. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  57765. }
  57766. // Emitter
  57767. var emitterType;
  57768. if (parsedParticleSystem.particleEmitterType) {
  57769. switch (parsedParticleSystem.particleEmitterType.type) {
  57770. case "SphereParticleEmitter":
  57771. emitterType = new BABYLON.SphereParticleEmitter();
  57772. break;
  57773. case "SphereDirectedParticleEmitter":
  57774. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57775. break;
  57776. case "ConeEmitter":
  57777. case "ConeParticleEmitter":
  57778. emitterType = new BABYLON.ConeParticleEmitter();
  57779. break;
  57780. case "BoxEmitter":
  57781. case "BoxParticleEmitter":
  57782. default:
  57783. emitterType = new BABYLON.BoxParticleEmitter();
  57784. break;
  57785. }
  57786. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57787. }
  57788. else {
  57789. emitterType = new BABYLON.BoxParticleEmitter();
  57790. emitterType.parse(parsedParticleSystem);
  57791. }
  57792. particleSystem.particleEmitterType = emitterType;
  57793. // Animation sheet
  57794. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57795. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57796. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57797. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57798. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57799. };
  57800. /**
  57801. * Parses a JSON object to create a particle system.
  57802. * @param parsedParticleSystem The JSON object to parse
  57803. * @param scene The scene to create the particle system in
  57804. * @param rootUrl The root url to use to load external dependencies like texture
  57805. * @returns the Parsed particle system
  57806. */
  57807. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57808. var name = parsedParticleSystem.name;
  57809. var custom = null;
  57810. var program = null;
  57811. if (parsedParticleSystem.customShader) {
  57812. program = parsedParticleSystem.customShader;
  57813. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57814. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57815. }
  57816. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57817. particleSystem.customShader = program;
  57818. if (parsedParticleSystem.id) {
  57819. particleSystem.id = parsedParticleSystem.id;
  57820. }
  57821. // Auto start
  57822. if (parsedParticleSystem.preventAutoStart) {
  57823. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57824. }
  57825. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57826. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57827. if (!particleSystem.preventAutoStart) {
  57828. particleSystem.start();
  57829. }
  57830. return particleSystem;
  57831. };
  57832. return ParticleSystem;
  57833. }(BABYLON.BaseParticleSystem));
  57834. BABYLON.ParticleSystem = ParticleSystem;
  57835. })(BABYLON || (BABYLON = {}));
  57836. //# sourceMappingURL=babylon.particleSystem.js.map
  57837. var BABYLON;
  57838. (function (BABYLON) {
  57839. /**
  57840. * Particle emitter emitting particles from the inside of a box.
  57841. * It emits the particles randomly between 2 given directions.
  57842. */
  57843. var BoxParticleEmitter = /** @class */ (function () {
  57844. /**
  57845. * Creates a new instance BoxParticleEmitter
  57846. */
  57847. function BoxParticleEmitter() {
  57848. /**
  57849. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57850. */
  57851. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57852. /**
  57853. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57854. */
  57855. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57856. /**
  57857. * 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.
  57858. */
  57859. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57860. /**
  57861. * 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.
  57862. */
  57863. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57864. }
  57865. /**
  57866. * Called by the particle System when the direction is computed for the created particle.
  57867. * @param worldMatrix is the world matrix of the particle system
  57868. * @param directionToUpdate is the direction vector to update with the result
  57869. * @param particle is the particle we are computed the direction for
  57870. */
  57871. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57872. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57873. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57874. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57875. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57876. };
  57877. /**
  57878. * Called by the particle System when the position is computed for the created particle.
  57879. * @param worldMatrix is the world matrix of the particle system
  57880. * @param positionToUpdate is the position vector to update with the result
  57881. * @param particle is the particle we are computed the position for
  57882. */
  57883. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57884. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57885. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57886. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57887. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57888. };
  57889. /**
  57890. * Clones the current emitter and returns a copy of it
  57891. * @returns the new emitter
  57892. */
  57893. BoxParticleEmitter.prototype.clone = function () {
  57894. var newOne = new BoxParticleEmitter();
  57895. BABYLON.Tools.DeepCopy(this, newOne);
  57896. return newOne;
  57897. };
  57898. /**
  57899. * Called by the GPUParticleSystem to setup the update shader
  57900. * @param effect defines the update shader
  57901. */
  57902. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57903. effect.setVector3("direction1", this.direction1);
  57904. effect.setVector3("direction2", this.direction2);
  57905. effect.setVector3("minEmitBox", this.minEmitBox);
  57906. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57907. };
  57908. /**
  57909. * Returns a string to use to update the GPU particles update shader
  57910. * @returns a string containng the defines string
  57911. */
  57912. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57913. return "#define BOXEMITTER";
  57914. };
  57915. /**
  57916. * Returns the string "BoxParticleEmitter"
  57917. * @returns a string containing the class name
  57918. */
  57919. BoxParticleEmitter.prototype.getClassName = function () {
  57920. return "BoxParticleEmitter";
  57921. };
  57922. /**
  57923. * Serializes the particle system to a JSON object.
  57924. * @returns the JSON object
  57925. */
  57926. BoxParticleEmitter.prototype.serialize = function () {
  57927. var serializationObject = {};
  57928. serializationObject.type = this.getClassName();
  57929. serializationObject.direction1 = this.direction1.asArray();
  57930. serializationObject.direction2 = this.direction2.asArray();
  57931. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57932. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57933. return serializationObject;
  57934. };
  57935. /**
  57936. * Parse properties from a JSON object
  57937. * @param serializationObject defines the JSON object
  57938. */
  57939. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57940. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  57941. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  57942. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  57943. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  57944. };
  57945. return BoxParticleEmitter;
  57946. }());
  57947. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57948. })(BABYLON || (BABYLON = {}));
  57949. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57950. var BABYLON;
  57951. (function (BABYLON) {
  57952. /**
  57953. * Particle emitter emitting particles from the inside of a cylinder.
  57954. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  57955. */
  57956. var CylinderParticleEmitter = /** @class */ (function () {
  57957. /**
  57958. * Creates a new instance CylinderParticleEmitter
  57959. * @param radius the radius of the emission cylinder (1 by default)
  57960. * @param height the height of the emission cylinder (1 by default)
  57961. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57962. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57963. */
  57964. function CylinderParticleEmitter(
  57965. /**
  57966. * The radius of the emission cylinder.
  57967. */
  57968. radius,
  57969. /**
  57970. * The height of the emission cylinder.
  57971. */
  57972. height,
  57973. /**
  57974. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57975. */
  57976. radiusRange,
  57977. /**
  57978. * How much to randomize the particle direction [0-1].
  57979. */
  57980. directionRandomizer) {
  57981. if (radius === void 0) { radius = 1; }
  57982. if (height === void 0) { height = 1; }
  57983. if (radiusRange === void 0) { radiusRange = 1; }
  57984. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57985. this.radius = radius;
  57986. this.height = height;
  57987. this.radiusRange = radiusRange;
  57988. this.directionRandomizer = directionRandomizer;
  57989. }
  57990. /**
  57991. * Called by the particle System when the direction is computed for the created particle.
  57992. * @param worldMatrix is the world matrix of the particle system
  57993. * @param directionToUpdate is the direction vector to update with the result
  57994. * @param particle is the particle we are computed the direction for
  57995. */
  57996. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57997. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57998. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  57999. var angle = Math.atan2(direction.x, direction.z);
  58000. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  58001. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  58002. direction.x = Math.sin(angle);
  58003. direction.z = Math.cos(angle);
  58004. direction.normalize();
  58005. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58006. };
  58007. /**
  58008. * Called by the particle System when the position is computed for the created particle.
  58009. * @param worldMatrix is the world matrix of the particle system
  58010. * @param positionToUpdate is the position vector to update with the result
  58011. * @param particle is the particle we are computed the position for
  58012. */
  58013. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58014. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  58015. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58016. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  58017. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  58018. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  58019. var xPos = positionRadius * Math.cos(angle);
  58020. var zPos = positionRadius * Math.sin(angle);
  58021. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  58022. };
  58023. /**
  58024. * Clones the current emitter and returns a copy of it
  58025. * @returns the new emitter
  58026. */
  58027. CylinderParticleEmitter.prototype.clone = function () {
  58028. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  58029. BABYLON.Tools.DeepCopy(this, newOne);
  58030. return newOne;
  58031. };
  58032. /**
  58033. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58034. * @param effect defines the update shader
  58035. */
  58036. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  58037. effect.setFloat("radius", this.radius);
  58038. effect.setFloat("height", this.height);
  58039. effect.setFloat("radiusRange", this.radiusRange);
  58040. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58041. };
  58042. /**
  58043. * Returns a string to use to update the GPU particles update shader
  58044. * @returns a string containng the defines string
  58045. */
  58046. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  58047. return "#define CYLINDEREMITTER";
  58048. };
  58049. /**
  58050. * Returns the string "CylinderParticleEmitter"
  58051. * @returns a string containing the class name
  58052. */
  58053. CylinderParticleEmitter.prototype.getClassName = function () {
  58054. return "CylinderParticleEmitter";
  58055. };
  58056. /**
  58057. * Serializes the particle system to a JSON object.
  58058. * @returns the JSON object
  58059. */
  58060. CylinderParticleEmitter.prototype.serialize = function () {
  58061. var serializationObject = {};
  58062. serializationObject.type = this.getClassName();
  58063. serializationObject.radius = this.radius;
  58064. serializationObject.height = this.height;
  58065. serializationObject.radiusRange = this.radiusRange;
  58066. serializationObject.directionRandomizer = this.directionRandomizer;
  58067. return serializationObject;
  58068. };
  58069. /**
  58070. * Parse properties from a JSON object
  58071. * @param serializationObject defines the JSON object
  58072. */
  58073. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  58074. this.radius = serializationObject.radius;
  58075. this.height = serializationObject.height;
  58076. this.radiusRange = serializationObject.radiusRange;
  58077. this.directionRandomizer = serializationObject.directionRandomizer;
  58078. };
  58079. return CylinderParticleEmitter;
  58080. }());
  58081. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  58082. /**
  58083. * Particle emitter emitting particles from the inside of a cylinder.
  58084. * It emits the particles randomly between two vectors.
  58085. */
  58086. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  58087. __extends(CylinderDirectedParticleEmitter, _super);
  58088. /**
  58089. * Creates a new instance CylinderDirectedParticleEmitter
  58090. * @param radius the radius of the emission cylinder (1 by default)
  58091. * @param height the height of the emission cylinder (1 by default)
  58092. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58093. * @param direction1 the min limit of the emission direction (up vector by default)
  58094. * @param direction2 the max limit of the emission direction (up vector by default)
  58095. */
  58096. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  58097. /**
  58098. * The min limit of the emission direction.
  58099. */
  58100. direction1,
  58101. /**
  58102. * The max limit of the emission direction.
  58103. */
  58104. direction2) {
  58105. if (radius === void 0) { radius = 1; }
  58106. if (height === void 0) { height = 1; }
  58107. if (radiusRange === void 0) { radiusRange = 1; }
  58108. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58109. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58110. var _this = _super.call(this, radius, height, radiusRange) || this;
  58111. _this.direction1 = direction1;
  58112. _this.direction2 = direction2;
  58113. return _this;
  58114. }
  58115. /**
  58116. * Called by the particle System when the direction is computed for the created particle.
  58117. * @param worldMatrix is the world matrix of the particle system
  58118. * @param directionToUpdate is the direction vector to update with the result
  58119. * @param particle is the particle we are computed the direction for
  58120. */
  58121. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58122. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58123. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58124. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58125. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58126. };
  58127. /**
  58128. * Clones the current emitter and returns a copy of it
  58129. * @returns the new emitter
  58130. */
  58131. CylinderDirectedParticleEmitter.prototype.clone = function () {
  58132. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  58133. BABYLON.Tools.DeepCopy(this, newOne);
  58134. return newOne;
  58135. };
  58136. /**
  58137. * Called by the GPUParticleSystem to setup the update shader
  58138. * @param effect defines the update shader
  58139. */
  58140. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58141. effect.setFloat("radius", this.radius);
  58142. effect.setFloat("height", this.height);
  58143. effect.setFloat("radiusRange", this.radiusRange);
  58144. effect.setVector3("direction1", this.direction1);
  58145. effect.setVector3("direction2", this.direction2);
  58146. };
  58147. /**
  58148. * Returns a string to use to update the GPU particles update shader
  58149. * @returns a string containng the defines string
  58150. */
  58151. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58152. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  58153. };
  58154. /**
  58155. * Returns the string "CylinderDirectedParticleEmitter"
  58156. * @returns a string containing the class name
  58157. */
  58158. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  58159. return "CylinderDirectedParticleEmitter";
  58160. };
  58161. /**
  58162. * Serializes the particle system to a JSON object.
  58163. * @returns the JSON object
  58164. */
  58165. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  58166. var serializationObject = _super.prototype.serialize.call(this);
  58167. serializationObject.direction1 = this.direction1.asArray();
  58168. serializationObject.direction2 = this.direction2.asArray();
  58169. return serializationObject;
  58170. };
  58171. /**
  58172. * Parse properties from a JSON object
  58173. * @param serializationObject defines the JSON object
  58174. */
  58175. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58176. _super.prototype.parse.call(this, serializationObject);
  58177. this.direction1.copyFrom(serializationObject.direction1);
  58178. this.direction2.copyFrom(serializationObject.direction2);
  58179. };
  58180. return CylinderDirectedParticleEmitter;
  58181. }(CylinderParticleEmitter));
  58182. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  58183. })(BABYLON || (BABYLON = {}));
  58184. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  58185. var BABYLON;
  58186. (function (BABYLON) {
  58187. /**
  58188. * Particle emitter emitting particles from the inside of a cone.
  58189. * It emits the particles alongside the cone volume from the base to the particle.
  58190. * The emission direction might be randomized.
  58191. */
  58192. var ConeParticleEmitter = /** @class */ (function () {
  58193. /**
  58194. * Creates a new instance ConeParticleEmitter
  58195. * @param radius the radius of the emission cone (1 by default)
  58196. * @param angles the cone base angle (PI by default)
  58197. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  58198. */
  58199. function ConeParticleEmitter(radius, angle,
  58200. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  58201. directionRandomizer) {
  58202. if (radius === void 0) { radius = 1; }
  58203. if (angle === void 0) { angle = Math.PI; }
  58204. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58205. this.directionRandomizer = directionRandomizer;
  58206. /**
  58207. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  58208. */
  58209. this.radiusRange = 1;
  58210. /**
  58211. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  58212. */
  58213. this.heightRange = 1;
  58214. /**
  58215. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  58216. */
  58217. this.emitFromSpawnPointOnly = false;
  58218. this.angle = angle;
  58219. this.radius = radius;
  58220. }
  58221. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  58222. /**
  58223. * Gets or sets the radius of the emission cone
  58224. */
  58225. get: function () {
  58226. return this._radius;
  58227. },
  58228. set: function (value) {
  58229. this._radius = value;
  58230. this._buildHeight();
  58231. },
  58232. enumerable: true,
  58233. configurable: true
  58234. });
  58235. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  58236. /**
  58237. * Gets or sets the angle of the emission cone
  58238. */
  58239. get: function () {
  58240. return this._angle;
  58241. },
  58242. set: function (value) {
  58243. this._angle = value;
  58244. this._buildHeight();
  58245. },
  58246. enumerable: true,
  58247. configurable: true
  58248. });
  58249. ConeParticleEmitter.prototype._buildHeight = function () {
  58250. if (this._angle !== 0) {
  58251. this._height = this._radius / Math.tan(this._angle / 2);
  58252. }
  58253. else {
  58254. this._height = 1;
  58255. }
  58256. };
  58257. /**
  58258. * Called by the particle System when the direction is computed for the created particle.
  58259. * @param worldMatrix is the world matrix of the particle system
  58260. * @param directionToUpdate is the direction vector to update with the result
  58261. * @param particle is the particle we are computed the direction for
  58262. */
  58263. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58264. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  58265. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  58266. }
  58267. else {
  58268. // measure the direction Vector from the emitter to the particle.
  58269. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58270. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58271. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58272. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58273. direction.x += randX;
  58274. direction.y += randY;
  58275. direction.z += randZ;
  58276. direction.normalize();
  58277. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58278. }
  58279. };
  58280. /**
  58281. * Called by the particle System when the position is computed for the created particle.
  58282. * @param worldMatrix is the world matrix of the particle system
  58283. * @param positionToUpdate is the position vector to update with the result
  58284. * @param particle is the particle we are computed the position for
  58285. */
  58286. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58287. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  58288. var h;
  58289. if (!this.emitFromSpawnPointOnly) {
  58290. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  58291. // Better distribution in a cone at normal angles.
  58292. h = 1 - h * h;
  58293. }
  58294. else {
  58295. h = 0.0001;
  58296. }
  58297. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  58298. radius = radius * h;
  58299. var randX = radius * Math.sin(s);
  58300. var randZ = radius * Math.cos(s);
  58301. var randY = h * this._height;
  58302. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58303. };
  58304. /**
  58305. * Clones the current emitter and returns a copy of it
  58306. * @returns the new emitter
  58307. */
  58308. ConeParticleEmitter.prototype.clone = function () {
  58309. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  58310. BABYLON.Tools.DeepCopy(this, newOne);
  58311. return newOne;
  58312. };
  58313. /**
  58314. * Called by the GPUParticleSystem to setup the update shader
  58315. * @param effect defines the update shader
  58316. */
  58317. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  58318. effect.setFloat2("radius", this._radius, this.radiusRange);
  58319. effect.setFloat("coneAngle", this._angle);
  58320. effect.setFloat2("height", this._height, this.heightRange);
  58321. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58322. };
  58323. /**
  58324. * Returns a string to use to update the GPU particles update shader
  58325. * @returns a string containng the defines string
  58326. */
  58327. ConeParticleEmitter.prototype.getEffectDefines = function () {
  58328. var defines = "#define CONEEMITTER";
  58329. if (this.emitFromSpawnPointOnly) {
  58330. defines += "\n#define CONEEMITTERSPAWNPOINT";
  58331. }
  58332. return defines;
  58333. };
  58334. /**
  58335. * Returns the string "ConeParticleEmitter"
  58336. * @returns a string containing the class name
  58337. */
  58338. ConeParticleEmitter.prototype.getClassName = function () {
  58339. return "ConeParticleEmitter";
  58340. };
  58341. /**
  58342. * Serializes the particle system to a JSON object.
  58343. * @returns the JSON object
  58344. */
  58345. ConeParticleEmitter.prototype.serialize = function () {
  58346. var serializationObject = {};
  58347. serializationObject.type = this.getClassName();
  58348. serializationObject.radius = this._radius;
  58349. serializationObject.angle = this._angle;
  58350. serializationObject.directionRandomizer = this.directionRandomizer;
  58351. return serializationObject;
  58352. };
  58353. /**
  58354. * Parse properties from a JSON object
  58355. * @param serializationObject defines the JSON object
  58356. */
  58357. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  58358. this.radius = serializationObject.radius;
  58359. this.angle = serializationObject.angle;
  58360. this.directionRandomizer = serializationObject.directionRandomizer;
  58361. };
  58362. return ConeParticleEmitter;
  58363. }());
  58364. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  58365. })(BABYLON || (BABYLON = {}));
  58366. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  58367. var BABYLON;
  58368. (function (BABYLON) {
  58369. /**
  58370. * Particle emitter emitting particles from the inside of a sphere.
  58371. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  58372. */
  58373. var SphereParticleEmitter = /** @class */ (function () {
  58374. /**
  58375. * Creates a new instance SphereParticleEmitter
  58376. * @param radius the radius of the emission sphere (1 by default)
  58377. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58378. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58379. */
  58380. function SphereParticleEmitter(
  58381. /**
  58382. * The radius of the emission sphere.
  58383. */
  58384. radius,
  58385. /**
  58386. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58387. */
  58388. radiusRange,
  58389. /**
  58390. * How much to randomize the particle direction [0-1].
  58391. */
  58392. directionRandomizer) {
  58393. if (radius === void 0) { radius = 1; }
  58394. if (radiusRange === void 0) { radiusRange = 1; }
  58395. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58396. this.radius = radius;
  58397. this.radiusRange = radiusRange;
  58398. this.directionRandomizer = directionRandomizer;
  58399. }
  58400. /**
  58401. * Called by the particle System when the direction is computed for the created particle.
  58402. * @param worldMatrix is the world matrix of the particle system
  58403. * @param directionToUpdate is the direction vector to update with the result
  58404. * @param particle is the particle we are computed the direction for
  58405. */
  58406. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58407. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58408. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58409. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58410. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58411. direction.x += randX;
  58412. direction.y += randY;
  58413. direction.z += randZ;
  58414. direction.normalize();
  58415. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58416. };
  58417. /**
  58418. * Called by the particle System when the position is computed for the created particle.
  58419. * @param worldMatrix is the world matrix of the particle system
  58420. * @param positionToUpdate is the position vector to update with the result
  58421. * @param particle is the particle we are computed the position for
  58422. */
  58423. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58424. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58425. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58426. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58427. var theta = Math.acos(2 * v - 1);
  58428. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58429. var randY = randRadius * Math.cos(theta);
  58430. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58431. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58432. };
  58433. /**
  58434. * Clones the current emitter and returns a copy of it
  58435. * @returns the new emitter
  58436. */
  58437. SphereParticleEmitter.prototype.clone = function () {
  58438. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  58439. BABYLON.Tools.DeepCopy(this, newOne);
  58440. return newOne;
  58441. };
  58442. /**
  58443. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58444. * @param effect defines the update shader
  58445. */
  58446. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  58447. effect.setFloat("radius", this.radius);
  58448. effect.setFloat("radiusRange", this.radiusRange);
  58449. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58450. };
  58451. /**
  58452. * Returns a string to use to update the GPU particles update shader
  58453. * @returns a string containng the defines string
  58454. */
  58455. SphereParticleEmitter.prototype.getEffectDefines = function () {
  58456. return "#define SPHEREEMITTER";
  58457. };
  58458. /**
  58459. * Returns the string "SphereParticleEmitter"
  58460. * @returns a string containing the class name
  58461. */
  58462. SphereParticleEmitter.prototype.getClassName = function () {
  58463. return "SphereParticleEmitter";
  58464. };
  58465. /**
  58466. * Serializes the particle system to a JSON object.
  58467. * @returns the JSON object
  58468. */
  58469. SphereParticleEmitter.prototype.serialize = function () {
  58470. var serializationObject = {};
  58471. serializationObject.type = this.getClassName();
  58472. serializationObject.radius = this.radius;
  58473. serializationObject.radiusRange = this.radiusRange;
  58474. serializationObject.directionRandomizer = this.directionRandomizer;
  58475. return serializationObject;
  58476. };
  58477. /**
  58478. * Parse properties from a JSON object
  58479. * @param serializationObject defines the JSON object
  58480. */
  58481. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  58482. this.radius = serializationObject.radius;
  58483. this.radiusRange = serializationObject.radiusRange;
  58484. this.directionRandomizer = serializationObject.directionRandomizer;
  58485. };
  58486. return SphereParticleEmitter;
  58487. }());
  58488. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  58489. /**
  58490. * Particle emitter emitting particles from the inside of a sphere.
  58491. * It emits the particles randomly between two vectors.
  58492. */
  58493. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  58494. __extends(SphereDirectedParticleEmitter, _super);
  58495. /**
  58496. * Creates a new instance SphereDirectedParticleEmitter
  58497. * @param radius the radius of the emission sphere (1 by default)
  58498. * @param direction1 the min limit of the emission direction (up vector by default)
  58499. * @param direction2 the max limit of the emission direction (up vector by default)
  58500. */
  58501. function SphereDirectedParticleEmitter(radius,
  58502. /**
  58503. * The min limit of the emission direction.
  58504. */
  58505. direction1,
  58506. /**
  58507. * The max limit of the emission direction.
  58508. */
  58509. direction2) {
  58510. if (radius === void 0) { radius = 1; }
  58511. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58512. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58513. var _this = _super.call(this, radius) || this;
  58514. _this.direction1 = direction1;
  58515. _this.direction2 = direction2;
  58516. return _this;
  58517. }
  58518. /**
  58519. * Called by the particle System when the direction is computed for the created particle.
  58520. * @param worldMatrix is the world matrix of the particle system
  58521. * @param directionToUpdate is the direction vector to update with the result
  58522. * @param particle is the particle we are computed the direction for
  58523. */
  58524. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58525. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58526. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58527. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58528. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58529. };
  58530. /**
  58531. * Clones the current emitter and returns a copy of it
  58532. * @returns the new emitter
  58533. */
  58534. SphereDirectedParticleEmitter.prototype.clone = function () {
  58535. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  58536. BABYLON.Tools.DeepCopy(this, newOne);
  58537. return newOne;
  58538. };
  58539. /**
  58540. * Called by the GPUParticleSystem to setup the update shader
  58541. * @param effect defines the update shader
  58542. */
  58543. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58544. effect.setFloat("radius", this.radius);
  58545. effect.setFloat("radiusRange", this.radiusRange);
  58546. effect.setVector3("direction1", this.direction1);
  58547. effect.setVector3("direction2", this.direction2);
  58548. };
  58549. /**
  58550. * Returns a string to use to update the GPU particles update shader
  58551. * @returns a string containng the defines string
  58552. */
  58553. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58554. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  58555. };
  58556. /**
  58557. * Returns the string "SphereDirectedParticleEmitter"
  58558. * @returns a string containing the class name
  58559. */
  58560. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  58561. return "SphereDirectedParticleEmitter";
  58562. };
  58563. /**
  58564. * Serializes the particle system to a JSON object.
  58565. * @returns the JSON object
  58566. */
  58567. SphereDirectedParticleEmitter.prototype.serialize = function () {
  58568. var serializationObject = _super.prototype.serialize.call(this);
  58569. serializationObject.direction1 = this.direction1.asArray();
  58570. serializationObject.direction2 = this.direction2.asArray();
  58571. return serializationObject;
  58572. };
  58573. /**
  58574. * Parse properties from a JSON object
  58575. * @param serializationObject defines the JSON object
  58576. */
  58577. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58578. _super.prototype.parse.call(this, serializationObject);
  58579. this.direction1.copyFrom(serializationObject.direction1);
  58580. this.direction2.copyFrom(serializationObject.direction2);
  58581. };
  58582. return SphereDirectedParticleEmitter;
  58583. }(SphereParticleEmitter));
  58584. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  58585. })(BABYLON || (BABYLON = {}));
  58586. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  58587. var BABYLON;
  58588. (function (BABYLON) {
  58589. /**
  58590. * Particle emitter emitting particles from the inside of a hemisphere.
  58591. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  58592. */
  58593. var HemisphericParticleEmitter = /** @class */ (function () {
  58594. /**
  58595. * Creates a new instance HemisphericParticleEmitter
  58596. * @param radius the radius of the emission hemisphere (1 by default)
  58597. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58598. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58599. */
  58600. function HemisphericParticleEmitter(
  58601. /**
  58602. * The radius of the emission hemisphere.
  58603. */
  58604. radius,
  58605. /**
  58606. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58607. */
  58608. radiusRange,
  58609. /**
  58610. * How much to randomize the particle direction [0-1].
  58611. */
  58612. directionRandomizer) {
  58613. if (radius === void 0) { radius = 1; }
  58614. if (radiusRange === void 0) { radiusRange = 1; }
  58615. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58616. this.radius = radius;
  58617. this.radiusRange = radiusRange;
  58618. this.directionRandomizer = directionRandomizer;
  58619. }
  58620. /**
  58621. * Called by the particle System when the direction is computed for the created particle.
  58622. * @param worldMatrix is the world matrix of the particle system
  58623. * @param directionToUpdate is the direction vector to update with the result
  58624. * @param particle is the particle we are computed the direction for
  58625. */
  58626. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58627. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58628. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58629. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58630. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58631. direction.x += randX;
  58632. direction.y += randY;
  58633. direction.z += randZ;
  58634. direction.normalize();
  58635. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58636. };
  58637. /**
  58638. * Called by the particle System when the position is computed for the created particle.
  58639. * @param worldMatrix is the world matrix of the particle system
  58640. * @param positionToUpdate is the position vector to update with the result
  58641. * @param particle is the particle we are computed the position for
  58642. */
  58643. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58644. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58645. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58646. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58647. var theta = Math.acos(2 * v - 1);
  58648. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58649. var randY = randRadius * Math.cos(theta);
  58650. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58651. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  58652. };
  58653. /**
  58654. * Clones the current emitter and returns a copy of it
  58655. * @returns the new emitter
  58656. */
  58657. HemisphericParticleEmitter.prototype.clone = function () {
  58658. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  58659. BABYLON.Tools.DeepCopy(this, newOne);
  58660. return newOne;
  58661. };
  58662. /**
  58663. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58664. * @param effect defines the update shader
  58665. */
  58666. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  58667. effect.setFloat("radius", this.radius);
  58668. effect.setFloat("radiusRange", this.radiusRange);
  58669. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58670. };
  58671. /**
  58672. * Returns a string to use to update the GPU particles update shader
  58673. * @returns a string containng the defines string
  58674. */
  58675. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  58676. return "#define HEMISPHERICEMITTER";
  58677. };
  58678. /**
  58679. * Returns the string "HemisphericParticleEmitter"
  58680. * @returns a string containing the class name
  58681. */
  58682. HemisphericParticleEmitter.prototype.getClassName = function () {
  58683. return "HemisphericParticleEmitter";
  58684. };
  58685. /**
  58686. * Serializes the particle system to a JSON object.
  58687. * @returns the JSON object
  58688. */
  58689. HemisphericParticleEmitter.prototype.serialize = function () {
  58690. var serializationObject = {};
  58691. serializationObject.type = this.getClassName();
  58692. serializationObject.radius = this.radius;
  58693. serializationObject.radiusRange = this.radiusRange;
  58694. serializationObject.directionRandomizer = this.directionRandomizer;
  58695. return serializationObject;
  58696. };
  58697. /**
  58698. * Parse properties from a JSON object
  58699. * @param serializationObject defines the JSON object
  58700. */
  58701. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  58702. this.radius = serializationObject.radius;
  58703. this.radiusRange = serializationObject.radiusRange;
  58704. this.directionRandomizer = serializationObject.directionRandomizer;
  58705. };
  58706. return HemisphericParticleEmitter;
  58707. }());
  58708. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  58709. })(BABYLON || (BABYLON = {}));
  58710. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  58711. var BABYLON;
  58712. (function (BABYLON) {
  58713. /**
  58714. * Particle emitter emitting particles from a point.
  58715. * It emits the particles randomly between 2 given directions.
  58716. */
  58717. var PointParticleEmitter = /** @class */ (function () {
  58718. /**
  58719. * Creates a new instance PointParticleEmitter
  58720. */
  58721. function PointParticleEmitter() {
  58722. /**
  58723. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58724. */
  58725. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58726. /**
  58727. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58728. */
  58729. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58730. }
  58731. /**
  58732. * Called by the particle System when the direction is computed for the created particle.
  58733. * @param worldMatrix is the world matrix of the particle system
  58734. * @param directionToUpdate is the direction vector to update with the result
  58735. * @param particle is the particle we are computed the direction for
  58736. */
  58737. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58738. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58739. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58740. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58741. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58742. };
  58743. /**
  58744. * Called by the particle System when the position is computed for the created particle.
  58745. * @param worldMatrix is the world matrix of the particle system
  58746. * @param positionToUpdate is the position vector to update with the result
  58747. * @param particle is the particle we are computed the position for
  58748. */
  58749. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58750. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  58751. };
  58752. /**
  58753. * Clones the current emitter and returns a copy of it
  58754. * @returns the new emitter
  58755. */
  58756. PointParticleEmitter.prototype.clone = function () {
  58757. var newOne = new PointParticleEmitter();
  58758. BABYLON.Tools.DeepCopy(this, newOne);
  58759. return newOne;
  58760. };
  58761. /**
  58762. * Called by the GPUParticleSystem to setup the update shader
  58763. * @param effect defines the update shader
  58764. */
  58765. PointParticleEmitter.prototype.applyToShader = function (effect) {
  58766. effect.setVector3("direction1", this.direction1);
  58767. effect.setVector3("direction2", this.direction2);
  58768. };
  58769. /**
  58770. * Returns a string to use to update the GPU particles update shader
  58771. * @returns a string containng the defines string
  58772. */
  58773. PointParticleEmitter.prototype.getEffectDefines = function () {
  58774. return "#define POINTEMITTER";
  58775. };
  58776. /**
  58777. * Returns the string "PointParticleEmitter"
  58778. * @returns a string containing the class name
  58779. */
  58780. PointParticleEmitter.prototype.getClassName = function () {
  58781. return "PointParticleEmitter";
  58782. };
  58783. /**
  58784. * Serializes the particle system to a JSON object.
  58785. * @returns the JSON object
  58786. */
  58787. PointParticleEmitter.prototype.serialize = function () {
  58788. var serializationObject = {};
  58789. serializationObject.type = this.getClassName();
  58790. serializationObject.direction1 = this.direction1.asArray();
  58791. serializationObject.direction2 = this.direction2.asArray();
  58792. return serializationObject;
  58793. };
  58794. /**
  58795. * Parse properties from a JSON object
  58796. * @param serializationObject defines the JSON object
  58797. */
  58798. PointParticleEmitter.prototype.parse = function (serializationObject) {
  58799. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58800. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58801. };
  58802. return PointParticleEmitter;
  58803. }());
  58804. BABYLON.PointParticleEmitter = PointParticleEmitter;
  58805. })(BABYLON || (BABYLON = {}));
  58806. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  58807. var BABYLON;
  58808. (function (BABYLON) {
  58809. // Adds the parsers to the scene parsers.
  58810. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  58811. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  58812. if (!individualParser) {
  58813. return;
  58814. }
  58815. // Particles Systems
  58816. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58817. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58818. var parsedParticleSystem = parsedData.particleSystems[index];
  58819. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  58820. }
  58821. }
  58822. });
  58823. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  58824. if (parsedParticleSystem.activeParticleCount) {
  58825. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58826. return ps;
  58827. }
  58828. else {
  58829. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58830. return ps;
  58831. }
  58832. });
  58833. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  58834. if (uniformsNames === void 0) { uniformsNames = []; }
  58835. if (samplers === void 0) { samplers = []; }
  58836. if (defines === void 0) { defines = ""; }
  58837. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  58838. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  58839. if (defines.indexOf(" BILLBOARD") === -1) {
  58840. defines += "\n#define BILLBOARD\n";
  58841. }
  58842. if (samplers.indexOf("diffuseSampler") === -1) {
  58843. samplers.push("diffuseSampler");
  58844. }
  58845. return this.createEffect({
  58846. vertex: "particles",
  58847. fragmentElement: fragmentName
  58848. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  58849. };
  58850. })(BABYLON || (BABYLON = {}));
  58851. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  58852. var BABYLON;
  58853. (function (BABYLON) {
  58854. var ShaderMaterial = /** @class */ (function (_super) {
  58855. __extends(ShaderMaterial, _super);
  58856. function ShaderMaterial(name, scene, shaderPath, options) {
  58857. var _this = _super.call(this, name, scene) || this;
  58858. _this._textures = {};
  58859. _this._textureArrays = {};
  58860. _this._floats = {};
  58861. _this._ints = {};
  58862. _this._floatsArrays = {};
  58863. _this._colors3 = {};
  58864. _this._colors3Arrays = {};
  58865. _this._colors4 = {};
  58866. _this._vectors2 = {};
  58867. _this._vectors3 = {};
  58868. _this._vectors4 = {};
  58869. _this._matrices = {};
  58870. _this._matrices3x3 = {};
  58871. _this._matrices2x2 = {};
  58872. _this._vectors2Arrays = {};
  58873. _this._vectors3Arrays = {};
  58874. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58875. _this._shaderPath = shaderPath;
  58876. options.needAlphaBlending = options.needAlphaBlending || false;
  58877. options.needAlphaTesting = options.needAlphaTesting || false;
  58878. options.attributes = options.attributes || ["position", "normal", "uv"];
  58879. options.uniforms = options.uniforms || ["worldViewProjection"];
  58880. options.uniformBuffers = options.uniformBuffers || [];
  58881. options.samplers = options.samplers || [];
  58882. options.defines = options.defines || [];
  58883. _this._options = options;
  58884. return _this;
  58885. }
  58886. ShaderMaterial.prototype.getClassName = function () {
  58887. return "ShaderMaterial";
  58888. };
  58889. ShaderMaterial.prototype.needAlphaBlending = function () {
  58890. return this._options.needAlphaBlending;
  58891. };
  58892. ShaderMaterial.prototype.needAlphaTesting = function () {
  58893. return this._options.needAlphaTesting;
  58894. };
  58895. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58896. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58897. this._options.uniforms.push(uniformName);
  58898. }
  58899. };
  58900. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58901. if (this._options.samplers.indexOf(name) === -1) {
  58902. this._options.samplers.push(name);
  58903. }
  58904. this._textures[name] = texture;
  58905. return this;
  58906. };
  58907. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58908. if (this._options.samplers.indexOf(name) === -1) {
  58909. this._options.samplers.push(name);
  58910. }
  58911. this._checkUniform(name);
  58912. this._textureArrays[name] = textures;
  58913. return this;
  58914. };
  58915. ShaderMaterial.prototype.setFloat = function (name, value) {
  58916. this._checkUniform(name);
  58917. this._floats[name] = value;
  58918. return this;
  58919. };
  58920. ShaderMaterial.prototype.setInt = function (name, value) {
  58921. this._checkUniform(name);
  58922. this._ints[name] = value;
  58923. return this;
  58924. };
  58925. ShaderMaterial.prototype.setFloats = function (name, value) {
  58926. this._checkUniform(name);
  58927. this._floatsArrays[name] = value;
  58928. return this;
  58929. };
  58930. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58931. this._checkUniform(name);
  58932. this._colors3[name] = value;
  58933. return this;
  58934. };
  58935. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58936. this._checkUniform(name);
  58937. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58938. color.toArray(arr, arr.length);
  58939. return arr;
  58940. }, []);
  58941. return this;
  58942. };
  58943. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58944. this._checkUniform(name);
  58945. this._colors4[name] = value;
  58946. return this;
  58947. };
  58948. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58949. this._checkUniform(name);
  58950. this._vectors2[name] = value;
  58951. return this;
  58952. };
  58953. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58954. this._checkUniform(name);
  58955. this._vectors3[name] = value;
  58956. return this;
  58957. };
  58958. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58959. this._checkUniform(name);
  58960. this._vectors4[name] = value;
  58961. return this;
  58962. };
  58963. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58964. this._checkUniform(name);
  58965. this._matrices[name] = value;
  58966. return this;
  58967. };
  58968. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58969. this._checkUniform(name);
  58970. this._matrices3x3[name] = value;
  58971. return this;
  58972. };
  58973. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58974. this._checkUniform(name);
  58975. this._matrices2x2[name] = value;
  58976. return this;
  58977. };
  58978. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58979. this._checkUniform(name);
  58980. this._vectors2Arrays[name] = value;
  58981. return this;
  58982. };
  58983. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58984. this._checkUniform(name);
  58985. this._vectors3Arrays[name] = value;
  58986. return this;
  58987. };
  58988. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58989. if (!mesh) {
  58990. return true;
  58991. }
  58992. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58993. return false;
  58994. }
  58995. return false;
  58996. };
  58997. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58998. var scene = this.getScene();
  58999. var engine = scene.getEngine();
  59000. if (!this.checkReadyOnEveryCall) {
  59001. if (this._renderId === scene.getRenderId()) {
  59002. if (this._checkCache(scene, mesh, useInstances)) {
  59003. return true;
  59004. }
  59005. }
  59006. }
  59007. // Instances
  59008. var defines = [];
  59009. var attribs = [];
  59010. var fallbacks = new BABYLON.EffectFallbacks();
  59011. if (useInstances) {
  59012. defines.push("#define INSTANCES");
  59013. }
  59014. for (var index = 0; index < this._options.defines.length; index++) {
  59015. defines.push(this._options.defines[index]);
  59016. }
  59017. for (var index = 0; index < this._options.attributes.length; index++) {
  59018. attribs.push(this._options.attributes[index]);
  59019. }
  59020. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59021. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59022. defines.push("#define VERTEXCOLOR");
  59023. }
  59024. // Bones
  59025. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59026. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59027. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59028. if (mesh.numBoneInfluencers > 4) {
  59029. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59030. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59031. }
  59032. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59033. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59034. fallbacks.addCPUSkinningFallback(0, mesh);
  59035. if (this._options.uniforms.indexOf("mBones") === -1) {
  59036. this._options.uniforms.push("mBones");
  59037. }
  59038. }
  59039. else {
  59040. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59041. }
  59042. // Textures
  59043. for (var name in this._textures) {
  59044. if (!this._textures[name].isReady()) {
  59045. return false;
  59046. }
  59047. }
  59048. // Alpha test
  59049. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59050. defines.push("#define ALPHATEST");
  59051. }
  59052. var previousEffect = this._effect;
  59053. var join = defines.join("\n");
  59054. this._effect = engine.createEffect(this._shaderPath, {
  59055. attributes: attribs,
  59056. uniformsNames: this._options.uniforms,
  59057. uniformBuffersNames: this._options.uniformBuffers,
  59058. samplers: this._options.samplers,
  59059. defines: join,
  59060. fallbacks: fallbacks,
  59061. onCompiled: this.onCompiled,
  59062. onError: this.onError
  59063. }, engine);
  59064. if (!this._effect.isReady()) {
  59065. return false;
  59066. }
  59067. if (previousEffect !== this._effect) {
  59068. scene.resetCachedMaterial();
  59069. }
  59070. this._renderId = scene.getRenderId();
  59071. return true;
  59072. };
  59073. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59074. var scene = this.getScene();
  59075. if (!this._effect) {
  59076. return;
  59077. }
  59078. if (this._options.uniforms.indexOf("world") !== -1) {
  59079. this._effect.setMatrix("world", world);
  59080. }
  59081. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59082. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59083. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59084. }
  59085. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59086. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59087. }
  59088. };
  59089. ShaderMaterial.prototype.bind = function (world, mesh) {
  59090. // Std values
  59091. this.bindOnlyWorldMatrix(world);
  59092. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59093. if (this._options.uniforms.indexOf("view") !== -1) {
  59094. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59095. }
  59096. if (this._options.uniforms.indexOf("projection") !== -1) {
  59097. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59098. }
  59099. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59100. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59101. }
  59102. // Bones
  59103. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59104. var name;
  59105. // Texture
  59106. for (name in this._textures) {
  59107. this._effect.setTexture(name, this._textures[name]);
  59108. }
  59109. // Texture arrays
  59110. for (name in this._textureArrays) {
  59111. this._effect.setTextureArray(name, this._textureArrays[name]);
  59112. }
  59113. // Int
  59114. for (name in this._ints) {
  59115. this._effect.setInt(name, this._ints[name]);
  59116. }
  59117. // Float
  59118. for (name in this._floats) {
  59119. this._effect.setFloat(name, this._floats[name]);
  59120. }
  59121. // Floats
  59122. for (name in this._floatsArrays) {
  59123. this._effect.setArray(name, this._floatsArrays[name]);
  59124. }
  59125. // Color3
  59126. for (name in this._colors3) {
  59127. this._effect.setColor3(name, this._colors3[name]);
  59128. }
  59129. for (name in this._colors3Arrays) {
  59130. this._effect.setArray3(name, this._colors3Arrays[name]);
  59131. }
  59132. // Color4
  59133. for (name in this._colors4) {
  59134. var color = this._colors4[name];
  59135. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59136. }
  59137. // Vector2
  59138. for (name in this._vectors2) {
  59139. this._effect.setVector2(name, this._vectors2[name]);
  59140. }
  59141. // Vector3
  59142. for (name in this._vectors3) {
  59143. this._effect.setVector3(name, this._vectors3[name]);
  59144. }
  59145. // Vector4
  59146. for (name in this._vectors4) {
  59147. this._effect.setVector4(name, this._vectors4[name]);
  59148. }
  59149. // Matrix
  59150. for (name in this._matrices) {
  59151. this._effect.setMatrix(name, this._matrices[name]);
  59152. }
  59153. // Matrix 3x3
  59154. for (name in this._matrices3x3) {
  59155. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59156. }
  59157. // Matrix 2x2
  59158. for (name in this._matrices2x2) {
  59159. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59160. }
  59161. // Vector2Array
  59162. for (name in this._vectors2Arrays) {
  59163. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59164. }
  59165. // Vector3Array
  59166. for (name in this._vectors3Arrays) {
  59167. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59168. }
  59169. }
  59170. this._afterBind(mesh);
  59171. };
  59172. ShaderMaterial.prototype.getActiveTextures = function () {
  59173. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59174. for (var name in this._textures) {
  59175. activeTextures.push(this._textures[name]);
  59176. }
  59177. for (var name in this._textureArrays) {
  59178. var array = this._textureArrays[name];
  59179. for (var index = 0; index < array.length; index++) {
  59180. activeTextures.push(array[index]);
  59181. }
  59182. }
  59183. return activeTextures;
  59184. };
  59185. ShaderMaterial.prototype.hasTexture = function (texture) {
  59186. if (_super.prototype.hasTexture.call(this, texture)) {
  59187. return true;
  59188. }
  59189. for (var name in this._textures) {
  59190. if (this._textures[name] === texture) {
  59191. return true;
  59192. }
  59193. }
  59194. for (var name in this._textureArrays) {
  59195. var array = this._textureArrays[name];
  59196. for (var index = 0; index < array.length; index++) {
  59197. if (array[index] === texture) {
  59198. return true;
  59199. }
  59200. }
  59201. }
  59202. return false;
  59203. };
  59204. ShaderMaterial.prototype.clone = function (name) {
  59205. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59206. return newShaderMaterial;
  59207. };
  59208. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59209. if (forceDisposeTextures) {
  59210. var name;
  59211. for (name in this._textures) {
  59212. this._textures[name].dispose();
  59213. }
  59214. for (name in this._textureArrays) {
  59215. var array = this._textureArrays[name];
  59216. for (var index = 0; index < array.length; index++) {
  59217. array[index].dispose();
  59218. }
  59219. }
  59220. }
  59221. this._textures = {};
  59222. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59223. };
  59224. ShaderMaterial.prototype.serialize = function () {
  59225. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59226. serializationObject.customType = "BABYLON.ShaderMaterial";
  59227. serializationObject.options = this._options;
  59228. serializationObject.shaderPath = this._shaderPath;
  59229. var name;
  59230. // Texture
  59231. serializationObject.textures = {};
  59232. for (name in this._textures) {
  59233. serializationObject.textures[name] = this._textures[name].serialize();
  59234. }
  59235. // Texture arrays
  59236. serializationObject.textureArrays = {};
  59237. for (name in this._textureArrays) {
  59238. serializationObject.textureArrays[name] = [];
  59239. var array = this._textureArrays[name];
  59240. for (var index = 0; index < array.length; index++) {
  59241. serializationObject.textureArrays[name].push(array[index].serialize());
  59242. }
  59243. }
  59244. // Float
  59245. serializationObject.floats = {};
  59246. for (name in this._floats) {
  59247. serializationObject.floats[name] = this._floats[name];
  59248. }
  59249. // Float s
  59250. serializationObject.FloatArrays = {};
  59251. for (name in this._floatsArrays) {
  59252. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59253. }
  59254. // Color3
  59255. serializationObject.colors3 = {};
  59256. for (name in this._colors3) {
  59257. serializationObject.colors3[name] = this._colors3[name].asArray();
  59258. }
  59259. // Color3 array
  59260. serializationObject.colors3Arrays = {};
  59261. for (name in this._colors3Arrays) {
  59262. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59263. }
  59264. // Color4
  59265. serializationObject.colors4 = {};
  59266. for (name in this._colors4) {
  59267. serializationObject.colors4[name] = this._colors4[name].asArray();
  59268. }
  59269. // Vector2
  59270. serializationObject.vectors2 = {};
  59271. for (name in this._vectors2) {
  59272. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59273. }
  59274. // Vector3
  59275. serializationObject.vectors3 = {};
  59276. for (name in this._vectors3) {
  59277. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59278. }
  59279. // Vector4
  59280. serializationObject.vectors4 = {};
  59281. for (name in this._vectors4) {
  59282. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59283. }
  59284. // Matrix
  59285. serializationObject.matrices = {};
  59286. for (name in this._matrices) {
  59287. serializationObject.matrices[name] = this._matrices[name].asArray();
  59288. }
  59289. // Matrix 3x3
  59290. serializationObject.matrices3x3 = {};
  59291. for (name in this._matrices3x3) {
  59292. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59293. }
  59294. // Matrix 2x2
  59295. serializationObject.matrices2x2 = {};
  59296. for (name in this._matrices2x2) {
  59297. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59298. }
  59299. // Vector2Array
  59300. serializationObject.vectors2Arrays = {};
  59301. for (name in this._vectors2Arrays) {
  59302. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59303. }
  59304. // Vector3Array
  59305. serializationObject.vectors3Arrays = {};
  59306. for (name in this._vectors3Arrays) {
  59307. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59308. }
  59309. return serializationObject;
  59310. };
  59311. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59312. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59313. var name;
  59314. // Texture
  59315. for (name in source.textures) {
  59316. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59317. }
  59318. // Texture arrays
  59319. for (name in source.textureArrays) {
  59320. var array = source.textureArrays[name];
  59321. var textureArray = new Array();
  59322. for (var index = 0; index < array.length; index++) {
  59323. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59324. }
  59325. material.setTextureArray(name, textureArray);
  59326. }
  59327. // Float
  59328. for (name in source.floats) {
  59329. material.setFloat(name, source.floats[name]);
  59330. }
  59331. // Float s
  59332. for (name in source.floatsArrays) {
  59333. material.setFloats(name, source.floatsArrays[name]);
  59334. }
  59335. // Color3
  59336. for (name in source.colors3) {
  59337. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59338. }
  59339. // Color3 arrays
  59340. for (name in source.colors3Arrays) {
  59341. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59342. if (i % 3 === 0) {
  59343. arr.push([num]);
  59344. }
  59345. else {
  59346. arr[arr.length - 1].push(num);
  59347. }
  59348. return arr;
  59349. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59350. material.setColor3Array(name, colors);
  59351. }
  59352. // Color4
  59353. for (name in source.colors4) {
  59354. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59355. }
  59356. // Vector2
  59357. for (name in source.vectors2) {
  59358. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59359. }
  59360. // Vector3
  59361. for (name in source.vectors3) {
  59362. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59363. }
  59364. // Vector4
  59365. for (name in source.vectors4) {
  59366. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59367. }
  59368. // Matrix
  59369. for (name in source.matrices) {
  59370. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59371. }
  59372. // Matrix 3x3
  59373. for (name in source.matrices3x3) {
  59374. material.setMatrix3x3(name, source.matrices3x3[name]);
  59375. }
  59376. // Matrix 2x2
  59377. for (name in source.matrices2x2) {
  59378. material.setMatrix2x2(name, source.matrices2x2[name]);
  59379. }
  59380. // Vector2Array
  59381. for (name in source.vectors2Arrays) {
  59382. material.setArray2(name, source.vectors2Arrays[name]);
  59383. }
  59384. // Vector3Array
  59385. for (name in source.vectors3Arrays) {
  59386. material.setArray3(name, source.vectors3Arrays[name]);
  59387. }
  59388. return material;
  59389. };
  59390. return ShaderMaterial;
  59391. }(BABYLON.Material));
  59392. BABYLON.ShaderMaterial = ShaderMaterial;
  59393. })(BABYLON || (BABYLON = {}));
  59394. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59395. var BABYLON;
  59396. (function (BABYLON) {
  59397. var GroundMesh = /** @class */ (function (_super) {
  59398. __extends(GroundMesh, _super);
  59399. function GroundMesh(name, scene) {
  59400. var _this = _super.call(this, name, scene) || this;
  59401. _this.generateOctree = false;
  59402. return _this;
  59403. }
  59404. GroundMesh.prototype.getClassName = function () {
  59405. return "GroundMesh";
  59406. };
  59407. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59408. get: function () {
  59409. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59410. },
  59411. enumerable: true,
  59412. configurable: true
  59413. });
  59414. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59415. get: function () {
  59416. return this._subdivisionsX;
  59417. },
  59418. enumerable: true,
  59419. configurable: true
  59420. });
  59421. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59422. get: function () {
  59423. return this._subdivisionsY;
  59424. },
  59425. enumerable: true,
  59426. configurable: true
  59427. });
  59428. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59429. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59430. this._subdivisionsX = chunksCount;
  59431. this._subdivisionsY = chunksCount;
  59432. this.subdivide(chunksCount);
  59433. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59434. };
  59435. /**
  59436. * Returns a height (y) value in the Worl system :
  59437. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59438. * Returns the ground y position if (x, z) are outside the ground surface.
  59439. */
  59440. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59441. var world = this.getWorldMatrix();
  59442. var invMat = BABYLON.Tmp.Matrix[5];
  59443. world.invertToRef(invMat);
  59444. var tmpVect = BABYLON.Tmp.Vector3[8];
  59445. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59446. x = tmpVect.x;
  59447. z = tmpVect.z;
  59448. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59449. return this.position.y;
  59450. }
  59451. if (!this._heightQuads || this._heightQuads.length == 0) {
  59452. this._initHeightQuads();
  59453. this._computeHeightQuads();
  59454. }
  59455. var facet = this._getFacetAt(x, z);
  59456. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59457. // return y in the World system
  59458. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59459. return tmpVect.y;
  59460. };
  59461. /**
  59462. * Returns a normalized vector (Vector3) orthogonal to the ground
  59463. * at the ground coordinates (x, z) expressed in the World system.
  59464. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59465. */
  59466. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59467. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59468. this.getNormalAtCoordinatesToRef(x, z, normal);
  59469. return normal;
  59470. };
  59471. /**
  59472. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59473. * at the ground coordinates (x, z) expressed in the World system.
  59474. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59475. * Returns the GroundMesh.
  59476. */
  59477. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59478. var world = this.getWorldMatrix();
  59479. var tmpMat = BABYLON.Tmp.Matrix[5];
  59480. world.invertToRef(tmpMat);
  59481. var tmpVect = BABYLON.Tmp.Vector3[8];
  59482. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59483. x = tmpVect.x;
  59484. z = tmpVect.z;
  59485. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59486. return this;
  59487. }
  59488. if (!this._heightQuads || this._heightQuads.length == 0) {
  59489. this._initHeightQuads();
  59490. this._computeHeightQuads();
  59491. }
  59492. var facet = this._getFacetAt(x, z);
  59493. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59494. return this;
  59495. };
  59496. /**
  59497. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59498. * if the ground has been updated.
  59499. * This can be used in the render loop.
  59500. * Returns the GroundMesh.
  59501. */
  59502. GroundMesh.prototype.updateCoordinateHeights = function () {
  59503. if (!this._heightQuads || this._heightQuads.length == 0) {
  59504. this._initHeightQuads();
  59505. }
  59506. this._computeHeightQuads();
  59507. return this;
  59508. };
  59509. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59510. GroundMesh.prototype._getFacetAt = function (x, z) {
  59511. // retrieve col and row from x, z coordinates in the ground local system
  59512. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59513. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59514. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59515. var facet;
  59516. if (z < quad.slope.x * x + quad.slope.y) {
  59517. facet = quad.facet1;
  59518. }
  59519. else {
  59520. facet = quad.facet2;
  59521. }
  59522. return facet;
  59523. };
  59524. // Creates and populates the heightMap array with "facet" elements :
  59525. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59526. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59527. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59528. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59529. // Returns the GroundMesh.
  59530. GroundMesh.prototype._initHeightQuads = function () {
  59531. var subdivisionsX = this._subdivisionsX;
  59532. var subdivisionsY = this._subdivisionsY;
  59533. this._heightQuads = new Array();
  59534. for (var row = 0; row < subdivisionsY; row++) {
  59535. for (var col = 0; col < subdivisionsX; col++) {
  59536. 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) };
  59537. this._heightQuads[row * subdivisionsX + col] = quad;
  59538. }
  59539. }
  59540. return this;
  59541. };
  59542. // Compute each quad element values and update the the heightMap array :
  59543. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59544. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59545. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59546. // Returns the GroundMesh.
  59547. GroundMesh.prototype._computeHeightQuads = function () {
  59548. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59549. if (!positions) {
  59550. return this;
  59551. }
  59552. var v1 = BABYLON.Tmp.Vector3[3];
  59553. var v2 = BABYLON.Tmp.Vector3[2];
  59554. var v3 = BABYLON.Tmp.Vector3[1];
  59555. var v4 = BABYLON.Tmp.Vector3[0];
  59556. var v1v2 = BABYLON.Tmp.Vector3[4];
  59557. var v1v3 = BABYLON.Tmp.Vector3[5];
  59558. var v1v4 = BABYLON.Tmp.Vector3[6];
  59559. var norm1 = BABYLON.Tmp.Vector3[7];
  59560. var norm2 = BABYLON.Tmp.Vector3[8];
  59561. var i = 0;
  59562. var j = 0;
  59563. var k = 0;
  59564. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59565. var h = 0;
  59566. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59567. var d2 = 0;
  59568. var subdivisionsX = this._subdivisionsX;
  59569. var subdivisionsY = this._subdivisionsY;
  59570. for (var row = 0; row < subdivisionsY; row++) {
  59571. for (var col = 0; col < subdivisionsX; col++) {
  59572. i = col * 3;
  59573. j = row * (subdivisionsX + 1) * 3;
  59574. k = (row + 1) * (subdivisionsX + 1) * 3;
  59575. v1.x = positions[j + i];
  59576. v1.y = positions[j + i + 1];
  59577. v1.z = positions[j + i + 2];
  59578. v2.x = positions[j + i + 3];
  59579. v2.y = positions[j + i + 4];
  59580. v2.z = positions[j + i + 5];
  59581. v3.x = positions[k + i];
  59582. v3.y = positions[k + i + 1];
  59583. v3.z = positions[k + i + 2];
  59584. v4.x = positions[k + i + 3];
  59585. v4.y = positions[k + i + 4];
  59586. v4.z = positions[k + i + 5];
  59587. // 2D slope V1V4
  59588. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59589. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59590. // facet equations :
  59591. // we compute each facet normal vector
  59592. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59593. // we compute the value d by applying the equation to v1 which belongs to the plane
  59594. // then we store the facet equation in a Vector4
  59595. v2.subtractToRef(v1, v1v2);
  59596. v3.subtractToRef(v1, v1v3);
  59597. v4.subtractToRef(v1, v1v4);
  59598. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59599. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59600. norm1.normalize();
  59601. norm2.normalize();
  59602. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59603. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59604. var quad = this._heightQuads[row * subdivisionsX + col];
  59605. quad.slope.copyFromFloats(cd, h);
  59606. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59607. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59608. }
  59609. }
  59610. return this;
  59611. };
  59612. GroundMesh.prototype.serialize = function (serializationObject) {
  59613. _super.prototype.serialize.call(this, serializationObject);
  59614. serializationObject.subdivisionsX = this._subdivisionsX;
  59615. serializationObject.subdivisionsY = this._subdivisionsY;
  59616. serializationObject.minX = this._minX;
  59617. serializationObject.maxX = this._maxX;
  59618. serializationObject.minZ = this._minZ;
  59619. serializationObject.maxZ = this._maxZ;
  59620. serializationObject.width = this._width;
  59621. serializationObject.height = this._height;
  59622. };
  59623. GroundMesh.Parse = function (parsedMesh, scene) {
  59624. var result = new GroundMesh(parsedMesh.name, scene);
  59625. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59626. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59627. result._minX = parsedMesh.minX;
  59628. result._maxX = parsedMesh.maxX;
  59629. result._minZ = parsedMesh.minZ;
  59630. result._maxZ = parsedMesh.maxZ;
  59631. result._width = parsedMesh.width;
  59632. result._height = parsedMesh.height;
  59633. return result;
  59634. };
  59635. return GroundMesh;
  59636. }(BABYLON.Mesh));
  59637. BABYLON.GroundMesh = GroundMesh;
  59638. })(BABYLON || (BABYLON = {}));
  59639. //# sourceMappingURL=babylon.groundMesh.js.map
  59640. var BABYLON;
  59641. (function (BABYLON) {
  59642. /**
  59643. * Creates an instance based on a source mesh.
  59644. */
  59645. var InstancedMesh = /** @class */ (function (_super) {
  59646. __extends(InstancedMesh, _super);
  59647. function InstancedMesh(name, source) {
  59648. var _this = _super.call(this, name, source.getScene()) || this;
  59649. source.instances.push(_this);
  59650. _this._sourceMesh = source;
  59651. _this.position.copyFrom(source.position);
  59652. _this.rotation.copyFrom(source.rotation);
  59653. _this.scaling.copyFrom(source.scaling);
  59654. if (source.rotationQuaternion) {
  59655. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59656. }
  59657. _this.infiniteDistance = source.infiniteDistance;
  59658. _this.setPivotMatrix(source.getPivotMatrix());
  59659. _this.refreshBoundingInfo();
  59660. _this._syncSubMeshes();
  59661. return _this;
  59662. }
  59663. /**
  59664. * Returns the string "InstancedMesh".
  59665. */
  59666. InstancedMesh.prototype.getClassName = function () {
  59667. return "InstancedMesh";
  59668. };
  59669. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59670. // Methods
  59671. get: function () {
  59672. return this._sourceMesh.receiveShadows;
  59673. },
  59674. enumerable: true,
  59675. configurable: true
  59676. });
  59677. Object.defineProperty(InstancedMesh.prototype, "material", {
  59678. get: function () {
  59679. return this._sourceMesh.material;
  59680. },
  59681. enumerable: true,
  59682. configurable: true
  59683. });
  59684. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59685. get: function () {
  59686. return this._sourceMesh.visibility;
  59687. },
  59688. enumerable: true,
  59689. configurable: true
  59690. });
  59691. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59692. get: function () {
  59693. return this._sourceMesh.skeleton;
  59694. },
  59695. enumerable: true,
  59696. configurable: true
  59697. });
  59698. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59699. get: function () {
  59700. return this._sourceMesh.renderingGroupId;
  59701. },
  59702. set: function (value) {
  59703. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59704. return;
  59705. }
  59706. //no-op with warning
  59707. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59708. },
  59709. enumerable: true,
  59710. configurable: true
  59711. });
  59712. /**
  59713. * Returns the total number of vertices (integer).
  59714. */
  59715. InstancedMesh.prototype.getTotalVertices = function () {
  59716. return this._sourceMesh.getTotalVertices();
  59717. };
  59718. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59719. get: function () {
  59720. return this._sourceMesh;
  59721. },
  59722. enumerable: true,
  59723. configurable: true
  59724. });
  59725. /**
  59726. * Is this node ready to be used/rendered
  59727. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59728. * @return {boolean} is it ready
  59729. */
  59730. InstancedMesh.prototype.isReady = function (completeCheck) {
  59731. if (completeCheck === void 0) { completeCheck = false; }
  59732. return this._sourceMesh.isReady(completeCheck, true);
  59733. };
  59734. /**
  59735. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59736. */
  59737. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59738. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59739. };
  59740. /**
  59741. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59742. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59743. * The `data` are either a numeric array either a Float32Array.
  59744. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59745. * 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).
  59746. * Note that a new underlying VertexBuffer object is created each call.
  59747. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59748. *
  59749. * Possible `kind` values :
  59750. * - BABYLON.VertexBuffer.PositionKind
  59751. * - BABYLON.VertexBuffer.UVKind
  59752. * - BABYLON.VertexBuffer.UV2Kind
  59753. * - BABYLON.VertexBuffer.UV3Kind
  59754. * - BABYLON.VertexBuffer.UV4Kind
  59755. * - BABYLON.VertexBuffer.UV5Kind
  59756. * - BABYLON.VertexBuffer.UV6Kind
  59757. * - BABYLON.VertexBuffer.ColorKind
  59758. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59759. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59760. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59761. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59762. *
  59763. * Returns the Mesh.
  59764. */
  59765. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59766. if (this.sourceMesh) {
  59767. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59768. }
  59769. return this.sourceMesh;
  59770. };
  59771. /**
  59772. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59773. * If the mesh has no geometry, it is simply returned as it is.
  59774. * The `data` are either a numeric array either a Float32Array.
  59775. * No new underlying VertexBuffer object is created.
  59776. * 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.
  59777. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59778. *
  59779. * Possible `kind` values :
  59780. * - BABYLON.VertexBuffer.PositionKind
  59781. * - BABYLON.VertexBuffer.UVKind
  59782. * - BABYLON.VertexBuffer.UV2Kind
  59783. * - BABYLON.VertexBuffer.UV3Kind
  59784. * - BABYLON.VertexBuffer.UV4Kind
  59785. * - BABYLON.VertexBuffer.UV5Kind
  59786. * - BABYLON.VertexBuffer.UV6Kind
  59787. * - BABYLON.VertexBuffer.ColorKind
  59788. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59789. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59790. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59791. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59792. *
  59793. * Returns the Mesh.
  59794. */
  59795. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59796. if (this.sourceMesh) {
  59797. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59798. }
  59799. return this.sourceMesh;
  59800. };
  59801. /**
  59802. * Sets the mesh indices.
  59803. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59804. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59805. * This method creates a new index buffer each call.
  59806. * Returns the Mesh.
  59807. */
  59808. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59809. if (totalVertices === void 0) { totalVertices = null; }
  59810. if (this.sourceMesh) {
  59811. this.sourceMesh.setIndices(indices, totalVertices);
  59812. }
  59813. return this.sourceMesh;
  59814. };
  59815. /**
  59816. * Boolean : True if the mesh owns the requested kind of data.
  59817. */
  59818. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59819. return this._sourceMesh.isVerticesDataPresent(kind);
  59820. };
  59821. /**
  59822. * Returns an array of indices (IndicesArray).
  59823. */
  59824. InstancedMesh.prototype.getIndices = function () {
  59825. return this._sourceMesh.getIndices();
  59826. };
  59827. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59828. get: function () {
  59829. return this._sourceMesh._positions;
  59830. },
  59831. enumerable: true,
  59832. configurable: true
  59833. });
  59834. /**
  59835. * Sets a new updated BoundingInfo to the mesh.
  59836. * Returns the mesh.
  59837. */
  59838. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59839. var meshBB = this._sourceMesh.getBoundingInfo();
  59840. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59841. this._updateBoundingInfo();
  59842. return this;
  59843. };
  59844. /** @hidden */
  59845. InstancedMesh.prototype._preActivate = function () {
  59846. if (this._currentLOD) {
  59847. this._currentLOD._preActivate();
  59848. }
  59849. return this;
  59850. };
  59851. /** @hidden */
  59852. InstancedMesh.prototype._activate = function (renderId) {
  59853. if (this._currentLOD) {
  59854. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59855. }
  59856. return this;
  59857. };
  59858. /**
  59859. * Returns the current associated LOD AbstractMesh.
  59860. */
  59861. InstancedMesh.prototype.getLOD = function (camera) {
  59862. if (!camera) {
  59863. return this;
  59864. }
  59865. var boundingInfo = this.getBoundingInfo();
  59866. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59867. if (this._currentLOD === this.sourceMesh) {
  59868. return this;
  59869. }
  59870. return this._currentLOD;
  59871. };
  59872. /** @hidden */
  59873. InstancedMesh.prototype._syncSubMeshes = function () {
  59874. this.releaseSubMeshes();
  59875. if (this._sourceMesh.subMeshes) {
  59876. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59877. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59878. }
  59879. }
  59880. return this;
  59881. };
  59882. /** @hidden */
  59883. InstancedMesh.prototype._generatePointsArray = function () {
  59884. return this._sourceMesh._generatePointsArray();
  59885. };
  59886. /**
  59887. * Creates a new InstancedMesh from the current mesh.
  59888. * - name (string) : the cloned mesh name
  59889. * - newParent (optional Node) : the optional Node to parent the clone to.
  59890. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59891. *
  59892. * Returns the clone.
  59893. */
  59894. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59895. var result = this._sourceMesh.createInstance(name);
  59896. // Deep copy
  59897. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59898. // Bounding info
  59899. this.refreshBoundingInfo();
  59900. // Parent
  59901. if (newParent) {
  59902. result.parent = newParent;
  59903. }
  59904. if (!doNotCloneChildren) {
  59905. // Children
  59906. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59907. var mesh = this.getScene().meshes[index];
  59908. if (mesh.parent === this) {
  59909. mesh.clone(mesh.name, result);
  59910. }
  59911. }
  59912. }
  59913. result.computeWorldMatrix(true);
  59914. return result;
  59915. };
  59916. /**
  59917. * Disposes the InstancedMesh.
  59918. * Returns nothing.
  59919. */
  59920. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59921. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59922. // Remove from mesh
  59923. var index = this._sourceMesh.instances.indexOf(this);
  59924. this._sourceMesh.instances.splice(index, 1);
  59925. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59926. };
  59927. return InstancedMesh;
  59928. }(BABYLON.AbstractMesh));
  59929. BABYLON.InstancedMesh = InstancedMesh;
  59930. })(BABYLON || (BABYLON = {}));
  59931. //# sourceMappingURL=babylon.instancedMesh.js.map
  59932. var BABYLON;
  59933. (function (BABYLON) {
  59934. var LinesMesh = /** @class */ (function (_super) {
  59935. __extends(LinesMesh, _super);
  59936. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59937. if (scene === void 0) { scene = null; }
  59938. if (parent === void 0) { parent = null; }
  59939. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59940. _this.useVertexColor = useVertexColor;
  59941. _this.useVertexAlpha = useVertexAlpha;
  59942. _this.color = new BABYLON.Color3(1, 1, 1);
  59943. _this.alpha = 1;
  59944. if (source) {
  59945. _this.color = source.color.clone();
  59946. _this.alpha = source.alpha;
  59947. _this.useVertexColor = source.useVertexColor;
  59948. _this.useVertexAlpha = source.useVertexAlpha;
  59949. }
  59950. _this._intersectionThreshold = 0.1;
  59951. var defines = [];
  59952. var options = {
  59953. attributes: [BABYLON.VertexBuffer.PositionKind],
  59954. uniforms: ["world", "viewProjection"],
  59955. needAlphaBlending: true,
  59956. defines: defines
  59957. };
  59958. if (useVertexAlpha === false) {
  59959. options.needAlphaBlending = false;
  59960. }
  59961. if (!useVertexColor) {
  59962. options.uniforms.push("color");
  59963. }
  59964. else {
  59965. options.defines.push("#define VERTEXCOLOR");
  59966. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59967. }
  59968. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59969. return _this;
  59970. }
  59971. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59972. /**
  59973. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59974. * This margin is expressed in world space coordinates, so its value may vary.
  59975. * Default value is 0.1
  59976. * @returns the intersection Threshold value.
  59977. */
  59978. get: function () {
  59979. return this._intersectionThreshold;
  59980. },
  59981. /**
  59982. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59983. * This margin is expressed in world space coordinates, so its value may vary.
  59984. * @param value the new threshold to apply
  59985. */
  59986. set: function (value) {
  59987. if (this._intersectionThreshold === value) {
  59988. return;
  59989. }
  59990. this._intersectionThreshold = value;
  59991. if (this.geometry) {
  59992. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59993. }
  59994. },
  59995. enumerable: true,
  59996. configurable: true
  59997. });
  59998. /**
  59999. * Returns the string "LineMesh"
  60000. */
  60001. LinesMesh.prototype.getClassName = function () {
  60002. return "LinesMesh";
  60003. };
  60004. Object.defineProperty(LinesMesh.prototype, "material", {
  60005. /**
  60006. * @hidden
  60007. */
  60008. get: function () {
  60009. return this._colorShader;
  60010. },
  60011. /**
  60012. * @hidden
  60013. */
  60014. set: function (value) {
  60015. // Do nothing
  60016. },
  60017. enumerable: true,
  60018. configurable: true
  60019. });
  60020. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60021. /**
  60022. * @hidden
  60023. */
  60024. get: function () {
  60025. return false;
  60026. },
  60027. enumerable: true,
  60028. configurable: true
  60029. });
  60030. LinesMesh.prototype.createInstance = function (name) {
  60031. throw new Error("LinesMeshes do not support createInstance.");
  60032. };
  60033. /** @hidden */
  60034. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60035. if (!this._geometry) {
  60036. return this;
  60037. }
  60038. // VBOs
  60039. this._geometry._bind(this._colorShader.getEffect());
  60040. // Color
  60041. if (!this.useVertexColor) {
  60042. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60043. }
  60044. return this;
  60045. };
  60046. /** @hidden */
  60047. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60048. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60049. return this;
  60050. }
  60051. var engine = this.getScene().getEngine();
  60052. // Draw order
  60053. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60054. return this;
  60055. };
  60056. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60057. this._colorShader.dispose();
  60058. _super.prototype.dispose.call(this, doNotRecurse);
  60059. };
  60060. /**
  60061. * Returns a new LineMesh object cloned from the current one.
  60062. */
  60063. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60064. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60065. };
  60066. return LinesMesh;
  60067. }(BABYLON.Mesh));
  60068. BABYLON.LinesMesh = LinesMesh;
  60069. })(BABYLON || (BABYLON = {}));
  60070. //# sourceMappingURL=babylon.linesMesh.js.map
  60071. var BABYLON;
  60072. (function (BABYLON) {
  60073. /**
  60074. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60075. * The underlying implementation relies on an associative array to ensure the best performances.
  60076. * The value can be anything including 'null' but except 'undefined'
  60077. */
  60078. var StringDictionary = /** @class */ (function () {
  60079. function StringDictionary() {
  60080. this._count = 0;
  60081. this._data = {};
  60082. }
  60083. /**
  60084. * This will clear this dictionary and copy the content from the 'source' one.
  60085. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60086. * @param source the dictionary to take the content from and copy to this dictionary
  60087. */
  60088. StringDictionary.prototype.copyFrom = function (source) {
  60089. var _this = this;
  60090. this.clear();
  60091. source.forEach(function (t, v) { return _this.add(t, v); });
  60092. };
  60093. /**
  60094. * Get a value based from its key
  60095. * @param key the given key to get the matching value from
  60096. * @return the value if found, otherwise undefined is returned
  60097. */
  60098. StringDictionary.prototype.get = function (key) {
  60099. var val = this._data[key];
  60100. if (val !== undefined) {
  60101. return val;
  60102. }
  60103. return undefined;
  60104. };
  60105. /**
  60106. * Get a value from its key or add it if it doesn't exist.
  60107. * This method will ensure you that a given key/data will be present in the dictionary.
  60108. * @param key the given key to get the matching value from
  60109. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60110. * The factory will only be invoked if there's no data for the given key.
  60111. * @return the value corresponding to the key.
  60112. */
  60113. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60114. var val = this.get(key);
  60115. if (val !== undefined) {
  60116. return val;
  60117. }
  60118. val = factory(key);
  60119. if (val) {
  60120. this.add(key, val);
  60121. }
  60122. return val;
  60123. };
  60124. /**
  60125. * Get a value from its key if present in the dictionary otherwise add it
  60126. * @param key the key to get the value from
  60127. * @param val if there's no such key/value pair in the dictionary add it with this value
  60128. * @return the value corresponding to the key
  60129. */
  60130. StringDictionary.prototype.getOrAdd = function (key, val) {
  60131. var curVal = this.get(key);
  60132. if (curVal !== undefined) {
  60133. return curVal;
  60134. }
  60135. this.add(key, val);
  60136. return val;
  60137. };
  60138. /**
  60139. * Check if there's a given key in the dictionary
  60140. * @param key the key to check for
  60141. * @return true if the key is present, false otherwise
  60142. */
  60143. StringDictionary.prototype.contains = function (key) {
  60144. return this._data[key] !== undefined;
  60145. };
  60146. /**
  60147. * Add a new key and its corresponding value
  60148. * @param key the key to add
  60149. * @param value the value corresponding to the key
  60150. * @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
  60151. */
  60152. StringDictionary.prototype.add = function (key, value) {
  60153. if (this._data[key] !== undefined) {
  60154. return false;
  60155. }
  60156. this._data[key] = value;
  60157. ++this._count;
  60158. return true;
  60159. };
  60160. StringDictionary.prototype.set = function (key, value) {
  60161. if (this._data[key] === undefined) {
  60162. return false;
  60163. }
  60164. this._data[key] = value;
  60165. return true;
  60166. };
  60167. /**
  60168. * Get the element of the given key and remove it from the dictionary
  60169. * @param key
  60170. */
  60171. StringDictionary.prototype.getAndRemove = function (key) {
  60172. var val = this.get(key);
  60173. if (val !== undefined) {
  60174. delete this._data[key];
  60175. --this._count;
  60176. return val;
  60177. }
  60178. return null;
  60179. };
  60180. /**
  60181. * Remove a key/value from the dictionary.
  60182. * @param key the key to remove
  60183. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60184. */
  60185. StringDictionary.prototype.remove = function (key) {
  60186. if (this.contains(key)) {
  60187. delete this._data[key];
  60188. --this._count;
  60189. return true;
  60190. }
  60191. return false;
  60192. };
  60193. /**
  60194. * Clear the whole content of the dictionary
  60195. */
  60196. StringDictionary.prototype.clear = function () {
  60197. this._data = {};
  60198. this._count = 0;
  60199. };
  60200. Object.defineProperty(StringDictionary.prototype, "count", {
  60201. get: function () {
  60202. return this._count;
  60203. },
  60204. enumerable: true,
  60205. configurable: true
  60206. });
  60207. /**
  60208. * Execute a callback on each key/val of the dictionary.
  60209. * Note that you can remove any element in this dictionary in the callback implementation
  60210. * @param callback the callback to execute on a given key/value pair
  60211. */
  60212. StringDictionary.prototype.forEach = function (callback) {
  60213. for (var cur in this._data) {
  60214. var val = this._data[cur];
  60215. callback(cur, val);
  60216. }
  60217. };
  60218. /**
  60219. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60220. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60221. * Note that you can remove any element in this dictionary in the callback implementation
  60222. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60223. */
  60224. StringDictionary.prototype.first = function (callback) {
  60225. for (var cur in this._data) {
  60226. var val = this._data[cur];
  60227. var res = callback(cur, val);
  60228. if (res) {
  60229. return res;
  60230. }
  60231. }
  60232. return null;
  60233. };
  60234. return StringDictionary;
  60235. }());
  60236. BABYLON.StringDictionary = StringDictionary;
  60237. })(BABYLON || (BABYLON = {}));
  60238. //# sourceMappingURL=babylon.stringDictionary.js.map
  60239. var BABYLON;
  60240. (function (BABYLON) {
  60241. var Debug;
  60242. (function (Debug) {
  60243. /**
  60244. * Class used to render a debug view of a given skeleton
  60245. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  60246. */
  60247. var SkeletonViewer = /** @class */ (function () {
  60248. /**
  60249. * Creates a new SkeletonViewer
  60250. * @param skeleton defines the skeleton to render
  60251. * @param mesh defines the mesh attached to the skeleton
  60252. * @param scene defines the hosting scene
  60253. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  60254. * @param renderingGroupId defines the rendering group id to use with the viewer
  60255. */
  60256. function SkeletonViewer(
  60257. /** defines the skeleton to render */
  60258. skeleton,
  60259. /** defines the mesh attached to the skeleton */
  60260. mesh, scene,
  60261. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  60262. autoUpdateBonesMatrices,
  60263. /** defines the rendering group id to use with the viewer */
  60264. renderingGroupId) {
  60265. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60266. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60267. this.skeleton = skeleton;
  60268. this.mesh = mesh;
  60269. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60270. this.renderingGroupId = renderingGroupId;
  60271. /** Gets or sets the color used to render the skeleton */
  60272. this.color = BABYLON.Color3.White();
  60273. this._debugLines = new Array();
  60274. this._isEnabled = false;
  60275. this._scene = scene;
  60276. this.update();
  60277. this._renderFunction = this.update.bind(this);
  60278. }
  60279. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60280. get: function () {
  60281. return this._isEnabled;
  60282. },
  60283. /** Gets or sets a boolean indicating if the viewer is enabled */
  60284. set: function (value) {
  60285. if (this._isEnabled === value) {
  60286. return;
  60287. }
  60288. this._isEnabled = value;
  60289. if (value) {
  60290. this._scene.registerBeforeRender(this._renderFunction);
  60291. }
  60292. else {
  60293. this._scene.unregisterBeforeRender(this._renderFunction);
  60294. }
  60295. },
  60296. enumerable: true,
  60297. configurable: true
  60298. });
  60299. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60300. if (x === void 0) { x = 0; }
  60301. if (y === void 0) { y = 0; }
  60302. if (z === void 0) { z = 0; }
  60303. var tmat = BABYLON.Tmp.Matrix[0];
  60304. var parentBone = bone.getParent();
  60305. tmat.copyFrom(bone.getLocalMatrix());
  60306. if (x !== 0 || y !== 0 || z !== 0) {
  60307. var tmat2 = BABYLON.Tmp.Matrix[1];
  60308. BABYLON.Matrix.IdentityToRef(tmat2);
  60309. tmat2.m[12] = x;
  60310. tmat2.m[13] = y;
  60311. tmat2.m[14] = z;
  60312. tmat2.multiplyToRef(tmat, tmat);
  60313. }
  60314. if (parentBone) {
  60315. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60316. }
  60317. tmat.multiplyToRef(meshMat, tmat);
  60318. position.x = tmat.m[12];
  60319. position.y = tmat.m[13];
  60320. position.z = tmat.m[14];
  60321. };
  60322. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60323. var len = bones.length;
  60324. var meshPos = this.mesh.position;
  60325. for (var i = 0; i < len; i++) {
  60326. var bone = bones[i];
  60327. var points = this._debugLines[i];
  60328. if (!points) {
  60329. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60330. this._debugLines[i] = points;
  60331. }
  60332. this._getBonePosition(points[0], bone, meshMat);
  60333. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60334. points[0].subtractInPlace(meshPos);
  60335. points[1].subtractInPlace(meshPos);
  60336. }
  60337. };
  60338. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60339. var len = bones.length;
  60340. var boneNum = 0;
  60341. var meshPos = this.mesh.position;
  60342. for (var i = len - 1; i >= 0; i--) {
  60343. var childBone = bones[i];
  60344. var parentBone = childBone.getParent();
  60345. if (!parentBone) {
  60346. continue;
  60347. }
  60348. var points = this._debugLines[boneNum];
  60349. if (!points) {
  60350. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60351. this._debugLines[boneNum] = points;
  60352. }
  60353. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  60354. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  60355. points[0].subtractInPlace(meshPos);
  60356. points[1].subtractInPlace(meshPos);
  60357. boneNum++;
  60358. }
  60359. };
  60360. /** Update the viewer to sync with current skeleton state */
  60361. SkeletonViewer.prototype.update = function () {
  60362. if (this.autoUpdateBonesMatrices) {
  60363. this.skeleton.computeAbsoluteTransforms();
  60364. }
  60365. if (this.skeleton.bones[0].length === undefined) {
  60366. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60367. }
  60368. else {
  60369. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60370. }
  60371. if (!this._debugMesh) {
  60372. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  60373. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60374. }
  60375. else {
  60376. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60377. }
  60378. this._debugMesh.position.copyFrom(this.mesh.position);
  60379. this._debugMesh.color = this.color;
  60380. };
  60381. /** Release associated resources */
  60382. SkeletonViewer.prototype.dispose = function () {
  60383. if (this._debugMesh) {
  60384. this.isEnabled = false;
  60385. this._debugMesh.dispose();
  60386. this._debugMesh = null;
  60387. }
  60388. };
  60389. return SkeletonViewer;
  60390. }());
  60391. Debug.SkeletonViewer = SkeletonViewer;
  60392. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60393. })(BABYLON || (BABYLON = {}));
  60394. //# sourceMappingURL=babylon.skeletonViewer.js.map
  60395. /**
  60396. * Module Debug contains the (visual) components to debug a scene correctly
  60397. */
  60398. var BABYLON;
  60399. (function (BABYLON) {
  60400. var Debug;
  60401. (function (Debug) {
  60402. /**
  60403. * The Axes viewer will show 3 axes in a specific point in space
  60404. */
  60405. var AxesViewer = /** @class */ (function () {
  60406. /**
  60407. * Creates a new AxesViewer
  60408. * @param scene defines the hosting scene
  60409. * @param scaleLines defines a number used to scale line length (1 by default)
  60410. */
  60411. function AxesViewer(scene, scaleLines) {
  60412. if (scaleLines === void 0) { scaleLines = 1; }
  60413. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60414. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60415. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60416. /**
  60417. * Gets or sets a number used to scale line length
  60418. */
  60419. this.scaleLines = 1;
  60420. this.scaleLines = scaleLines;
  60421. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  60422. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  60423. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  60424. this._xmesh.renderingGroupId = 2;
  60425. this._ymesh.renderingGroupId = 2;
  60426. this._zmesh.renderingGroupId = 2;
  60427. this._xmesh.material.checkReadyOnlyOnce = true;
  60428. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60429. this._ymesh.material.checkReadyOnlyOnce = true;
  60430. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60431. this._zmesh.material.checkReadyOnlyOnce = true;
  60432. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60433. this.scene = scene;
  60434. }
  60435. /**
  60436. * Force the viewer to update
  60437. * @param position defines the position of the viewer
  60438. * @param xaxis defines the x axis of the viewer
  60439. * @param yaxis defines the y axis of the viewer
  60440. * @param zaxis defines the z axis of the viewer
  60441. */
  60442. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60443. var scaleLines = this.scaleLines;
  60444. if (this._xmesh) {
  60445. this._xmesh.position.copyFrom(position);
  60446. }
  60447. if (this._ymesh) {
  60448. this._ymesh.position.copyFrom(position);
  60449. }
  60450. if (this._zmesh) {
  60451. this._zmesh.position.copyFrom(position);
  60452. }
  60453. var point2 = this._xline[1];
  60454. point2.x = xaxis.x * scaleLines;
  60455. point2.y = xaxis.y * scaleLines;
  60456. point2.z = xaxis.z * scaleLines;
  60457. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  60458. point2 = this._yline[1];
  60459. point2.x = yaxis.x * scaleLines;
  60460. point2.y = yaxis.y * scaleLines;
  60461. point2.z = yaxis.z * scaleLines;
  60462. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  60463. point2 = this._zline[1];
  60464. point2.x = zaxis.x * scaleLines;
  60465. point2.y = zaxis.y * scaleLines;
  60466. point2.z = zaxis.z * scaleLines;
  60467. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  60468. };
  60469. /** Releases resources */
  60470. AxesViewer.prototype.dispose = function () {
  60471. if (this._xmesh) {
  60472. this._xmesh.dispose();
  60473. }
  60474. if (this._ymesh) {
  60475. this._ymesh.dispose();
  60476. }
  60477. if (this._zmesh) {
  60478. this._zmesh.dispose();
  60479. }
  60480. this._xmesh = null;
  60481. this._ymesh = null;
  60482. this._zmesh = null;
  60483. this.scene = null;
  60484. };
  60485. return AxesViewer;
  60486. }());
  60487. Debug.AxesViewer = AxesViewer;
  60488. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60489. })(BABYLON || (BABYLON = {}));
  60490. //# sourceMappingURL=babylon.axesViewer.js.map
  60491. var BABYLON;
  60492. (function (BABYLON) {
  60493. var Debug;
  60494. (function (Debug) {
  60495. /**
  60496. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  60497. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  60498. */
  60499. var BoneAxesViewer = /** @class */ (function (_super) {
  60500. __extends(BoneAxesViewer, _super);
  60501. /**
  60502. * Creates a new BoneAxesViewer
  60503. * @param scene defines the hosting scene
  60504. * @param bone defines the target bone
  60505. * @param mesh defines the target mesh
  60506. * @param scaleLines defines a scaling factor for line length (1 by default)
  60507. */
  60508. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  60509. if (scaleLines === void 0) { scaleLines = 1; }
  60510. var _this = _super.call(this, scene, scaleLines) || this;
  60511. /** Gets current position */
  60512. _this.pos = BABYLON.Vector3.Zero();
  60513. /** Gets direction of X axis */
  60514. _this.xaxis = BABYLON.Vector3.Zero();
  60515. /** Gets direction of Y axis */
  60516. _this.yaxis = BABYLON.Vector3.Zero();
  60517. /** Gets direction of Z axis */
  60518. _this.zaxis = BABYLON.Vector3.Zero();
  60519. _this.mesh = mesh;
  60520. _this.bone = bone;
  60521. return _this;
  60522. }
  60523. /**
  60524. * Force the viewer to update
  60525. */
  60526. BoneAxesViewer.prototype.update = function () {
  60527. if (!this.mesh || !this.bone) {
  60528. return;
  60529. }
  60530. var bone = this.bone;
  60531. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  60532. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  60533. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  60534. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  60535. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  60536. };
  60537. /** Releases resources */
  60538. BoneAxesViewer.prototype.dispose = function () {
  60539. if (this.mesh) {
  60540. this.mesh = null;
  60541. this.bone = null;
  60542. _super.prototype.dispose.call(this);
  60543. }
  60544. };
  60545. return BoneAxesViewer;
  60546. }(Debug.AxesViewer));
  60547. Debug.BoneAxesViewer = BoneAxesViewer;
  60548. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60549. })(BABYLON || (BABYLON = {}));
  60550. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  60551. var BABYLON;
  60552. (function (BABYLON) {
  60553. var RayHelper = /** @class */ (function () {
  60554. function RayHelper(ray) {
  60555. this.ray = ray;
  60556. }
  60557. RayHelper.CreateAndShow = function (ray, scene, color) {
  60558. var helper = new RayHelper(ray);
  60559. helper.show(scene, color);
  60560. return helper;
  60561. };
  60562. RayHelper.prototype.show = function (scene, color) {
  60563. if (!this._renderFunction && this.ray) {
  60564. var ray = this.ray;
  60565. this._renderFunction = this._render.bind(this);
  60566. this._scene = scene;
  60567. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  60568. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  60569. if (this._renderFunction) {
  60570. this._scene.registerBeforeRender(this._renderFunction);
  60571. }
  60572. }
  60573. if (color && this._renderLine) {
  60574. this._renderLine.color.copyFrom(color);
  60575. }
  60576. };
  60577. RayHelper.prototype.hide = function () {
  60578. if (this._renderFunction && this._scene) {
  60579. this._scene.unregisterBeforeRender(this._renderFunction);
  60580. this._scene = null;
  60581. this._renderFunction = null;
  60582. if (this._renderLine) {
  60583. this._renderLine.dispose();
  60584. this._renderLine = null;
  60585. }
  60586. this._renderPoints = [];
  60587. }
  60588. };
  60589. RayHelper.prototype._render = function () {
  60590. var ray = this.ray;
  60591. if (!ray) {
  60592. return;
  60593. }
  60594. var point = this._renderPoints[1];
  60595. var len = Math.min(ray.length, 1000000);
  60596. point.copyFrom(ray.direction);
  60597. point.scaleInPlace(len);
  60598. point.addInPlace(ray.origin);
  60599. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  60600. };
  60601. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  60602. this._attachedToMesh = mesh;
  60603. var ray = this.ray;
  60604. if (!ray) {
  60605. return;
  60606. }
  60607. if (!ray.direction) {
  60608. ray.direction = BABYLON.Vector3.Zero();
  60609. }
  60610. if (!ray.origin) {
  60611. ray.origin = BABYLON.Vector3.Zero();
  60612. }
  60613. if (length) {
  60614. ray.length = length;
  60615. }
  60616. if (!meshSpaceOrigin) {
  60617. meshSpaceOrigin = BABYLON.Vector3.Zero();
  60618. }
  60619. if (!meshSpaceDirection) {
  60620. // -1 so that this will work with Mesh.lookAt
  60621. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  60622. }
  60623. if (!this._meshSpaceDirection) {
  60624. this._meshSpaceDirection = meshSpaceDirection.clone();
  60625. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  60626. }
  60627. else {
  60628. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  60629. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  60630. }
  60631. if (!this._updateToMeshFunction) {
  60632. this._updateToMeshFunction = this._updateToMesh.bind(this);
  60633. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  60634. }
  60635. this._updateToMesh();
  60636. };
  60637. RayHelper.prototype.detachFromMesh = function () {
  60638. if (this._attachedToMesh) {
  60639. if (this._updateToMeshFunction) {
  60640. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  60641. }
  60642. this._attachedToMesh = null;
  60643. this._updateToMeshFunction = null;
  60644. }
  60645. };
  60646. RayHelper.prototype._updateToMesh = function () {
  60647. var ray = this.ray;
  60648. if (!this._attachedToMesh || !ray) {
  60649. return;
  60650. }
  60651. if (this._attachedToMesh._isDisposed) {
  60652. this.detachFromMesh();
  60653. return;
  60654. }
  60655. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  60656. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  60657. };
  60658. RayHelper.prototype.dispose = function () {
  60659. this.hide();
  60660. this.detachFromMesh();
  60661. this.ray = null;
  60662. };
  60663. return RayHelper;
  60664. }());
  60665. BABYLON.RayHelper = RayHelper;
  60666. })(BABYLON || (BABYLON = {}));
  60667. //# sourceMappingURL=babylon.rayHelper.js.map
  60668. var BABYLON;
  60669. (function (BABYLON) {
  60670. // load the inspector using require, if not present in the global namespace.
  60671. var DebugLayer = /** @class */ (function () {
  60672. function DebugLayer(scene) {
  60673. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60674. this.onPropertyChangedObservable = new BABYLON.Observable();
  60675. this._scene = scene;
  60676. }
  60677. /** Creates the inspector window. */
  60678. DebugLayer.prototype._createInspector = function (config) {
  60679. if (config === void 0) { config = {}; }
  60680. var popup = config.popup || false;
  60681. var initialTab = config.initialTab || 0;
  60682. var parentElement = config.parentElement || null;
  60683. if (!this._inspector) {
  60684. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60685. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  60686. } // else nothing to do as instance is already created
  60687. };
  60688. DebugLayer.prototype.isVisible = function () {
  60689. if (!this._inspector) {
  60690. return false;
  60691. }
  60692. return true;
  60693. };
  60694. DebugLayer.prototype.hide = function () {
  60695. if (this._inspector) {
  60696. try {
  60697. this._inspector.dispose();
  60698. }
  60699. catch (e) {
  60700. // If the inspector has been removed directly from the inspector tool
  60701. }
  60702. this.onPropertyChangedObservable.clear();
  60703. this._inspector = null;
  60704. }
  60705. };
  60706. /**
  60707. *
  60708. * Launch the debugLayer.
  60709. *
  60710. * initialTab:
  60711. * | Value | Tab Name |
  60712. * | --- | --- |
  60713. * | 0 | Scene |
  60714. * | 1 | Console |
  60715. * | 2 | Stats |
  60716. * | 3 | Textures |
  60717. * | 4 | Mesh |
  60718. * | 5 | Light |
  60719. * | 6 | Material |
  60720. * | 7 | GLTF |
  60721. * | 8 | GUI |
  60722. * | 9 | Physics |
  60723. * | 10 | Camera |
  60724. * | 11 | Audio |
  60725. *
  60726. */
  60727. DebugLayer.prototype.show = function (config) {
  60728. if (config === void 0) { config = {}; }
  60729. if (typeof this.BJSINSPECTOR == 'undefined') {
  60730. // Load inspector and add it to the DOM
  60731. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60732. }
  60733. else {
  60734. // Otherwise creates the inspector
  60735. this._createInspector(config);
  60736. }
  60737. };
  60738. /**
  60739. * Gets the active tab
  60740. * @return the index of the active tab or -1 if the inspector is hidden
  60741. */
  60742. DebugLayer.prototype.getActiveTab = function () {
  60743. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  60744. };
  60745. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  60746. return DebugLayer;
  60747. }());
  60748. BABYLON.DebugLayer = DebugLayer;
  60749. })(BABYLON || (BABYLON = {}));
  60750. //# sourceMappingURL=babylon.debugLayer.js.map
  60751. var BABYLON;
  60752. (function (BABYLON) {
  60753. var Debug;
  60754. (function (Debug) {
  60755. /**
  60756. * Used to show the physics impostor around the specific mesh
  60757. */
  60758. var PhysicsViewer = /** @class */ (function () {
  60759. /**
  60760. * Creates a new PhysicsViewer
  60761. * @param scene defines the hosting scene
  60762. */
  60763. function PhysicsViewer(scene) {
  60764. /** @hidden */
  60765. this._impostors = [];
  60766. /** @hidden */
  60767. this._meshes = [];
  60768. /** @hidden */
  60769. this._numMeshes = 0;
  60770. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60771. var physicEngine = this._scene.getPhysicsEngine();
  60772. if (physicEngine) {
  60773. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  60774. }
  60775. }
  60776. /** @hidden */
  60777. PhysicsViewer.prototype._updateDebugMeshes = function () {
  60778. var plugin = this._physicsEnginePlugin;
  60779. for (var i = 0; i < this._numMeshes; i++) {
  60780. var impostor = this._impostors[i];
  60781. if (!impostor) {
  60782. continue;
  60783. }
  60784. if (impostor.isDisposed) {
  60785. this.hideImpostor(this._impostors[i--]);
  60786. }
  60787. else {
  60788. var mesh = this._meshes[i];
  60789. if (mesh && plugin) {
  60790. plugin.syncMeshWithImpostor(mesh, impostor);
  60791. }
  60792. }
  60793. }
  60794. };
  60795. /**
  60796. * Renders a specified physic impostor
  60797. * @param impostor defines the impostor to render
  60798. */
  60799. PhysicsViewer.prototype.showImpostor = function (impostor) {
  60800. if (!this._scene) {
  60801. return;
  60802. }
  60803. for (var i = 0; i < this._numMeshes; i++) {
  60804. if (this._impostors[i] == impostor) {
  60805. return;
  60806. }
  60807. }
  60808. var debugMesh = this._getDebugMesh(impostor, this._scene);
  60809. if (debugMesh) {
  60810. this._impostors[this._numMeshes] = impostor;
  60811. this._meshes[this._numMeshes] = debugMesh;
  60812. if (this._numMeshes === 0) {
  60813. this._renderFunction = this._updateDebugMeshes.bind(this);
  60814. this._scene.registerBeforeRender(this._renderFunction);
  60815. }
  60816. this._numMeshes++;
  60817. }
  60818. };
  60819. /**
  60820. * Hides a specified physic impostor
  60821. * @param impostor defines the impostor to hide
  60822. */
  60823. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  60824. if (!impostor || !this._scene) {
  60825. return;
  60826. }
  60827. var removed = false;
  60828. for (var i = 0; i < this._numMeshes; i++) {
  60829. if (this._impostors[i] == impostor) {
  60830. var mesh = this._meshes[i];
  60831. if (!mesh) {
  60832. continue;
  60833. }
  60834. this._scene.removeMesh(mesh);
  60835. mesh.dispose();
  60836. this._numMeshes--;
  60837. if (this._numMeshes > 0) {
  60838. this._meshes[i] = this._meshes[this._numMeshes];
  60839. this._impostors[i] = this._impostors[this._numMeshes];
  60840. this._meshes[this._numMeshes] = null;
  60841. this._impostors[this._numMeshes] = null;
  60842. }
  60843. else {
  60844. this._meshes[0] = null;
  60845. this._impostors[0] = null;
  60846. }
  60847. removed = true;
  60848. break;
  60849. }
  60850. }
  60851. if (removed && this._numMeshes === 0) {
  60852. this._scene.unregisterBeforeRender(this._renderFunction);
  60853. }
  60854. };
  60855. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  60856. if (!this._debugMaterial) {
  60857. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  60858. this._debugMaterial.wireframe = true;
  60859. }
  60860. return this._debugMaterial;
  60861. };
  60862. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  60863. if (!this._debugBoxMesh) {
  60864. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  60865. this._debugBoxMesh.renderingGroupId = 1;
  60866. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60867. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  60868. scene.removeMesh(this._debugBoxMesh);
  60869. }
  60870. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  60871. };
  60872. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  60873. if (!this._debugSphereMesh) {
  60874. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  60875. this._debugSphereMesh.renderingGroupId = 1;
  60876. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60877. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  60878. scene.removeMesh(this._debugSphereMesh);
  60879. }
  60880. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  60881. };
  60882. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  60883. var mesh = null;
  60884. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  60885. mesh = this._getDebugBoxMesh(scene);
  60886. impostor.getBoxSizeToRef(mesh.scaling);
  60887. }
  60888. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  60889. mesh = this._getDebugSphereMesh(scene);
  60890. var radius = impostor.getRadius();
  60891. mesh.scaling.x = radius * 2;
  60892. mesh.scaling.y = radius * 2;
  60893. mesh.scaling.z = radius * 2;
  60894. }
  60895. return mesh;
  60896. };
  60897. /** Releases all resources */
  60898. PhysicsViewer.prototype.dispose = function () {
  60899. for (var i = 0; i < this._numMeshes; i++) {
  60900. this.hideImpostor(this._impostors[i]);
  60901. }
  60902. if (this._debugBoxMesh) {
  60903. this._debugBoxMesh.dispose();
  60904. }
  60905. if (this._debugSphereMesh) {
  60906. this._debugSphereMesh.dispose();
  60907. }
  60908. if (this._debugMaterial) {
  60909. this._debugMaterial.dispose();
  60910. }
  60911. this._impostors.length = 0;
  60912. this._scene = null;
  60913. this._physicsEnginePlugin = null;
  60914. };
  60915. return PhysicsViewer;
  60916. }());
  60917. Debug.PhysicsViewer = PhysicsViewer;
  60918. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60919. })(BABYLON || (BABYLON = {}));
  60920. //# sourceMappingURL=babylon.physicsViewer.js.map
  60921. var BABYLON;
  60922. (function (BABYLON) {
  60923. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  60924. get: function () {
  60925. return this._forceShowBoundingBoxes || false;
  60926. },
  60927. set: function (value) {
  60928. this._forceShowBoundingBoxes = value;
  60929. // Lazyly creates a BB renderer if needed.
  60930. if (value) {
  60931. this.getBoundingBoxRenderer();
  60932. }
  60933. },
  60934. enumerable: true,
  60935. configurable: true
  60936. });
  60937. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  60938. if (!this._boundingBoxRenderer) {
  60939. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  60940. }
  60941. return this._boundingBoxRenderer;
  60942. };
  60943. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  60944. get: function () {
  60945. return this._showBoundingBox || false;
  60946. },
  60947. set: function (value) {
  60948. this._showBoundingBox = value;
  60949. // Lazyly creates a BB renderer if needed.
  60950. if (value) {
  60951. this.getScene().getBoundingBoxRenderer();
  60952. }
  60953. },
  60954. enumerable: true,
  60955. configurable: true
  60956. });
  60957. var BoundingBoxRenderer = /** @class */ (function () {
  60958. function BoundingBoxRenderer(scene) {
  60959. /**
  60960. * The component name helpfull to identify the component in the list of scene components.
  60961. */
  60962. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  60963. this.frontColor = new BABYLON.Color3(1, 1, 1);
  60964. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  60965. this.showBackLines = true;
  60966. this.renderList = new BABYLON.SmartArray(32);
  60967. this._vertexBuffers = {};
  60968. this.scene = scene;
  60969. scene._addComponent(this);
  60970. }
  60971. /**
  60972. * Registers the component in a given scene
  60973. */
  60974. BoundingBoxRenderer.prototype.register = function () {
  60975. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  60976. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  60977. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  60978. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  60979. };
  60980. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  60981. if (mesh.showSubMeshesBoundingBox) {
  60982. var boundingInfo = subMesh.getBoundingInfo();
  60983. if (boundingInfo !== null && boundingInfo !== undefined) {
  60984. this.renderList.push(boundingInfo.boundingBox);
  60985. }
  60986. }
  60987. };
  60988. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  60989. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  60990. var boundingInfo = sourceMesh.getBoundingInfo();
  60991. this.renderList.push(boundingInfo.boundingBox);
  60992. }
  60993. };
  60994. BoundingBoxRenderer.prototype._prepareRessources = function () {
  60995. if (this._colorShader) {
  60996. return;
  60997. }
  60998. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  60999. attributes: [BABYLON.VertexBuffer.PositionKind],
  61000. uniforms: ["world", "viewProjection", "color"]
  61001. });
  61002. var engine = this.scene.getEngine();
  61003. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  61004. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  61005. this._createIndexBuffer();
  61006. };
  61007. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  61008. var engine = this.scene.getEngine();
  61009. 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]);
  61010. };
  61011. /**
  61012. * Rebuilds the elements related to this component in case of
  61013. * context lost for instance.
  61014. */
  61015. BoundingBoxRenderer.prototype.rebuild = function () {
  61016. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61017. if (vb) {
  61018. vb._rebuild();
  61019. }
  61020. this._createIndexBuffer();
  61021. };
  61022. BoundingBoxRenderer.prototype.reset = function () {
  61023. this.renderList.reset();
  61024. };
  61025. BoundingBoxRenderer.prototype.render = function () {
  61026. if (this.renderList.length === 0) {
  61027. return;
  61028. }
  61029. this._prepareRessources();
  61030. if (!this._colorShader.isReady()) {
  61031. return;
  61032. }
  61033. var engine = this.scene.getEngine();
  61034. engine.setDepthWrite(false);
  61035. this._colorShader._preBind();
  61036. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  61037. var boundingBox = this.renderList.data[boundingBoxIndex];
  61038. var min = boundingBox.minimum;
  61039. var max = boundingBox.maximum;
  61040. var diff = max.subtract(min);
  61041. var median = min.add(diff.scale(0.5));
  61042. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61043. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61044. .multiply(boundingBox.getWorldMatrix());
  61045. // VBOs
  61046. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61047. if (this.showBackLines) {
  61048. // Back
  61049. engine.setDepthFunctionToGreaterOrEqual();
  61050. this.scene.resetCachedMaterial();
  61051. this._colorShader.setColor4("color", this.backColor.toColor4());
  61052. this._colorShader.bind(worldMatrix);
  61053. // Draw order
  61054. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61055. }
  61056. // Front
  61057. engine.setDepthFunctionToLess();
  61058. this.scene.resetCachedMaterial();
  61059. this._colorShader.setColor4("color", this.frontColor.toColor4());
  61060. this._colorShader.bind(worldMatrix);
  61061. // Draw order
  61062. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61063. }
  61064. this._colorShader.unbind();
  61065. engine.setDepthFunctionToLessOrEqual();
  61066. engine.setDepthWrite(true);
  61067. };
  61068. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  61069. this._prepareRessources();
  61070. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  61071. return;
  61072. }
  61073. var engine = this.scene.getEngine();
  61074. engine.setDepthWrite(false);
  61075. engine.setColorWrite(false);
  61076. this._colorShader._preBind();
  61077. var boundingBox = mesh._boundingInfo.boundingBox;
  61078. var min = boundingBox.minimum;
  61079. var max = boundingBox.maximum;
  61080. var diff = max.subtract(min);
  61081. var median = min.add(diff.scale(0.5));
  61082. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61083. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61084. .multiply(boundingBox.getWorldMatrix());
  61085. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61086. engine.setDepthFunctionToLess();
  61087. this.scene.resetCachedMaterial();
  61088. this._colorShader.bind(worldMatrix);
  61089. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61090. this._colorShader.unbind();
  61091. engine.setDepthFunctionToLessOrEqual();
  61092. engine.setDepthWrite(true);
  61093. engine.setColorWrite(true);
  61094. };
  61095. BoundingBoxRenderer.prototype.dispose = function () {
  61096. if (!this._colorShader) {
  61097. return;
  61098. }
  61099. this.renderList.dispose();
  61100. this._colorShader.dispose();
  61101. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61102. if (buffer) {
  61103. buffer.dispose();
  61104. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61105. }
  61106. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  61107. };
  61108. return BoundingBoxRenderer;
  61109. }());
  61110. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  61111. })(BABYLON || (BABYLON = {}));
  61112. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  61113. var BABYLON;
  61114. (function (BABYLON) {
  61115. BABYLON.Engine.prototype.createTransformFeedback = function () {
  61116. return this._gl.createTransformFeedback();
  61117. };
  61118. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  61119. this._gl.deleteTransformFeedback(value);
  61120. };
  61121. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  61122. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  61123. };
  61124. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  61125. if (usePoints === void 0) { usePoints = true; }
  61126. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  61127. };
  61128. BABYLON.Engine.prototype.endTransformFeedback = function () {
  61129. this._gl.endTransformFeedback();
  61130. };
  61131. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  61132. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  61133. };
  61134. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  61135. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  61136. };
  61137. })(BABYLON || (BABYLON = {}));
  61138. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  61139. var BABYLON;
  61140. (function (BABYLON) {
  61141. /**
  61142. * This represents a GPU particle system in Babylon
  61143. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  61144. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  61145. */
  61146. var GPUParticleSystem = /** @class */ (function (_super) {
  61147. __extends(GPUParticleSystem, _super);
  61148. /**
  61149. * Instantiates a GPU particle system.
  61150. * 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.
  61151. * @param name The name of the particle system
  61152. * @param options The options used to create the system
  61153. * @param scene The scene the particle system belongs to
  61154. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  61155. */
  61156. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  61157. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61158. var _this = _super.call(this, name) || this;
  61159. /**
  61160. * The layer mask we are rendering the particles through.
  61161. */
  61162. _this.layerMask = 0x0FFFFFFF;
  61163. _this._accumulatedCount = 0;
  61164. _this._targetIndex = 0;
  61165. _this._currentRenderId = -1;
  61166. _this._started = false;
  61167. _this._stopped = false;
  61168. _this._timeDelta = 0;
  61169. _this._attributesStrideSize = 21;
  61170. _this._actualFrame = 0;
  61171. _this._rawTextureWidth = 256;
  61172. /**
  61173. * An event triggered when the system is disposed.
  61174. */
  61175. _this.onDisposeObservable = new BABYLON.Observable();
  61176. /**
  61177. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  61178. * to override the particles.
  61179. */
  61180. _this.forceDepthWrite = false;
  61181. _this._preWarmDone = false;
  61182. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61183. // Setup the default processing configuration to the scene.
  61184. _this._attachImageProcessingConfiguration(null);
  61185. _this._engine = _this._scene.getEngine();
  61186. if (!options.randomTextureSize) {
  61187. delete options.randomTextureSize;
  61188. }
  61189. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  61190. var optionsAsNumber = options;
  61191. if (isFinite(optionsAsNumber)) {
  61192. fullOptions.capacity = optionsAsNumber;
  61193. }
  61194. _this._capacity = fullOptions.capacity;
  61195. _this._activeCount = fullOptions.capacity;
  61196. _this._currentActiveCount = 0;
  61197. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  61198. _this._scene.particleSystems.push(_this);
  61199. _this._updateEffectOptions = {
  61200. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset"],
  61201. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  61202. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  61203. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  61204. uniformBuffersNames: [],
  61205. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  61206. defines: "",
  61207. fallbacks: null,
  61208. onCompiled: null,
  61209. onError: null,
  61210. indexParameters: null,
  61211. maxSimultaneousLights: 0,
  61212. transformFeedbackVaryings: []
  61213. };
  61214. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  61215. // Random data
  61216. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  61217. var d = [];
  61218. for (var i = 0; i < maxTextureSize; ++i) {
  61219. d.push(Math.random());
  61220. d.push(Math.random());
  61221. d.push(Math.random());
  61222. d.push(Math.random());
  61223. }
  61224. _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);
  61225. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61226. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61227. d = [];
  61228. for (var i = 0; i < maxTextureSize; ++i) {
  61229. d.push(Math.random());
  61230. d.push(Math.random());
  61231. d.push(Math.random());
  61232. d.push(Math.random());
  61233. }
  61234. _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);
  61235. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61236. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61237. _this._randomTextureSize = maxTextureSize;
  61238. return _this;
  61239. }
  61240. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  61241. /**
  61242. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  61243. */
  61244. get: function () {
  61245. if (!BABYLON.Engine.LastCreatedEngine) {
  61246. return false;
  61247. }
  61248. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  61249. },
  61250. enumerable: true,
  61251. configurable: true
  61252. });
  61253. /**
  61254. * Gets the maximum number of particles active at the same time.
  61255. * @returns The max number of active particles.
  61256. */
  61257. GPUParticleSystem.prototype.getCapacity = function () {
  61258. return this._capacity;
  61259. };
  61260. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  61261. /**
  61262. * Gets or set the number of active particles
  61263. */
  61264. get: function () {
  61265. return this._activeCount;
  61266. },
  61267. set: function (value) {
  61268. this._activeCount = Math.min(value, this._capacity);
  61269. },
  61270. enumerable: true,
  61271. configurable: true
  61272. });
  61273. /**
  61274. * Is this system ready to be used/rendered
  61275. * @return true if the system is ready
  61276. */
  61277. GPUParticleSystem.prototype.isReady = function () {
  61278. if (!this._updateEffect) {
  61279. this._recreateUpdateEffect();
  61280. this._recreateRenderEffect();
  61281. return false;
  61282. }
  61283. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61284. return false;
  61285. }
  61286. return true;
  61287. };
  61288. /**
  61289. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61290. * @returns True if it has been started, otherwise false.
  61291. */
  61292. GPUParticleSystem.prototype.isStarted = function () {
  61293. return this._started;
  61294. };
  61295. /**
  61296. * Starts the particle system and begins to emit
  61297. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  61298. */
  61299. GPUParticleSystem.prototype.start = function (delay) {
  61300. var _this = this;
  61301. if (delay === void 0) { delay = 0; }
  61302. if (delay) {
  61303. setTimeout(function () {
  61304. _this.start(0);
  61305. }, delay);
  61306. return;
  61307. }
  61308. this._started = true;
  61309. this._stopped = false;
  61310. this._preWarmDone = false;
  61311. };
  61312. /**
  61313. * Stops the particle system.
  61314. */
  61315. GPUParticleSystem.prototype.stop = function () {
  61316. this._stopped = true;
  61317. };
  61318. /**
  61319. * Remove all active particles
  61320. */
  61321. GPUParticleSystem.prototype.reset = function () {
  61322. this._releaseBuffers();
  61323. this._releaseVAOs();
  61324. this._currentActiveCount = 0;
  61325. this._targetIndex = 0;
  61326. };
  61327. /**
  61328. * Returns the string "GPUParticleSystem"
  61329. * @returns a string containing the class name
  61330. */
  61331. GPUParticleSystem.prototype.getClassName = function () {
  61332. return "GPUParticleSystem";
  61333. };
  61334. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  61335. if (!gradients) {
  61336. return this;
  61337. }
  61338. var index = 0;
  61339. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  61340. var valueGradient = gradients_1[_i];
  61341. if (valueGradient.gradient === gradient) {
  61342. gradients.splice(index, 1);
  61343. break;
  61344. }
  61345. index++;
  61346. }
  61347. if (texture) {
  61348. texture.dispose();
  61349. }
  61350. this._releaseBuffers();
  61351. return this;
  61352. };
  61353. /**
  61354. * Adds a new color gradient
  61355. * @param gradient defines the gradient to use (between 0 and 1)
  61356. * @param color defines the color to affect to the specified gradient
  61357. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61358. * @returns the current particle system
  61359. */
  61360. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61361. if (!this._colorGradients) {
  61362. this._colorGradients = [];
  61363. }
  61364. var colorGradient = new BABYLON.ColorGradient();
  61365. colorGradient.gradient = gradient;
  61366. colorGradient.color1 = color1;
  61367. this._colorGradients.push(colorGradient);
  61368. this._colorGradients.sort(function (a, b) {
  61369. if (a.gradient < b.gradient) {
  61370. return -1;
  61371. }
  61372. else if (a.gradient > b.gradient) {
  61373. return 1;
  61374. }
  61375. return 0;
  61376. });
  61377. if (this._colorGradientsTexture) {
  61378. this._colorGradientsTexture.dispose();
  61379. this._colorGradientsTexture = null;
  61380. }
  61381. this._releaseBuffers();
  61382. return this;
  61383. };
  61384. /**
  61385. * Remove a specific color gradient
  61386. * @param gradient defines the gradient to remove
  61387. * @returns the current particle system
  61388. */
  61389. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  61390. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  61391. this._colorGradientsTexture = null;
  61392. return this;
  61393. };
  61394. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  61395. var valueGradient = new BABYLON.FactorGradient();
  61396. valueGradient.gradient = gradient;
  61397. valueGradient.factor1 = factor;
  61398. factorGradients.push(valueGradient);
  61399. factorGradients.sort(function (a, b) {
  61400. if (a.gradient < b.gradient) {
  61401. return -1;
  61402. }
  61403. else if (a.gradient > b.gradient) {
  61404. return 1;
  61405. }
  61406. return 0;
  61407. });
  61408. this._releaseBuffers();
  61409. };
  61410. /**
  61411. * Adds a new size gradient
  61412. * @param gradient defines the gradient to use (between 0 and 1)
  61413. * @param factor defines the size factor to affect to the specified gradient
  61414. * @returns the current particle system
  61415. */
  61416. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  61417. if (!this._sizeGradients) {
  61418. this._sizeGradients = [];
  61419. }
  61420. this._addFactorGradient(this._sizeGradients, gradient, factor);
  61421. if (this._sizeGradientsTexture) {
  61422. this._sizeGradientsTexture.dispose();
  61423. this._sizeGradientsTexture = null;
  61424. }
  61425. this._releaseBuffers();
  61426. return this;
  61427. };
  61428. /**
  61429. * Remove a specific size gradient
  61430. * @param gradient defines the gradient to remove
  61431. * @returns the current particle system
  61432. */
  61433. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61434. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  61435. this._sizeGradientsTexture = null;
  61436. return this;
  61437. };
  61438. /**
  61439. * Adds a new angular speed gradient
  61440. * @param gradient defines the gradient to use (between 0 and 1)
  61441. * @param factor defines the angular speed to affect to the specified gradient
  61442. * @returns the current particle system
  61443. */
  61444. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  61445. if (!this._angularSpeedGradients) {
  61446. this._angularSpeedGradients = [];
  61447. }
  61448. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  61449. if (this._angularSpeedGradientsTexture) {
  61450. this._angularSpeedGradientsTexture.dispose();
  61451. this._angularSpeedGradientsTexture = null;
  61452. }
  61453. this._releaseBuffers();
  61454. return this;
  61455. };
  61456. /**
  61457. * Remove a specific angular speed gradient
  61458. * @param gradient defines the gradient to remove
  61459. * @returns the current particle system
  61460. */
  61461. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61462. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  61463. this._angularSpeedGradientsTexture = null;
  61464. return this;
  61465. };
  61466. /**
  61467. * Adds a new velocity gradient
  61468. * @param gradient defines the gradient to use (between 0 and 1)
  61469. * @param factor defines the velocity to affect to the specified gradient
  61470. * @returns the current particle system
  61471. */
  61472. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  61473. if (!this._velocityGradients) {
  61474. this._velocityGradients = [];
  61475. }
  61476. this._addFactorGradient(this._velocityGradients, gradient, factor);
  61477. if (this._velocityGradientsTexture) {
  61478. this._velocityGradientsTexture.dispose();
  61479. this._velocityGradientsTexture = null;
  61480. }
  61481. this._releaseBuffers();
  61482. return this;
  61483. };
  61484. /**
  61485. * Remove a specific velocity gradient
  61486. * @param gradient defines the gradient to remove
  61487. * @returns the current particle system
  61488. */
  61489. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61490. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  61491. this._velocityGradientsTexture = null;
  61492. return this;
  61493. };
  61494. /**
  61495. * Adds a new limit velocity gradient
  61496. * @param gradient defines the gradient to use (between 0 and 1)
  61497. * @param factor defines the limit velocity value to affect to the specified gradient
  61498. * @returns the current particle system
  61499. */
  61500. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  61501. if (!this._limitVelocityGradients) {
  61502. this._limitVelocityGradients = [];
  61503. }
  61504. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  61505. if (this._limitVelocityGradientsTexture) {
  61506. this._limitVelocityGradientsTexture.dispose();
  61507. this._limitVelocityGradientsTexture = null;
  61508. }
  61509. this._releaseBuffers();
  61510. return this;
  61511. };
  61512. /**
  61513. * Remove a specific limit velocity gradient
  61514. * @param gradient defines the gradient to remove
  61515. * @returns the current particle system
  61516. */
  61517. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61518. this._removeGradient(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  61519. this._limitVelocityGradientsTexture = null;
  61520. return this;
  61521. };
  61522. /**
  61523. * Adds a new drag gradient
  61524. * @param gradient defines the gradient to use (between 0 and 1)
  61525. * @param factor defines the drag value to affect to the specified gradient
  61526. * @returns the current particle system
  61527. */
  61528. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  61529. if (!this._dragGradients) {
  61530. this._dragGradients = [];
  61531. }
  61532. this._addFactorGradient(this._dragGradients, gradient, factor);
  61533. if (this._dragGradientsTexture) {
  61534. this._dragGradientsTexture.dispose();
  61535. this._dragGradientsTexture = null;
  61536. }
  61537. this._releaseBuffers();
  61538. return this;
  61539. };
  61540. /**
  61541. * Remove a specific drag gradient
  61542. * @param gradient defines the gradient to remove
  61543. * @returns the current particle system
  61544. */
  61545. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  61546. this._removeGradient(gradient, this._dragGradients, this._dragGradientsTexture);
  61547. this._dragGradientsTexture = null;
  61548. return this;
  61549. };
  61550. /**
  61551. * Not supported by GPUParticleSystem
  61552. * @param gradient defines the gradient to use (between 0 and 1)
  61553. * @param factor defines the emit rate value to affect to the specified gradient
  61554. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61555. * @returns the current particle system
  61556. */
  61557. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  61558. // Do nothing as emit rate is not supported by GPUParticleSystem
  61559. return this;
  61560. };
  61561. /**
  61562. * Not supported by GPUParticleSystem
  61563. * @param gradient defines the gradient to remove
  61564. * @returns the current particle system
  61565. */
  61566. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  61567. // Do nothing as emit rate is not supported by GPUParticleSystem
  61568. return this;
  61569. };
  61570. /**
  61571. * Not supported by GPUParticleSystem
  61572. * @param gradient defines the gradient to use (between 0 and 1)
  61573. * @param factor defines the start size value to affect to the specified gradient
  61574. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61575. * @returns the current particle system
  61576. */
  61577. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  61578. // Do nothing as start size is not supported by GPUParticleSystem
  61579. return this;
  61580. };
  61581. /**
  61582. * Not supported by GPUParticleSystem
  61583. * @param gradient defines the gradient to remove
  61584. * @returns the current particle system
  61585. */
  61586. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  61587. // Do nothing as start size is not supported by GPUParticleSystem
  61588. return this;
  61589. };
  61590. GPUParticleSystem.prototype._reset = function () {
  61591. this._releaseBuffers();
  61592. };
  61593. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  61594. var updateVertexBuffers = {};
  61595. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  61596. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  61597. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  61598. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  61599. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  61600. var offset = 12;
  61601. if (!this._colorGradientsTexture) {
  61602. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  61603. offset += 4;
  61604. }
  61605. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  61606. offset += 3;
  61607. if (!this._isBillboardBased) {
  61608. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  61609. offset += 3;
  61610. }
  61611. if (this._angularSpeedGradientsTexture) {
  61612. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  61613. offset += 1;
  61614. }
  61615. else {
  61616. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  61617. offset += 2;
  61618. }
  61619. if (this._isAnimationSheetEnabled) {
  61620. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  61621. offset += 1;
  61622. if (this.spriteRandomStartCell) {
  61623. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  61624. offset += 1;
  61625. }
  61626. }
  61627. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  61628. this._engine.bindArrayBuffer(null);
  61629. return vao;
  61630. };
  61631. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  61632. var renderVertexBuffers = {};
  61633. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  61634. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  61635. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  61636. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  61637. var offset = 12;
  61638. if (!this._colorGradientsTexture) {
  61639. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  61640. offset += 4;
  61641. }
  61642. offset += 3; // Direction
  61643. if (!this._isBillboardBased) {
  61644. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  61645. offset += 3;
  61646. }
  61647. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  61648. if (this._angularSpeedGradientsTexture) {
  61649. offset++;
  61650. }
  61651. else {
  61652. offset += 2;
  61653. }
  61654. if (this._isAnimationSheetEnabled) {
  61655. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  61656. offset += 1;
  61657. if (this.spriteRandomStartCell) {
  61658. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  61659. offset += 1;
  61660. }
  61661. }
  61662. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  61663. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  61664. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  61665. this._engine.bindArrayBuffer(null);
  61666. return vao;
  61667. };
  61668. GPUParticleSystem.prototype._initialize = function (force) {
  61669. if (force === void 0) { force = false; }
  61670. if (this._buffer0 && !force) {
  61671. return;
  61672. }
  61673. var engine = this._scene.getEngine();
  61674. var data = new Array();
  61675. if (!this.isBillboardBased) {
  61676. this._attributesStrideSize += 3;
  61677. }
  61678. if (this._colorGradientsTexture) {
  61679. this._attributesStrideSize -= 4;
  61680. }
  61681. if (this._angularSpeedGradientsTexture) {
  61682. this._attributesStrideSize -= 1;
  61683. }
  61684. if (this._isAnimationSheetEnabled) {
  61685. this._attributesStrideSize += 1;
  61686. if (this.spriteRandomStartCell) {
  61687. this._attributesStrideSize += 1;
  61688. }
  61689. }
  61690. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  61691. // position
  61692. data.push(0.0);
  61693. data.push(0.0);
  61694. data.push(0.0);
  61695. // Age and life
  61696. data.push(0.0); // create the particle as a dead one to create a new one at start
  61697. data.push(0.0);
  61698. // Seed
  61699. data.push(Math.random());
  61700. data.push(Math.random());
  61701. data.push(Math.random());
  61702. data.push(Math.random());
  61703. // Size
  61704. data.push(0.0);
  61705. data.push(0.0);
  61706. data.push(0.0);
  61707. if (!this._colorGradientsTexture) {
  61708. // color
  61709. data.push(0.0);
  61710. data.push(0.0);
  61711. data.push(0.0);
  61712. data.push(0.0);
  61713. }
  61714. // direction
  61715. data.push(0.0);
  61716. data.push(0.0);
  61717. data.push(0.0);
  61718. if (!this.isBillboardBased) {
  61719. // initialDirection
  61720. data.push(0.0);
  61721. data.push(0.0);
  61722. data.push(0.0);
  61723. }
  61724. // angle
  61725. data.push(0.0);
  61726. if (!this._angularSpeedGradientsTexture) {
  61727. data.push(0.0);
  61728. }
  61729. if (this._isAnimationSheetEnabled) {
  61730. data.push(0.0);
  61731. if (this.spriteRandomStartCell) {
  61732. data.push(0.0);
  61733. }
  61734. }
  61735. }
  61736. // Sprite data
  61737. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  61738. -0.5, 0.5, 0, 1,
  61739. -0.5, -0.5, 0, 0,
  61740. 0.5, -0.5, 1, 0]);
  61741. // Buffers
  61742. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61743. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61744. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  61745. // Update VAO
  61746. this._updateVAO = [];
  61747. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  61748. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  61749. // Render VAO
  61750. this._renderVAO = [];
  61751. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  61752. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  61753. // Links
  61754. this._sourceBuffer = this._buffer0;
  61755. this._targetBuffer = this._buffer1;
  61756. };
  61757. /** @hidden */
  61758. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  61759. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  61760. if (this._isBillboardBased) {
  61761. defines += "\n#define BILLBOARD";
  61762. }
  61763. if (this._colorGradientsTexture) {
  61764. defines += "\n#define COLORGRADIENTS";
  61765. }
  61766. if (this._sizeGradientsTexture) {
  61767. defines += "\n#define SIZEGRADIENTS";
  61768. }
  61769. if (this._angularSpeedGradientsTexture) {
  61770. defines += "\n#define ANGULARSPEEDGRADIENTS";
  61771. }
  61772. if (this._velocityGradientsTexture) {
  61773. defines += "\n#define VELOCITYGRADIENTS";
  61774. }
  61775. if (this._limitVelocityGradientsTexture) {
  61776. defines += "\n#define LIMITVELOCITYGRADIENTS";
  61777. }
  61778. if (this._dragGradientsTexture) {
  61779. defines += "\n#define DRAGGRADIENTS";
  61780. }
  61781. if (this.isAnimationSheetEnabled) {
  61782. defines += "\n#define ANIMATESHEET";
  61783. if (this.spriteRandomStartCell) {
  61784. defines += "\n#define ANIMATESHEETRANDOMSTART";
  61785. }
  61786. }
  61787. if (this.noiseTexture) {
  61788. defines += "\n#define NOISE";
  61789. }
  61790. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  61791. return;
  61792. }
  61793. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  61794. if (!this._colorGradientsTexture) {
  61795. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  61796. }
  61797. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  61798. if (!this._isBillboardBased) {
  61799. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  61800. }
  61801. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  61802. if (this.isAnimationSheetEnabled) {
  61803. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  61804. if (this.spriteRandomStartCell) {
  61805. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  61806. }
  61807. }
  61808. this._updateEffectOptions.defines = defines;
  61809. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  61810. };
  61811. /** @hidden */
  61812. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  61813. var defines = "";
  61814. if (this._scene.clipPlane) {
  61815. defines = "\n#define CLIPPLANE";
  61816. }
  61817. if (this._scene.clipPlane2) {
  61818. defines = "\n#define CLIPPLANE2";
  61819. }
  61820. if (this._scene.clipPlane3) {
  61821. defines = "\n#define CLIPPLANE3";
  61822. }
  61823. if (this._scene.clipPlane4) {
  61824. defines = "\n#define CLIPPLANE4";
  61825. }
  61826. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  61827. defines = "\n#define BLENDMULTIPLYMODE";
  61828. }
  61829. if (this._isBillboardBased) {
  61830. defines += "\n#define BILLBOARD";
  61831. switch (this.billboardMode) {
  61832. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  61833. defines += "\n#define BILLBOARDY";
  61834. break;
  61835. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  61836. default:
  61837. break;
  61838. }
  61839. }
  61840. if (this._colorGradientsTexture) {
  61841. defines += "\n#define COLORGRADIENTS";
  61842. }
  61843. if (this.isAnimationSheetEnabled) {
  61844. defines += "\n#define ANIMATESHEET";
  61845. }
  61846. if (this._imageProcessingConfiguration) {
  61847. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  61848. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  61849. }
  61850. if (this._renderEffect && this._renderEffect.defines === defines) {
  61851. return;
  61852. }
  61853. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  61854. var samplers = ["textureSampler", "colorGradientSampler"];
  61855. if (BABYLON.ImageProcessingConfiguration) {
  61856. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  61857. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  61858. }
  61859. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  61860. };
  61861. /**
  61862. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  61863. * @param preWarm defines if we are in the pre-warmimg phase
  61864. */
  61865. GPUParticleSystem.prototype.animate = function (preWarm) {
  61866. if (preWarm === void 0) { preWarm = false; }
  61867. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  61868. this._actualFrame += this._timeDelta;
  61869. if (!this._stopped) {
  61870. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  61871. this.stop();
  61872. }
  61873. }
  61874. };
  61875. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  61876. var texture = this[textureName];
  61877. if (!factorGradients || !factorGradients.length || texture) {
  61878. return;
  61879. }
  61880. var data = new Float32Array(this._rawTextureWidth);
  61881. for (var x = 0; x < this._rawTextureWidth; x++) {
  61882. var ratio = x / this._rawTextureWidth;
  61883. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  61884. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  61885. });
  61886. }
  61887. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61888. };
  61889. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  61890. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  61891. };
  61892. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  61893. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  61894. };
  61895. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  61896. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  61897. };
  61898. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  61899. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  61900. };
  61901. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  61902. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  61903. };
  61904. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  61905. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  61906. return;
  61907. }
  61908. var data = new Uint8Array(this._rawTextureWidth * 4);
  61909. var tmpColor = BABYLON.Tmp.Color4[0];
  61910. for (var x = 0; x < this._rawTextureWidth; x++) {
  61911. var ratio = x / this._rawTextureWidth;
  61912. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  61913. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  61914. data[x * 4] = tmpColor.r * 255;
  61915. data[x * 4 + 1] = tmpColor.g * 255;
  61916. data[x * 4 + 2] = tmpColor.b * 255;
  61917. data[x * 4 + 3] = tmpColor.a * 255;
  61918. });
  61919. }
  61920. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61921. };
  61922. /**
  61923. * Renders the particle system in its current state
  61924. * @param preWarm defines if the system should only update the particles but not render them
  61925. * @returns the current number of particles
  61926. */
  61927. GPUParticleSystem.prototype.render = function (preWarm) {
  61928. if (preWarm === void 0) { preWarm = false; }
  61929. if (!this._started) {
  61930. return 0;
  61931. }
  61932. this._createColorGradientTexture();
  61933. this._createSizeGradientTexture();
  61934. this._createAngularSpeedGradientTexture();
  61935. this._createVelocityGradientTexture();
  61936. this._createLimitVelocityGradientTexture();
  61937. this._createDragGradientTexture();
  61938. this._recreateUpdateEffect();
  61939. this._recreateRenderEffect();
  61940. if (!this.isReady()) {
  61941. return 0;
  61942. }
  61943. if (!preWarm) {
  61944. if (!this._preWarmDone && this.preWarmCycles) {
  61945. for (var index = 0; index < this.preWarmCycles; index++) {
  61946. this.animate(true);
  61947. this.render(true);
  61948. }
  61949. this._preWarmDone = true;
  61950. }
  61951. if (this._currentRenderId === this._scene.getRenderId()) {
  61952. return 0;
  61953. }
  61954. this._currentRenderId = this._scene.getRenderId();
  61955. }
  61956. // Get everything ready to render
  61957. this._initialize();
  61958. this._accumulatedCount += this.emitRate * this._timeDelta;
  61959. if (this._accumulatedCount > 1) {
  61960. var intPart = this._accumulatedCount | 0;
  61961. this._accumulatedCount -= intPart;
  61962. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  61963. }
  61964. if (!this._currentActiveCount) {
  61965. return 0;
  61966. }
  61967. // Enable update effect
  61968. this._engine.enableEffect(this._updateEffect);
  61969. this._engine.setState(false);
  61970. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  61971. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  61972. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  61973. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  61974. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  61975. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  61976. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  61977. if (!this._colorGradientsTexture) {
  61978. this._updateEffect.setDirectColor4("color1", this.color1);
  61979. this._updateEffect.setDirectColor4("color2", this.color2);
  61980. }
  61981. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  61982. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  61983. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  61984. this._updateEffect.setVector3("gravity", this.gravity);
  61985. if (this._sizeGradientsTexture) {
  61986. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  61987. }
  61988. if (this._angularSpeedGradientsTexture) {
  61989. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  61990. }
  61991. if (this._velocityGradientsTexture) {
  61992. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  61993. }
  61994. if (this._limitVelocityGradientsTexture) {
  61995. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  61996. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  61997. }
  61998. if (this._dragGradientsTexture) {
  61999. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  62000. }
  62001. if (this.particleEmitterType) {
  62002. this.particleEmitterType.applyToShader(this._updateEffect);
  62003. }
  62004. if (this._isAnimationSheetEnabled) {
  62005. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  62006. }
  62007. if (this.noiseTexture) {
  62008. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  62009. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  62010. }
  62011. var emitterWM;
  62012. if (this.emitter.position) {
  62013. var emitterMesh = this.emitter;
  62014. emitterWM = emitterMesh.getWorldMatrix();
  62015. }
  62016. else {
  62017. var emitterPosition = this.emitter;
  62018. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  62019. }
  62020. this._updateEffect.setMatrix("emitterWM", emitterWM);
  62021. // Bind source VAO
  62022. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  62023. // Update
  62024. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  62025. this._engine.setRasterizerState(false);
  62026. this._engine.beginTransformFeedback(true);
  62027. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  62028. this._engine.endTransformFeedback();
  62029. this._engine.setRasterizerState(true);
  62030. this._engine.bindTransformFeedbackBuffer(null);
  62031. if (!preWarm) {
  62032. // Enable render effect
  62033. this._engine.enableEffect(this._renderEffect);
  62034. var viewMatrix = this._scene.getViewMatrix();
  62035. this._renderEffect.setMatrix("view", viewMatrix);
  62036. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  62037. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  62038. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  62039. if (this._colorGradientsTexture) {
  62040. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  62041. }
  62042. else {
  62043. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  62044. }
  62045. if (this._isAnimationSheetEnabled && this.particleTexture) {
  62046. var baseSize = this.particleTexture.getBaseSize();
  62047. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  62048. }
  62049. if (this._isBillboardBased) {
  62050. var camera = this._scene.activeCamera;
  62051. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  62052. }
  62053. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  62054. var invView = viewMatrix.clone();
  62055. invView.invert();
  62056. this._renderEffect.setMatrix("invView", invView);
  62057. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  62058. }
  62059. // image processing
  62060. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  62061. this._imageProcessingConfiguration.bind(this._renderEffect);
  62062. }
  62063. // Draw order
  62064. switch (this.blendMode) {
  62065. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  62066. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  62067. break;
  62068. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  62069. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  62070. break;
  62071. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  62072. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62073. break;
  62074. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  62075. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  62076. break;
  62077. }
  62078. if (this.forceDepthWrite) {
  62079. this._engine.setDepthWrite(true);
  62080. }
  62081. // Bind source VAO
  62082. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  62083. // Render
  62084. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  62085. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62086. }
  62087. // Switch VAOs
  62088. this._targetIndex++;
  62089. if (this._targetIndex === 2) {
  62090. this._targetIndex = 0;
  62091. }
  62092. // Switch buffers
  62093. var tmpBuffer = this._sourceBuffer;
  62094. this._sourceBuffer = this._targetBuffer;
  62095. this._targetBuffer = tmpBuffer;
  62096. return this._currentActiveCount;
  62097. };
  62098. /**
  62099. * Rebuilds the particle system
  62100. */
  62101. GPUParticleSystem.prototype.rebuild = function () {
  62102. this._initialize(true);
  62103. };
  62104. GPUParticleSystem.prototype._releaseBuffers = function () {
  62105. if (this._buffer0) {
  62106. this._buffer0.dispose();
  62107. this._buffer0 = null;
  62108. }
  62109. if (this._buffer1) {
  62110. this._buffer1.dispose();
  62111. this._buffer1 = null;
  62112. }
  62113. if (this._spriteBuffer) {
  62114. this._spriteBuffer.dispose();
  62115. this._spriteBuffer = null;
  62116. }
  62117. };
  62118. GPUParticleSystem.prototype._releaseVAOs = function () {
  62119. if (!this._updateVAO) {
  62120. return;
  62121. }
  62122. for (var index = 0; index < this._updateVAO.length; index++) {
  62123. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  62124. }
  62125. this._updateVAO = [];
  62126. for (var index = 0; index < this._renderVAO.length; index++) {
  62127. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  62128. }
  62129. this._renderVAO = [];
  62130. };
  62131. /**
  62132. * Disposes the particle system and free the associated resources
  62133. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  62134. */
  62135. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  62136. if (disposeTexture === void 0) { disposeTexture = true; }
  62137. var index = this._scene.particleSystems.indexOf(this);
  62138. if (index > -1) {
  62139. this._scene.particleSystems.splice(index, 1);
  62140. }
  62141. this._releaseBuffers();
  62142. this._releaseVAOs();
  62143. if (this._colorGradientsTexture) {
  62144. this._colorGradientsTexture.dispose();
  62145. this._colorGradientsTexture = null;
  62146. }
  62147. if (this._sizeGradientsTexture) {
  62148. this._sizeGradientsTexture.dispose();
  62149. this._sizeGradientsTexture = null;
  62150. }
  62151. if (this._angularSpeedGradientsTexture) {
  62152. this._angularSpeedGradientsTexture.dispose();
  62153. this._angularSpeedGradientsTexture = null;
  62154. }
  62155. if (this._velocityGradientsTexture) {
  62156. this._velocityGradientsTexture.dispose();
  62157. this._velocityGradientsTexture = null;
  62158. }
  62159. if (this._limitVelocityGradientsTexture) {
  62160. this._limitVelocityGradientsTexture.dispose();
  62161. this._limitVelocityGradientsTexture = null;
  62162. }
  62163. if (this._dragGradientsTexture) {
  62164. this._dragGradientsTexture.dispose();
  62165. this._dragGradientsTexture = null;
  62166. }
  62167. if (this._randomTexture) {
  62168. this._randomTexture.dispose();
  62169. this._randomTexture = null;
  62170. }
  62171. if (this._randomTexture2) {
  62172. this._randomTexture2.dispose();
  62173. this._randomTexture2 = null;
  62174. }
  62175. if (disposeTexture && this.particleTexture) {
  62176. this.particleTexture.dispose();
  62177. this.particleTexture = null;
  62178. }
  62179. if (disposeTexture && this.noiseTexture) {
  62180. this.noiseTexture.dispose();
  62181. this.noiseTexture = null;
  62182. }
  62183. // Callback
  62184. this.onDisposeObservable.notifyObservers(this);
  62185. this.onDisposeObservable.clear();
  62186. };
  62187. /**
  62188. * Clones the particle system.
  62189. * @param name The name of the cloned object
  62190. * @param newEmitter The new emitter to use
  62191. * @returns the cloned particle system
  62192. */
  62193. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  62194. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  62195. BABYLON.Tools.DeepCopy(this, result);
  62196. if (newEmitter === undefined) {
  62197. newEmitter = this.emitter;
  62198. }
  62199. result.emitter = newEmitter;
  62200. if (this.particleTexture) {
  62201. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  62202. }
  62203. return result;
  62204. };
  62205. /**
  62206. * Serializes the particle system to a JSON object.
  62207. * @returns the JSON object
  62208. */
  62209. GPUParticleSystem.prototype.serialize = function () {
  62210. var serializationObject = {};
  62211. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  62212. serializationObject.activeParticleCount = this.activeParticleCount;
  62213. return serializationObject;
  62214. };
  62215. /**
  62216. * Parses a JSON object to create a GPU particle system.
  62217. * @param parsedParticleSystem The JSON object to parse
  62218. * @param scene The scene to create the particle system in
  62219. * @param rootUrl The root url to use to load external dependencies like texture
  62220. * @returns the parsed GPU particle system
  62221. */
  62222. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  62223. var name = parsedParticleSystem.name;
  62224. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  62225. if (parsedParticleSystem.activeParticleCount) {
  62226. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  62227. }
  62228. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62229. return particleSystem;
  62230. };
  62231. return GPUParticleSystem;
  62232. }(BABYLON.BaseParticleSystem));
  62233. BABYLON.GPUParticleSystem = GPUParticleSystem;
  62234. })(BABYLON || (BABYLON = {}));
  62235. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  62236. var BABYLON;
  62237. (function (BABYLON) {
  62238. /**
  62239. * Represents one particle of a solid particle system.
  62240. */
  62241. var SolidParticle = /** @class */ (function () {
  62242. /**
  62243. * Creates a Solid Particle object.
  62244. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  62245. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  62246. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  62247. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  62248. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  62249. * @param shapeId (integer) is the model shape identifier in the SPS.
  62250. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  62251. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  62252. */
  62253. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  62254. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  62255. /**
  62256. * particle global index
  62257. */
  62258. this.idx = 0;
  62259. /**
  62260. * The color of the particle
  62261. */
  62262. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  62263. /**
  62264. * The world space position of the particle.
  62265. */
  62266. this.position = BABYLON.Vector3.Zero();
  62267. /**
  62268. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  62269. */
  62270. this.rotation = BABYLON.Vector3.Zero();
  62271. /**
  62272. * The scaling of the particle.
  62273. */
  62274. this.scaling = BABYLON.Vector3.One();
  62275. /**
  62276. * The uvs of the particle.
  62277. */
  62278. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  62279. /**
  62280. * The current speed of the particle.
  62281. */
  62282. this.velocity = BABYLON.Vector3.Zero();
  62283. /**
  62284. * The pivot point in the particle local space.
  62285. */
  62286. this.pivot = BABYLON.Vector3.Zero();
  62287. /**
  62288. * Must the particle be translated from its pivot point in its local space ?
  62289. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  62290. * Default : false
  62291. */
  62292. this.translateFromPivot = false;
  62293. /**
  62294. * Is the particle active or not ?
  62295. */
  62296. this.alive = true;
  62297. /**
  62298. * Is the particle visible or not ?
  62299. */
  62300. this.isVisible = true;
  62301. /**
  62302. * Index of this particle in the global "positions" array (Internal use)
  62303. * @hidden
  62304. */
  62305. this._pos = 0;
  62306. /**
  62307. * @hidden Index of this particle in the global "indices" array (Internal use)
  62308. */
  62309. this._ind = 0;
  62310. /**
  62311. * ModelShape id of this particle
  62312. */
  62313. this.shapeId = 0;
  62314. /**
  62315. * Index of the particle in its shape id (Internal use)
  62316. */
  62317. this.idxInShape = 0;
  62318. /**
  62319. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  62320. */
  62321. this._stillInvisible = false;
  62322. /**
  62323. * @hidden Last computed particle rotation matrix
  62324. */
  62325. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  62326. /**
  62327. * Parent particle Id, if any.
  62328. * Default null.
  62329. */
  62330. this.parentId = null;
  62331. /**
  62332. * @hidden Internal global position in the SPS.
  62333. */
  62334. this._globalPosition = BABYLON.Vector3.Zero();
  62335. this.idx = particleIndex;
  62336. this._pos = positionIndex;
  62337. this._ind = indiceIndex;
  62338. this._model = model;
  62339. this.shapeId = shapeId;
  62340. this.idxInShape = idxInShape;
  62341. this._sps = sps;
  62342. if (modelBoundingInfo) {
  62343. this._modelBoundingInfo = modelBoundingInfo;
  62344. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  62345. }
  62346. }
  62347. Object.defineProperty(SolidParticle.prototype, "scale", {
  62348. /**
  62349. * Legacy support, changed scale to scaling
  62350. */
  62351. get: function () {
  62352. return this.scaling;
  62353. },
  62354. /**
  62355. * Legacy support, changed scale to scaling
  62356. */
  62357. set: function (scale) {
  62358. this.scaling = scale;
  62359. },
  62360. enumerable: true,
  62361. configurable: true
  62362. });
  62363. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  62364. /**
  62365. * Legacy support, changed quaternion to rotationQuaternion
  62366. */
  62367. get: function () {
  62368. return this.rotationQuaternion;
  62369. },
  62370. /**
  62371. * Legacy support, changed quaternion to rotationQuaternion
  62372. */
  62373. set: function (q) {
  62374. this.rotationQuaternion = q;
  62375. },
  62376. enumerable: true,
  62377. configurable: true
  62378. });
  62379. /**
  62380. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  62381. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  62382. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  62383. * @returns true if it intersects
  62384. */
  62385. SolidParticle.prototype.intersectsMesh = function (target) {
  62386. if (!this._boundingInfo || !target._boundingInfo) {
  62387. return false;
  62388. }
  62389. if (this._sps._bSphereOnly) {
  62390. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  62391. }
  62392. return this._boundingInfo.intersects(target._boundingInfo, false);
  62393. };
  62394. return SolidParticle;
  62395. }());
  62396. BABYLON.SolidParticle = SolidParticle;
  62397. /**
  62398. * Represents the shape of the model used by one particle of a solid particle system.
  62399. * SPS internal tool, don't use it manually.
  62400. */
  62401. var ModelShape = /** @class */ (function () {
  62402. /**
  62403. * 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.
  62404. * SPS internal tool, don't use it manually.
  62405. * @hidden
  62406. */
  62407. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  62408. /**
  62409. * length of the shape in the model indices array (internal use)
  62410. * @hidden
  62411. */
  62412. this._indicesLength = 0;
  62413. this.shapeID = id;
  62414. this._shape = shape;
  62415. this._indicesLength = indicesLength;
  62416. this._shapeUV = shapeUV;
  62417. this._positionFunction = posFunction;
  62418. this._vertexFunction = vtxFunction;
  62419. }
  62420. return ModelShape;
  62421. }());
  62422. BABYLON.ModelShape = ModelShape;
  62423. /**
  62424. * Represents a Depth Sorted Particle in the solid particle system.
  62425. */
  62426. var DepthSortedParticle = /** @class */ (function () {
  62427. function DepthSortedParticle() {
  62428. /**
  62429. * Index of the particle in the "indices" array
  62430. */
  62431. this.ind = 0;
  62432. /**
  62433. * Length of the particle shape in the "indices" array
  62434. */
  62435. this.indicesLength = 0;
  62436. /**
  62437. * Squared distance from the particle to the camera
  62438. */
  62439. this.sqDistance = 0.0;
  62440. }
  62441. return DepthSortedParticle;
  62442. }());
  62443. BABYLON.DepthSortedParticle = DepthSortedParticle;
  62444. })(BABYLON || (BABYLON = {}));
  62445. //# sourceMappingURL=babylon.solidParticle.js.map
  62446. var BABYLON;
  62447. (function (BABYLON) {
  62448. /**
  62449. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  62450. *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.
  62451. * The SPS is also a particle system. It provides some methods to manage the particles.
  62452. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  62453. *
  62454. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  62455. */
  62456. var SolidParticleSystem = /** @class */ (function () {
  62457. /**
  62458. * Creates a SPS (Solid Particle System) object.
  62459. * @param name (String) is the SPS name, this will be the underlying mesh name.
  62460. * @param scene (Scene) is the scene in which the SPS is added.
  62461. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  62462. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  62463. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  62464. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  62465. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  62466. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  62467. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  62468. */
  62469. function SolidParticleSystem(name, scene, options) {
  62470. /**
  62471. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  62472. * Example : var p = SPS.particles[i];
  62473. */
  62474. this.particles = new Array();
  62475. /**
  62476. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  62477. */
  62478. this.nbParticles = 0;
  62479. /**
  62480. * If the particles must ever face the camera (default false). Useful for planar particles.
  62481. */
  62482. this.billboard = false;
  62483. /**
  62484. * Recompute normals when adding a shape
  62485. */
  62486. this.recomputeNormals = true;
  62487. /**
  62488. * This a counter ofr your own usage. It's not set by any SPS functions.
  62489. */
  62490. this.counter = 0;
  62491. /**
  62492. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  62493. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  62494. */
  62495. this.vars = {};
  62496. /**
  62497. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  62498. * @hidden
  62499. */
  62500. this._bSphereOnly = false;
  62501. /**
  62502. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  62503. * @hidden
  62504. */
  62505. this._bSphereRadiusFactor = 1.0;
  62506. this._positions = new Array();
  62507. this._indices = new Array();
  62508. this._normals = new Array();
  62509. this._colors = new Array();
  62510. this._uvs = new Array();
  62511. this._index = 0; // indices index
  62512. this._updatable = true;
  62513. this._pickable = false;
  62514. this._isVisibilityBoxLocked = false;
  62515. this._alwaysVisible = false;
  62516. this._depthSort = false;
  62517. this._shapeCounter = 0;
  62518. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  62519. this._color = new BABYLON.Color4(0, 0, 0, 0);
  62520. this._computeParticleColor = true;
  62521. this._computeParticleTexture = true;
  62522. this._computeParticleRotation = true;
  62523. this._computeParticleVertex = false;
  62524. this._computeBoundingBox = false;
  62525. this._depthSortParticles = true;
  62526. this._cam_axisZ = BABYLON.Vector3.Zero();
  62527. this._cam_axisY = BABYLON.Vector3.Zero();
  62528. this._cam_axisX = BABYLON.Vector3.Zero();
  62529. this._axisZ = BABYLON.Axis.Z;
  62530. this._camDir = BABYLON.Vector3.Zero();
  62531. this._camInvertedPosition = BABYLON.Vector3.Zero();
  62532. this._rotMatrix = new BABYLON.Matrix();
  62533. this._invertMatrix = new BABYLON.Matrix();
  62534. this._rotated = BABYLON.Vector3.Zero();
  62535. this._quaternion = new BABYLON.Quaternion();
  62536. this._vertex = BABYLON.Vector3.Zero();
  62537. this._normal = BABYLON.Vector3.Zero();
  62538. this._yaw = 0.0;
  62539. this._pitch = 0.0;
  62540. this._roll = 0.0;
  62541. this._halfroll = 0.0;
  62542. this._halfpitch = 0.0;
  62543. this._halfyaw = 0.0;
  62544. this._sinRoll = 0.0;
  62545. this._cosRoll = 0.0;
  62546. this._sinPitch = 0.0;
  62547. this._cosPitch = 0.0;
  62548. this._sinYaw = 0.0;
  62549. this._cosYaw = 0.0;
  62550. this._mustUnrotateFixedNormals = false;
  62551. this._minimum = BABYLON.Vector3.Zero();
  62552. this._maximum = BABYLON.Vector3.Zero();
  62553. this._minBbox = BABYLON.Vector3.Zero();
  62554. this._maxBbox = BABYLON.Vector3.Zero();
  62555. this._particlesIntersect = false;
  62556. this._depthSortFunction = function (p1, p2) {
  62557. return (p2.sqDistance - p1.sqDistance);
  62558. };
  62559. this._needs32Bits = false;
  62560. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  62561. this._scaledPivot = BABYLON.Vector3.Zero();
  62562. this._particleHasParent = false;
  62563. this.name = name;
  62564. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62565. this._camera = scene.activeCamera;
  62566. this._pickable = options ? options.isPickable : false;
  62567. this._depthSort = options ? options.enableDepthSort : false;
  62568. this._particlesIntersect = options ? options.particleIntersection : false;
  62569. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  62570. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  62571. if (options && options.updatable !== undefined) {
  62572. this._updatable = options.updatable;
  62573. }
  62574. else {
  62575. this._updatable = true;
  62576. }
  62577. if (this._pickable) {
  62578. this.pickedParticles = [];
  62579. }
  62580. if (this._depthSort) {
  62581. this.depthSortedParticles = [];
  62582. }
  62583. }
  62584. /**
  62585. * Builds the SPS underlying mesh. Returns a standard Mesh.
  62586. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  62587. * @returns the created mesh
  62588. */
  62589. SolidParticleSystem.prototype.buildMesh = function () {
  62590. if (this.nbParticles === 0) {
  62591. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  62592. this.addShape(triangle, 1);
  62593. triangle.dispose();
  62594. }
  62595. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  62596. this._positions32 = new Float32Array(this._positions);
  62597. this._uvs32 = new Float32Array(this._uvs);
  62598. this._colors32 = new Float32Array(this._colors);
  62599. if (this.recomputeNormals) {
  62600. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  62601. }
  62602. this._normals32 = new Float32Array(this._normals);
  62603. this._fixedNormal32 = new Float32Array(this._normals);
  62604. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  62605. this._unrotateFixedNormals();
  62606. }
  62607. var vertexData = new BABYLON.VertexData();
  62608. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  62609. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  62610. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  62611. if (this._uvs32.length > 0) {
  62612. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  62613. }
  62614. if (this._colors32.length > 0) {
  62615. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  62616. }
  62617. var mesh = new BABYLON.Mesh(this.name, this._scene);
  62618. vertexData.applyToMesh(mesh, this._updatable);
  62619. this.mesh = mesh;
  62620. this.mesh.isPickable = this._pickable;
  62621. // free memory
  62622. if (!this._depthSort) {
  62623. this._indices = null;
  62624. }
  62625. this._positions = null;
  62626. this._normals = null;
  62627. this._uvs = null;
  62628. this._colors = null;
  62629. if (!this._updatable) {
  62630. this.particles.length = 0;
  62631. }
  62632. return mesh;
  62633. };
  62634. /**
  62635. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  62636. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  62637. * Thus the particles generated from `digest()` have their property `position` set yet.
  62638. * @param mesh ( Mesh ) is the mesh to be digested
  62639. * @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
  62640. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  62641. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  62642. * @returns the current SPS
  62643. */
  62644. SolidParticleSystem.prototype.digest = function (mesh, options) {
  62645. var size = (options && options.facetNb) || 1;
  62646. var number = (options && options.number) || 0;
  62647. var delta = (options && options.delta) || 0;
  62648. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62649. var meshInd = mesh.getIndices();
  62650. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62651. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62652. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62653. var f = 0; // facet counter
  62654. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  62655. // compute size from number
  62656. if (number) {
  62657. number = (number > totalFacets) ? totalFacets : number;
  62658. size = Math.round(totalFacets / number);
  62659. delta = 0;
  62660. }
  62661. else {
  62662. size = (size > totalFacets) ? totalFacets : size;
  62663. }
  62664. var facetPos = []; // submesh positions
  62665. var facetInd = []; // submesh indices
  62666. var facetUV = []; // submesh UV
  62667. var facetCol = []; // submesh colors
  62668. var barycenter = BABYLON.Vector3.Zero();
  62669. var sizeO = size;
  62670. while (f < totalFacets) {
  62671. size = sizeO + Math.floor((1 + delta) * Math.random());
  62672. if (f > totalFacets - size) {
  62673. size = totalFacets - f;
  62674. }
  62675. // reset temp arrays
  62676. facetPos.length = 0;
  62677. facetInd.length = 0;
  62678. facetUV.length = 0;
  62679. facetCol.length = 0;
  62680. // iterate over "size" facets
  62681. var fi = 0;
  62682. for (var j = f * 3; j < (f + size) * 3; j++) {
  62683. facetInd.push(fi);
  62684. var i = meshInd[j];
  62685. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  62686. if (meshUV) {
  62687. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  62688. }
  62689. if (meshCol) {
  62690. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  62691. }
  62692. fi++;
  62693. }
  62694. // create a model shape for each single particle
  62695. var idx = this.nbParticles;
  62696. var shape = this._posToShape(facetPos);
  62697. var shapeUV = this._uvsToShapeUV(facetUV);
  62698. // compute the barycenter of the shape
  62699. var v;
  62700. for (v = 0; v < shape.length; v++) {
  62701. barycenter.addInPlace(shape[v]);
  62702. }
  62703. barycenter.scaleInPlace(1 / shape.length);
  62704. // shift the shape from its barycenter to the origin
  62705. for (v = 0; v < shape.length; v++) {
  62706. shape[v].subtractInPlace(barycenter);
  62707. }
  62708. var bInfo;
  62709. if (this._particlesIntersect) {
  62710. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  62711. }
  62712. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  62713. // add the particle in the SPS
  62714. var currentPos = this._positions.length;
  62715. var currentInd = this._indices.length;
  62716. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  62717. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  62718. // initialize the particle position
  62719. this.particles[this.nbParticles].position.addInPlace(barycenter);
  62720. this._index += shape.length;
  62721. idx++;
  62722. this.nbParticles++;
  62723. this._shapeCounter++;
  62724. f += size;
  62725. }
  62726. return this;
  62727. };
  62728. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  62729. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  62730. var index = 0;
  62731. var idx = 0;
  62732. for (var p = 0; p < this.particles.length; p++) {
  62733. this._particle = this.particles[p];
  62734. this._shape = this._particle._model._shape;
  62735. if (this._particle.rotationQuaternion) {
  62736. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  62737. }
  62738. else {
  62739. this._yaw = this._particle.rotation.y;
  62740. this._pitch = this._particle.rotation.x;
  62741. this._roll = this._particle.rotation.z;
  62742. this._quaternionRotationYPR();
  62743. }
  62744. this._quaternionToRotationMatrix();
  62745. this._rotMatrix.invertToRef(this._invertMatrix);
  62746. for (var pt = 0; pt < this._shape.length; pt++) {
  62747. idx = index + pt * 3;
  62748. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  62749. this._fixedNormal32[idx] = this._normal.x;
  62750. this._fixedNormal32[idx + 1] = this._normal.y;
  62751. this._fixedNormal32[idx + 2] = this._normal.z;
  62752. }
  62753. index = idx + 3;
  62754. }
  62755. };
  62756. //reset copy
  62757. SolidParticleSystem.prototype._resetCopy = function () {
  62758. this._copy.position.x = 0;
  62759. this._copy.position.y = 0;
  62760. this._copy.position.z = 0;
  62761. this._copy.rotation.x = 0;
  62762. this._copy.rotation.y = 0;
  62763. this._copy.rotation.z = 0;
  62764. this._copy.rotationQuaternion = null;
  62765. this._copy.scaling.x = 1.0;
  62766. this._copy.scaling.y = 1.0;
  62767. this._copy.scaling.z = 1.0;
  62768. this._copy.uvs.x = 0;
  62769. this._copy.uvs.y = 0;
  62770. this._copy.uvs.z = 1.0;
  62771. this._copy.uvs.w = 1.0;
  62772. this._copy.color = null;
  62773. this._copy.translateFromPivot = false;
  62774. };
  62775. // _meshBuilder : inserts the shape model in the global SPS mesh
  62776. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  62777. var i;
  62778. var u = 0;
  62779. var c = 0;
  62780. var n = 0;
  62781. this._resetCopy();
  62782. if (options && options.positionFunction) { // call to custom positionFunction
  62783. options.positionFunction(this._copy, idx, idxInShape);
  62784. this._mustUnrotateFixedNormals = true;
  62785. }
  62786. if (this._copy.rotationQuaternion) {
  62787. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62788. }
  62789. else {
  62790. this._yaw = this._copy.rotation.y;
  62791. this._pitch = this._copy.rotation.x;
  62792. this._roll = this._copy.rotation.z;
  62793. this._quaternionRotationYPR();
  62794. }
  62795. this._quaternionToRotationMatrix();
  62796. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  62797. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  62798. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  62799. if (this._copy.translateFromPivot) {
  62800. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62801. }
  62802. else {
  62803. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62804. }
  62805. for (i = 0; i < shape.length; i++) {
  62806. this._vertex.x = shape[i].x;
  62807. this._vertex.y = shape[i].y;
  62808. this._vertex.z = shape[i].z;
  62809. if (options && options.vertexFunction) {
  62810. options.vertexFunction(this._copy, this._vertex, i);
  62811. }
  62812. this._vertex.x *= this._copy.scaling.x;
  62813. this._vertex.y *= this._copy.scaling.y;
  62814. this._vertex.z *= this._copy.scaling.z;
  62815. this._vertex.x -= this._scaledPivot.x;
  62816. this._vertex.y -= this._scaledPivot.y;
  62817. this._vertex.z -= this._scaledPivot.z;
  62818. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62819. this._rotated.addInPlace(this._pivotBackTranslation);
  62820. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  62821. if (meshUV) {
  62822. 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);
  62823. u += 2;
  62824. }
  62825. if (this._copy.color) {
  62826. this._color = this._copy.color;
  62827. }
  62828. else if (meshCol && meshCol[c] !== undefined) {
  62829. this._color.r = meshCol[c];
  62830. this._color.g = meshCol[c + 1];
  62831. this._color.b = meshCol[c + 2];
  62832. this._color.a = meshCol[c + 3];
  62833. }
  62834. else {
  62835. this._color.r = 1.0;
  62836. this._color.g = 1.0;
  62837. this._color.b = 1.0;
  62838. this._color.a = 1.0;
  62839. }
  62840. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  62841. c += 4;
  62842. if (!this.recomputeNormals && meshNor) {
  62843. this._normal.x = meshNor[n];
  62844. this._normal.y = meshNor[n + 1];
  62845. this._normal.z = meshNor[n + 2];
  62846. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  62847. normals.push(this._normal.x, this._normal.y, this._normal.z);
  62848. n += 3;
  62849. }
  62850. }
  62851. for (i = 0; i < meshInd.length; i++) {
  62852. var current_ind = p + meshInd[i];
  62853. indices.push(current_ind);
  62854. if (current_ind > 65535) {
  62855. this._needs32Bits = true;
  62856. }
  62857. }
  62858. if (this._pickable) {
  62859. var nbfaces = meshInd.length / 3;
  62860. for (i = 0; i < nbfaces; i++) {
  62861. this.pickedParticles.push({ idx: idx, faceId: i });
  62862. }
  62863. }
  62864. if (this._depthSort) {
  62865. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  62866. }
  62867. return this._copy;
  62868. };
  62869. // returns a shape array from positions array
  62870. SolidParticleSystem.prototype._posToShape = function (positions) {
  62871. var shape = [];
  62872. for (var i = 0; i < positions.length; i += 3) {
  62873. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  62874. }
  62875. return shape;
  62876. };
  62877. // returns a shapeUV array from a Vector4 uvs
  62878. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  62879. var shapeUV = [];
  62880. if (uvs) {
  62881. for (var i = 0; i < uvs.length; i++)
  62882. shapeUV.push(uvs[i]);
  62883. }
  62884. return shapeUV;
  62885. };
  62886. // adds a new particle object in the particles array
  62887. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  62888. if (bInfo === void 0) { bInfo = null; }
  62889. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  62890. this.particles.push(sp);
  62891. return sp;
  62892. };
  62893. /**
  62894. * Adds some particles to the SPS from the model shape. Returns the shape id.
  62895. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  62896. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  62897. * @param nb (positive integer) the number of particles to be created from this model
  62898. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  62899. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  62900. * @returns the number of shapes in the system
  62901. */
  62902. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  62903. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62904. var meshInd = mesh.getIndices();
  62905. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62906. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62907. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62908. var bbInfo;
  62909. if (this._particlesIntersect) {
  62910. bbInfo = mesh.getBoundingInfo();
  62911. }
  62912. var shape = this._posToShape(meshPos);
  62913. var shapeUV = this._uvsToShapeUV(meshUV);
  62914. var posfunc = options ? options.positionFunction : null;
  62915. var vtxfunc = options ? options.vertexFunction : null;
  62916. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  62917. // particles
  62918. var sp;
  62919. var currentCopy;
  62920. var idx = this.nbParticles;
  62921. for (var i = 0; i < nb; i++) {
  62922. var currentPos = this._positions.length;
  62923. var currentInd = this._indices.length;
  62924. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  62925. if (this._updatable) {
  62926. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  62927. sp.position.copyFrom(currentCopy.position);
  62928. sp.rotation.copyFrom(currentCopy.rotation);
  62929. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  62930. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  62931. }
  62932. if (currentCopy.color && sp.color) {
  62933. sp.color.copyFrom(currentCopy.color);
  62934. }
  62935. sp.scaling.copyFrom(currentCopy.scaling);
  62936. sp.uvs.copyFrom(currentCopy.uvs);
  62937. }
  62938. this._index += shape.length;
  62939. idx++;
  62940. }
  62941. this.nbParticles += nb;
  62942. this._shapeCounter++;
  62943. return this._shapeCounter - 1;
  62944. };
  62945. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  62946. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  62947. this._resetCopy();
  62948. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  62949. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  62950. }
  62951. if (this._copy.rotationQuaternion) {
  62952. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62953. }
  62954. else {
  62955. this._yaw = this._copy.rotation.y;
  62956. this._pitch = this._copy.rotation.x;
  62957. this._roll = this._copy.rotation.z;
  62958. this._quaternionRotationYPR();
  62959. }
  62960. this._quaternionToRotationMatrix();
  62961. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62962. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62963. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62964. if (this._copy.translateFromPivot) {
  62965. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62966. }
  62967. else {
  62968. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62969. }
  62970. this._shape = particle._model._shape;
  62971. for (var pt = 0; pt < this._shape.length; pt++) {
  62972. this._vertex.x = this._shape[pt].x;
  62973. this._vertex.y = this._shape[pt].y;
  62974. this._vertex.z = this._shape[pt].z;
  62975. if (particle._model._vertexFunction) {
  62976. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  62977. }
  62978. this._vertex.x *= this._copy.scaling.x;
  62979. this._vertex.y *= this._copy.scaling.y;
  62980. this._vertex.z *= this._copy.scaling.z;
  62981. this._vertex.x -= this._scaledPivot.x;
  62982. this._vertex.y -= this._scaledPivot.y;
  62983. this._vertex.z -= this._scaledPivot.z;
  62984. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62985. this._rotated.addInPlace(this._pivotBackTranslation);
  62986. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  62987. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  62988. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  62989. }
  62990. particle.position.x = 0.0;
  62991. particle.position.y = 0.0;
  62992. particle.position.z = 0.0;
  62993. particle.rotation.x = 0.0;
  62994. particle.rotation.y = 0.0;
  62995. particle.rotation.z = 0.0;
  62996. particle.rotationQuaternion = null;
  62997. particle.scaling.x = 1.0;
  62998. particle.scaling.y = 1.0;
  62999. particle.scaling.z = 1.0;
  63000. particle.uvs.x = 0.0;
  63001. particle.uvs.y = 0.0;
  63002. particle.uvs.z = 1.0;
  63003. particle.uvs.w = 1.0;
  63004. particle.pivot.x = 0.0;
  63005. particle.pivot.y = 0.0;
  63006. particle.pivot.z = 0.0;
  63007. particle.translateFromPivot = false;
  63008. particle.parentId = null;
  63009. };
  63010. /**
  63011. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  63012. * @returns the SPS.
  63013. */
  63014. SolidParticleSystem.prototype.rebuildMesh = function () {
  63015. for (var p = 0; p < this.particles.length; p++) {
  63016. this._rebuildParticle(this.particles[p]);
  63017. }
  63018. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63019. return this;
  63020. };
  63021. /**
  63022. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  63023. * This method calls `updateParticle()` for each particle of the SPS.
  63024. * For an animated SPS, it is usually called within the render loop.
  63025. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  63026. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  63027. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  63028. * @returns the SPS.
  63029. */
  63030. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  63031. if (start === void 0) { start = 0; }
  63032. if (end === void 0) { end = this.nbParticles - 1; }
  63033. if (update === void 0) { update = true; }
  63034. if (!this._updatable) {
  63035. return this;
  63036. }
  63037. // custom beforeUpdate
  63038. this.beforeUpdateParticles(start, end, update);
  63039. this._cam_axisX.x = 1.0;
  63040. this._cam_axisX.y = 0.0;
  63041. this._cam_axisX.z = 0.0;
  63042. this._cam_axisY.x = 0.0;
  63043. this._cam_axisY.y = 1.0;
  63044. this._cam_axisY.z = 0.0;
  63045. this._cam_axisZ.x = 0.0;
  63046. this._cam_axisZ.y = 0.0;
  63047. this._cam_axisZ.z = 1.0;
  63048. // cases when the World Matrix is to be computed first
  63049. if (this.billboard || this._depthSort) {
  63050. this.mesh.computeWorldMatrix(true);
  63051. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  63052. }
  63053. // if the particles will always face the camera
  63054. if (this.billboard) {
  63055. // compute the camera position and un-rotate it by the current mesh rotation
  63056. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  63057. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  63058. this._cam_axisZ.normalize();
  63059. // same for camera up vector extracted from the cam view matrix
  63060. var view = this._camera.getViewMatrix(true);
  63061. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  63062. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  63063. this._cam_axisY.normalize();
  63064. this._cam_axisX.normalize();
  63065. }
  63066. // if depthSort, compute the camera global position in the mesh local system
  63067. if (this._depthSort) {
  63068. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  63069. }
  63070. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  63071. var idx = 0; // current position index in the global array positions32
  63072. var index = 0; // position start index in the global array positions32 of the current particle
  63073. var colidx = 0; // current color index in the global array colors32
  63074. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  63075. var uvidx = 0; // current uv index in the global array uvs32
  63076. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  63077. var pt = 0; // current index in the particle model shape
  63078. if (this.mesh.isFacetDataEnabled) {
  63079. this._computeBoundingBox = true;
  63080. }
  63081. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  63082. if (this._computeBoundingBox) {
  63083. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  63084. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  63085. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  63086. }
  63087. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  63088. if (this.mesh._boundingInfo) {
  63089. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  63090. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  63091. }
  63092. }
  63093. }
  63094. // particle loop
  63095. index = this.particles[start]._pos;
  63096. var vpos = (index / 3) | 0;
  63097. colorIndex = vpos * 4;
  63098. uvIndex = vpos * 2;
  63099. for (var p = start; p <= end; p++) {
  63100. this._particle = this.particles[p];
  63101. this._shape = this._particle._model._shape;
  63102. this._shapeUV = this._particle._model._shapeUV;
  63103. // call to custom user function to update the particle properties
  63104. this.updateParticle(this._particle);
  63105. // camera-particle distance for depth sorting
  63106. if (this._depthSort && this._depthSortParticles) {
  63107. var dsp = this.depthSortedParticles[p];
  63108. dsp.ind = this._particle._ind;
  63109. dsp.indicesLength = this._particle._model._indicesLength;
  63110. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  63111. }
  63112. // skip the computations for inactive or already invisible particles
  63113. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  63114. // increment indexes for the next particle
  63115. pt = this._shape.length;
  63116. index += pt * 3;
  63117. colorIndex += pt * 4;
  63118. uvIndex += pt * 2;
  63119. continue;
  63120. }
  63121. if (this._particle.isVisible) {
  63122. this._particle._stillInvisible = false; // un-mark permanent invisibility
  63123. this._particleHasParent = (this._particle.parentId !== null);
  63124. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63125. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63126. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63127. // particle rotation matrix
  63128. if (this.billboard) {
  63129. this._particle.rotation.x = 0.0;
  63130. this._particle.rotation.y = 0.0;
  63131. }
  63132. if (this._computeParticleRotation || this.billboard) {
  63133. if (this._particle.rotationQuaternion) {
  63134. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63135. }
  63136. else {
  63137. this._yaw = this._particle.rotation.y;
  63138. this._pitch = this._particle.rotation.x;
  63139. this._roll = this._particle.rotation.z;
  63140. this._quaternionRotationYPR();
  63141. }
  63142. this._quaternionToRotationMatrix();
  63143. }
  63144. if (this._particleHasParent) {
  63145. this._parent = this.particles[this._particle.parentId];
  63146. 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];
  63147. 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];
  63148. 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];
  63149. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  63150. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  63151. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  63152. if (this._computeParticleRotation || this.billboard) {
  63153. 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];
  63154. 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];
  63155. 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];
  63156. 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];
  63157. 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];
  63158. 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];
  63159. 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];
  63160. 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];
  63161. 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];
  63162. }
  63163. }
  63164. else {
  63165. this._particle._globalPosition.x = this._particle.position.x;
  63166. this._particle._globalPosition.y = this._particle.position.y;
  63167. this._particle._globalPosition.z = this._particle.position.z;
  63168. if (this._computeParticleRotation || this.billboard) {
  63169. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  63170. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  63171. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  63172. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  63173. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  63174. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  63175. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  63176. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  63177. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  63178. }
  63179. }
  63180. if (this._particle.translateFromPivot) {
  63181. this._pivotBackTranslation.x = 0.0;
  63182. this._pivotBackTranslation.y = 0.0;
  63183. this._pivotBackTranslation.z = 0.0;
  63184. }
  63185. else {
  63186. this._pivotBackTranslation.x = this._scaledPivot.x;
  63187. this._pivotBackTranslation.y = this._scaledPivot.y;
  63188. this._pivotBackTranslation.z = this._scaledPivot.z;
  63189. }
  63190. // particle vertex loop
  63191. for (pt = 0; pt < this._shape.length; pt++) {
  63192. idx = index + pt * 3;
  63193. colidx = colorIndex + pt * 4;
  63194. uvidx = uvIndex + pt * 2;
  63195. this._vertex.x = this._shape[pt].x;
  63196. this._vertex.y = this._shape[pt].y;
  63197. this._vertex.z = this._shape[pt].z;
  63198. if (this._computeParticleVertex) {
  63199. this.updateParticleVertex(this._particle, this._vertex, pt);
  63200. }
  63201. // positions
  63202. this._vertex.x *= this._particle.scaling.x;
  63203. this._vertex.y *= this._particle.scaling.y;
  63204. this._vertex.z *= this._particle.scaling.z;
  63205. this._vertex.x -= this._scaledPivot.x;
  63206. this._vertex.y -= this._scaledPivot.y;
  63207. this._vertex.z -= this._scaledPivot.z;
  63208. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63209. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63210. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63211. this._rotated.x += this._pivotBackTranslation.x;
  63212. this._rotated.y += this._pivotBackTranslation.y;
  63213. this._rotated.z += this._pivotBackTranslation.z;
  63214. 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;
  63215. 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;
  63216. 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;
  63217. if (this._computeBoundingBox) {
  63218. if (this._positions32[idx] < this._minimum.x) {
  63219. this._minimum.x = this._positions32[idx];
  63220. }
  63221. if (this._positions32[idx] > this._maximum.x) {
  63222. this._maximum.x = this._positions32[idx];
  63223. }
  63224. if (this._positions32[idx + 1] < this._minimum.y) {
  63225. this._minimum.y = this._positions32[idx + 1];
  63226. }
  63227. if (this._positions32[idx + 1] > this._maximum.y) {
  63228. this._maximum.y = this._positions32[idx + 1];
  63229. }
  63230. if (this._positions32[idx + 2] < this._minimum.z) {
  63231. this._minimum.z = this._positions32[idx + 2];
  63232. }
  63233. if (this._positions32[idx + 2] > this._maximum.z) {
  63234. this._maximum.z = this._positions32[idx + 2];
  63235. }
  63236. }
  63237. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  63238. if (!this._computeParticleVertex) {
  63239. this._normal.x = this._fixedNormal32[idx];
  63240. this._normal.y = this._fixedNormal32[idx + 1];
  63241. this._normal.z = this._fixedNormal32[idx + 2];
  63242. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  63243. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  63244. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  63245. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  63246. 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;
  63247. 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;
  63248. }
  63249. if (this._computeParticleColor && this._particle.color) {
  63250. this._colors32[colidx] = this._particle.color.r;
  63251. this._colors32[colidx + 1] = this._particle.color.g;
  63252. this._colors32[colidx + 2] = this._particle.color.b;
  63253. this._colors32[colidx + 3] = this._particle.color.a;
  63254. }
  63255. if (this._computeParticleTexture) {
  63256. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63257. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63258. }
  63259. }
  63260. }
  63261. // particle just set invisible : scaled to zero and positioned at the origin
  63262. else {
  63263. this._particle._stillInvisible = true; // mark the particle as invisible
  63264. for (pt = 0; pt < this._shape.length; pt++) {
  63265. idx = index + pt * 3;
  63266. colidx = colorIndex + pt * 4;
  63267. uvidx = uvIndex + pt * 2;
  63268. this._positions32[idx] = 0.0;
  63269. this._positions32[idx + 1] = 0.0;
  63270. this._positions32[idx + 2] = 0.0;
  63271. this._normals32[idx] = 0.0;
  63272. this._normals32[idx + 1] = 0.0;
  63273. this._normals32[idx + 2] = 0.0;
  63274. if (this._computeParticleColor && this._particle.color) {
  63275. this._colors32[colidx] = this._particle.color.r;
  63276. this._colors32[colidx + 1] = this._particle.color.g;
  63277. this._colors32[colidx + 2] = this._particle.color.b;
  63278. this._colors32[colidx + 3] = this._particle.color.a;
  63279. }
  63280. if (this._computeParticleTexture) {
  63281. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63282. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63283. }
  63284. }
  63285. }
  63286. // if the particle intersections must be computed : update the bbInfo
  63287. if (this._particlesIntersect) {
  63288. var bInfo = this._particle._boundingInfo;
  63289. var bBox = bInfo.boundingBox;
  63290. var bSphere = bInfo.boundingSphere;
  63291. if (!this._bSphereOnly) {
  63292. // place, scale and rotate the particle bbox within the SPS local system, then update it
  63293. for (var b = 0; b < bBox.vectors.length; b++) {
  63294. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  63295. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  63296. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  63297. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63298. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63299. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63300. 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;
  63301. 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;
  63302. 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;
  63303. }
  63304. bBox._update(this.mesh._worldMatrix);
  63305. }
  63306. // place and scale the particle bouding sphere in the SPS local system, then update it
  63307. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  63308. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  63309. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  63310. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  63311. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  63312. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  63313. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  63314. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  63315. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  63316. 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));
  63317. bSphere._update(this.mesh._worldMatrix);
  63318. }
  63319. // increment indexes for the next particle
  63320. index = idx + 3;
  63321. colorIndex = colidx + 4;
  63322. uvIndex = uvidx + 2;
  63323. }
  63324. // if the VBO must be updated
  63325. if (update) {
  63326. if (this._computeParticleColor) {
  63327. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  63328. }
  63329. if (this._computeParticleTexture) {
  63330. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  63331. }
  63332. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63333. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  63334. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  63335. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  63336. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  63337. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  63338. for (var i = 0; i < this._normals32.length; i++) {
  63339. this._fixedNormal32[i] = this._normals32[i];
  63340. }
  63341. }
  63342. if (!this.mesh.areNormalsFrozen) {
  63343. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  63344. }
  63345. }
  63346. if (this._depthSort && this._depthSortParticles) {
  63347. this.depthSortedParticles.sort(this._depthSortFunction);
  63348. var dspl = this.depthSortedParticles.length;
  63349. var sorted = 0;
  63350. var lind = 0;
  63351. var sind = 0;
  63352. var sid = 0;
  63353. for (sorted = 0; sorted < dspl; sorted++) {
  63354. lind = this.depthSortedParticles[sorted].indicesLength;
  63355. sind = this.depthSortedParticles[sorted].ind;
  63356. for (var i = 0; i < lind; i++) {
  63357. this._indices32[sid] = this._indices[sind + i];
  63358. sid++;
  63359. }
  63360. }
  63361. this.mesh.updateIndices(this._indices32);
  63362. }
  63363. }
  63364. if (this._computeBoundingBox) {
  63365. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  63366. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  63367. }
  63368. this.afterUpdateParticles(start, end, update);
  63369. return this;
  63370. };
  63371. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  63372. this._halfroll = this._roll * 0.5;
  63373. this._halfpitch = this._pitch * 0.5;
  63374. this._halfyaw = this._yaw * 0.5;
  63375. this._sinRoll = Math.sin(this._halfroll);
  63376. this._cosRoll = Math.cos(this._halfroll);
  63377. this._sinPitch = Math.sin(this._halfpitch);
  63378. this._cosPitch = Math.cos(this._halfpitch);
  63379. this._sinYaw = Math.sin(this._halfyaw);
  63380. this._cosYaw = Math.cos(this._halfyaw);
  63381. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  63382. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  63383. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  63384. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  63385. };
  63386. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  63387. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  63388. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  63389. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  63390. this._rotMatrix.m[3] = 0;
  63391. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  63392. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  63393. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  63394. this._rotMatrix.m[7] = 0;
  63395. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  63396. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  63397. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  63398. this._rotMatrix.m[11] = 0;
  63399. this._rotMatrix.m[12] = 0;
  63400. this._rotMatrix.m[13] = 0;
  63401. this._rotMatrix.m[14] = 0;
  63402. this._rotMatrix.m[15] = 1.0;
  63403. };
  63404. /**
  63405. * Disposes the SPS.
  63406. */
  63407. SolidParticleSystem.prototype.dispose = function () {
  63408. this.mesh.dispose();
  63409. this.vars = null;
  63410. // drop references to internal big arrays for the GC
  63411. this._positions = null;
  63412. this._indices = null;
  63413. this._normals = null;
  63414. this._uvs = null;
  63415. this._colors = null;
  63416. this._indices32 = null;
  63417. this._positions32 = null;
  63418. this._normals32 = null;
  63419. this._fixedNormal32 = null;
  63420. this._uvs32 = null;
  63421. this._colors32 = null;
  63422. this.pickedParticles = null;
  63423. };
  63424. /**
  63425. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  63426. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63427. * @returns the SPS.
  63428. */
  63429. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  63430. if (!this._isVisibilityBoxLocked) {
  63431. this.mesh.refreshBoundingInfo();
  63432. }
  63433. return this;
  63434. };
  63435. /**
  63436. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  63437. * @param size the size (float) of the visibility box
  63438. * note : this doesn't lock the SPS mesh bounding box.
  63439. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63440. */
  63441. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  63442. var vis = size / 2;
  63443. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  63444. };
  63445. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  63446. /**
  63447. * Gets whether the SPS as always visible or not
  63448. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63449. */
  63450. get: function () {
  63451. return this._alwaysVisible;
  63452. },
  63453. /**
  63454. * Sets the SPS as always visible or not
  63455. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63456. */
  63457. set: function (val) {
  63458. this._alwaysVisible = val;
  63459. this.mesh.alwaysSelectAsActiveMesh = val;
  63460. },
  63461. enumerable: true,
  63462. configurable: true
  63463. });
  63464. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  63465. /**
  63466. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63467. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63468. */
  63469. get: function () {
  63470. return this._isVisibilityBoxLocked;
  63471. },
  63472. /**
  63473. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63474. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63475. */
  63476. set: function (val) {
  63477. this._isVisibilityBoxLocked = val;
  63478. var boundingInfo = this.mesh.getBoundingInfo();
  63479. boundingInfo.isLocked = val;
  63480. },
  63481. enumerable: true,
  63482. configurable: true
  63483. });
  63484. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  63485. /**
  63486. * Gets if `setParticles()` computes the particle rotations or not.
  63487. * Default value : true. The SPS is faster when it's set to false.
  63488. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63489. */
  63490. get: function () {
  63491. return this._computeParticleRotation;
  63492. },
  63493. /**
  63494. * Tells to `setParticles()` to compute the particle rotations or not.
  63495. * Default value : true. The SPS is faster when it's set to false.
  63496. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63497. */
  63498. set: function (val) {
  63499. this._computeParticleRotation = val;
  63500. },
  63501. enumerable: true,
  63502. configurable: true
  63503. });
  63504. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  63505. /**
  63506. * Gets if `setParticles()` computes the particle colors or not.
  63507. * Default value : true. The SPS is faster when it's set to false.
  63508. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63509. */
  63510. get: function () {
  63511. return this._computeParticleColor;
  63512. },
  63513. /**
  63514. * Tells to `setParticles()` to compute the particle colors or not.
  63515. * Default value : true. The SPS is faster when it's set to false.
  63516. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63517. */
  63518. set: function (val) {
  63519. this._computeParticleColor = val;
  63520. },
  63521. enumerable: true,
  63522. configurable: true
  63523. });
  63524. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  63525. /**
  63526. * Gets if `setParticles()` computes the particle textures or not.
  63527. * Default value : true. The SPS is faster when it's set to false.
  63528. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  63529. */
  63530. get: function () {
  63531. return this._computeParticleTexture;
  63532. },
  63533. set: function (val) {
  63534. this._computeParticleTexture = val;
  63535. },
  63536. enumerable: true,
  63537. configurable: true
  63538. });
  63539. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  63540. /**
  63541. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  63542. * Default value : false. The SPS is faster when it's set to false.
  63543. * Note : the particle custom vertex positions aren't stored values.
  63544. */
  63545. get: function () {
  63546. return this._computeParticleVertex;
  63547. },
  63548. /**
  63549. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  63550. * Default value : false. The SPS is faster when it's set to false.
  63551. * Note : the particle custom vertex positions aren't stored values.
  63552. */
  63553. set: function (val) {
  63554. this._computeParticleVertex = val;
  63555. },
  63556. enumerable: true,
  63557. configurable: true
  63558. });
  63559. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  63560. /**
  63561. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  63562. */
  63563. get: function () {
  63564. return this._computeBoundingBox;
  63565. },
  63566. /**
  63567. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  63568. */
  63569. set: function (val) {
  63570. this._computeBoundingBox = val;
  63571. },
  63572. enumerable: true,
  63573. configurable: true
  63574. });
  63575. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  63576. /**
  63577. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  63578. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63579. * Default : `true`
  63580. */
  63581. get: function () {
  63582. return this._depthSortParticles;
  63583. },
  63584. /**
  63585. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  63586. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63587. * Default : `true`
  63588. */
  63589. set: function (val) {
  63590. this._depthSortParticles = val;
  63591. },
  63592. enumerable: true,
  63593. configurable: true
  63594. });
  63595. // =======================================================================
  63596. // Particle behavior logic
  63597. // these following methods may be overwritten by the user to fit his needs
  63598. /**
  63599. * This function does nothing. It may be overwritten to set all the particle first values.
  63600. * The SPS doesn't call this function, you may have to call it by your own.
  63601. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63602. */
  63603. SolidParticleSystem.prototype.initParticles = function () {
  63604. };
  63605. /**
  63606. * This function does nothing. It may be overwritten to recycle a particle.
  63607. * The SPS doesn't call this function, you may have to call it by your own.
  63608. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63609. * @param particle The particle to recycle
  63610. * @returns the recycled particle
  63611. */
  63612. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  63613. return particle;
  63614. };
  63615. /**
  63616. * Updates a particle : this function should be overwritten by the user.
  63617. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  63618. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63619. * @example : just set a particle position or velocity and recycle conditions
  63620. * @param particle The particle to update
  63621. * @returns the updated particle
  63622. */
  63623. SolidParticleSystem.prototype.updateParticle = function (particle) {
  63624. return particle;
  63625. };
  63626. /**
  63627. * Updates a vertex of a particle : it can be overwritten by the user.
  63628. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  63629. * @param particle the current particle
  63630. * @param vertex the current index of the current particle
  63631. * @param pt the index of the current vertex in the particle shape
  63632. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  63633. * @example : just set a vertex particle position
  63634. * @returns the updated vertex
  63635. */
  63636. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  63637. return vertex;
  63638. };
  63639. /**
  63640. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  63641. * This does nothing and may be overwritten by the user.
  63642. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63643. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63644. * @param update the boolean update value actually passed to setParticles()
  63645. */
  63646. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  63647. };
  63648. /**
  63649. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  63650. * This will be passed three parameters.
  63651. * This does nothing and may be overwritten by the user.
  63652. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63653. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63654. * @param update the boolean update value actually passed to setParticles()
  63655. */
  63656. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  63657. };
  63658. return SolidParticleSystem;
  63659. }());
  63660. BABYLON.SolidParticleSystem = SolidParticleSystem;
  63661. })(BABYLON || (BABYLON = {}));
  63662. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  63663. var BABYLON;
  63664. (function (BABYLON) {
  63665. /**
  63666. * Class containing static functions to help procedurally build meshes
  63667. */
  63668. var MeshBuilder = /** @class */ (function () {
  63669. function MeshBuilder() {
  63670. }
  63671. MeshBuilder.updateSideOrientation = function (orientation) {
  63672. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  63673. return BABYLON.Mesh.DOUBLESIDE;
  63674. }
  63675. if (orientation === undefined || orientation === null) {
  63676. return BABYLON.Mesh.FRONTSIDE;
  63677. }
  63678. return orientation;
  63679. };
  63680. /**
  63681. * Creates a box mesh
  63682. * * The parameter `size` sets the size (float) of each box side (default 1)
  63683. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  63684. * * 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)
  63685. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  63686. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63687. * * 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
  63688. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63689. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  63690. * @param name defines the name of the mesh
  63691. * @param options defines the options used to create the mesh
  63692. * @param scene defines the hosting scene
  63693. * @returns the box mesh
  63694. */
  63695. MeshBuilder.CreateBox = function (name, options, scene) {
  63696. if (scene === void 0) { scene = null; }
  63697. var box = new BABYLON.Mesh(name, scene);
  63698. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63699. box._originalBuilderSideOrientation = options.sideOrientation;
  63700. var vertexData = BABYLON.VertexData.CreateBox(options);
  63701. vertexData.applyToMesh(box, options.updatable);
  63702. return box;
  63703. };
  63704. /**
  63705. * Creates a sphere mesh
  63706. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  63707. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)
  63708. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  63709. * * 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
  63710. * * 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)
  63711. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63712. * * 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
  63713. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63714. * @param name defines the name of the mesh
  63715. * @param options defines the options used to create the mesh
  63716. * @param scene defines the hosting scene
  63717. * @returns the sphere mesh
  63718. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  63719. */
  63720. MeshBuilder.CreateSphere = function (name, options, scene) {
  63721. var sphere = new BABYLON.Mesh(name, scene);
  63722. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63723. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63724. var vertexData = BABYLON.VertexData.CreateSphere(options);
  63725. vertexData.applyToMesh(sphere, options.updatable);
  63726. return sphere;
  63727. };
  63728. /**
  63729. * Creates a plane polygonal mesh. By default, this is a disc
  63730. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  63731. * * 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
  63732. * * 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
  63733. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63734. * * 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
  63735. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63736. * @param name defines the name of the mesh
  63737. * @param options defines the options used to create the mesh
  63738. * @param scene defines the hosting scene
  63739. * @returns the plane polygonal mesh
  63740. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  63741. */
  63742. MeshBuilder.CreateDisc = function (name, options, scene) {
  63743. if (scene === void 0) { scene = null; }
  63744. var disc = new BABYLON.Mesh(name, scene);
  63745. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63746. disc._originalBuilderSideOrientation = options.sideOrientation;
  63747. var vertexData = BABYLON.VertexData.CreateDisc(options);
  63748. vertexData.applyToMesh(disc, options.updatable);
  63749. return disc;
  63750. };
  63751. /**
  63752. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  63753. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  63754. * * 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`)
  63755. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  63756. * * 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
  63757. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63758. * * 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
  63759. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63760. * @param name defines the name of the mesh
  63761. * @param options defines the options used to create the mesh
  63762. * @param scene defines the hosting scene
  63763. * @returns the icosahedron mesh
  63764. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  63765. */
  63766. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  63767. var sphere = new BABYLON.Mesh(name, scene);
  63768. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63769. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63770. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  63771. vertexData.applyToMesh(sphere, options.updatable);
  63772. return sphere;
  63773. };
  63774. ;
  63775. /**
  63776. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  63777. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  63778. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  63779. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  63780. * * 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
  63781. * * 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
  63782. * * 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
  63783. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63784. * * 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
  63785. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63786. * * 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
  63787. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  63788. * * 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
  63789. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  63790. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63791. * @param name defines the name of the mesh
  63792. * @param options defines the options used to create the mesh
  63793. * @param scene defines the hosting scene
  63794. * @returns the ribbon mesh
  63795. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  63796. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63797. */
  63798. MeshBuilder.CreateRibbon = function (name, options, scene) {
  63799. if (scene === void 0) { scene = null; }
  63800. var pathArray = options.pathArray;
  63801. var closeArray = options.closeArray;
  63802. var closePath = options.closePath;
  63803. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63804. var instance = options.instance;
  63805. var updatable = options.updatable;
  63806. if (instance) { // existing ribbon instance update
  63807. // positionFunction : ribbon case
  63808. // only pathArray and sideOrientation parameters are taken into account for positions update
  63809. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  63810. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  63811. var positionFunction = function (positions) {
  63812. var minlg = pathArray[0].length;
  63813. var i = 0;
  63814. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  63815. for (var si = 1; si <= ns; si++) {
  63816. for (var p = 0; p < pathArray.length; p++) {
  63817. var path = pathArray[p];
  63818. var l = path.length;
  63819. minlg = (minlg < l) ? minlg : l;
  63820. var j = 0;
  63821. while (j < minlg) {
  63822. positions[i] = path[j].x;
  63823. positions[i + 1] = path[j].y;
  63824. positions[i + 2] = path[j].z;
  63825. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  63826. BABYLON.Tmp.Vector3[0].x = path[j].x;
  63827. }
  63828. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  63829. BABYLON.Tmp.Vector3[1].x = path[j].x;
  63830. }
  63831. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  63832. BABYLON.Tmp.Vector3[0].y = path[j].y;
  63833. }
  63834. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  63835. BABYLON.Tmp.Vector3[1].y = path[j].y;
  63836. }
  63837. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  63838. BABYLON.Tmp.Vector3[0].z = path[j].z;
  63839. }
  63840. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  63841. BABYLON.Tmp.Vector3[1].z = path[j].z;
  63842. }
  63843. j++;
  63844. i += 3;
  63845. }
  63846. if (instance._closePath) {
  63847. positions[i] = path[0].x;
  63848. positions[i + 1] = path[0].y;
  63849. positions[i + 2] = path[0].z;
  63850. i += 3;
  63851. }
  63852. }
  63853. }
  63854. };
  63855. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63856. positionFunction(positions);
  63857. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  63858. instance._boundingInfo.update(instance._worldMatrix);
  63859. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63860. if (options.colors) {
  63861. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63862. for (var c = 0; c < options.colors.length; c++) {
  63863. colors[c * 4] = options.colors[c].r;
  63864. colors[c * 4 + 1] = options.colors[c].g;
  63865. colors[c * 4 + 2] = options.colors[c].b;
  63866. colors[c * 4 + 3] = options.colors[c].a;
  63867. }
  63868. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  63869. }
  63870. if (options.uvs) {
  63871. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63872. for (var i = 0; i < options.uvs.length; i++) {
  63873. uvs[i * 2] = options.uvs[i].x;
  63874. uvs[i * 2 + 1] = options.uvs[i].y;
  63875. }
  63876. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  63877. }
  63878. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  63879. var indices = instance.getIndices();
  63880. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63881. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  63882. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  63883. if (instance._closePath) {
  63884. var indexFirst = 0;
  63885. var indexLast = 0;
  63886. for (var p = 0; p < pathArray.length; p++) {
  63887. indexFirst = instance._idx[p] * 3;
  63888. if (p + 1 < pathArray.length) {
  63889. indexLast = (instance._idx[p + 1] - 1) * 3;
  63890. }
  63891. else {
  63892. indexLast = normals.length - 3;
  63893. }
  63894. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  63895. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  63896. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  63897. normals[indexLast] = normals[indexFirst];
  63898. normals[indexLast + 1] = normals[indexFirst + 1];
  63899. normals[indexLast + 2] = normals[indexFirst + 2];
  63900. }
  63901. }
  63902. if (!(instance.areNormalsFrozen)) {
  63903. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  63904. }
  63905. }
  63906. return instance;
  63907. }
  63908. else { // new ribbon creation
  63909. var ribbon = new BABYLON.Mesh(name, scene);
  63910. ribbon._originalBuilderSideOrientation = sideOrientation;
  63911. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  63912. if (closePath) {
  63913. ribbon._idx = vertexData._idx;
  63914. }
  63915. ribbon._closePath = closePath;
  63916. ribbon._closeArray = closeArray;
  63917. vertexData.applyToMesh(ribbon, updatable);
  63918. return ribbon;
  63919. }
  63920. };
  63921. /**
  63922. * Creates a cylinder or a cone mesh
  63923. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  63924. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  63925. * * 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.
  63926. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  63927. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  63928. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  63929. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  63930. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  63931. * * 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).
  63932. * * 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
  63933. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  63934. * * 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
  63935. * * 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.
  63936. * * If `enclose` is false, a ring surface is one element.
  63937. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  63938. * * 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
  63939. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63940. * * 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
  63941. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63942. * @param name defines the name of the mesh
  63943. * @param options defines the options used to create the mesh
  63944. * @param scene defines the hosting scene
  63945. * @returns the cylinder mesh
  63946. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  63947. */
  63948. MeshBuilder.CreateCylinder = function (name, options, scene) {
  63949. var cylinder = new BABYLON.Mesh(name, scene);
  63950. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63951. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  63952. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  63953. vertexData.applyToMesh(cylinder, options.updatable);
  63954. return cylinder;
  63955. };
  63956. /**
  63957. * Creates a torus mesh
  63958. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  63959. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  63960. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  63961. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63962. * * 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
  63963. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63964. * @param name defines the name of the mesh
  63965. * @param options defines the options used to create the mesh
  63966. * @param scene defines the hosting scene
  63967. * @returns the torus mesh
  63968. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  63969. */
  63970. MeshBuilder.CreateTorus = function (name, options, scene) {
  63971. var torus = new BABYLON.Mesh(name, scene);
  63972. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63973. torus._originalBuilderSideOrientation = options.sideOrientation;
  63974. var vertexData = BABYLON.VertexData.CreateTorus(options);
  63975. vertexData.applyToMesh(torus, options.updatable);
  63976. return torus;
  63977. };
  63978. /**
  63979. * Creates a torus knot mesh
  63980. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  63981. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  63982. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  63983. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  63984. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63985. * * 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
  63986. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63987. * @param name defines the name of the mesh
  63988. * @param options defines the options used to create the mesh
  63989. * @param scene defines the hosting scene
  63990. * @returns the torus knot mesh
  63991. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  63992. */
  63993. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  63994. var torusKnot = new BABYLON.Mesh(name, scene);
  63995. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63996. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  63997. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  63998. vertexData.applyToMesh(torusKnot, options.updatable);
  63999. return torusKnot;
  64000. };
  64001. /**
  64002. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  64003. * * 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
  64004. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  64005. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  64006. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  64007. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  64008. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  64009. * * 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
  64010. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  64011. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64012. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  64013. * @param name defines the name of the new line system
  64014. * @param options defines the options used to create the line system
  64015. * @param scene defines the hosting scene
  64016. * @returns a new line system mesh
  64017. */
  64018. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  64019. var instance = options.instance;
  64020. var lines = options.lines;
  64021. var colors = options.colors;
  64022. if (instance) { // lines update
  64023. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64024. var vertexColor;
  64025. var lineColors;
  64026. if (colors) {
  64027. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64028. }
  64029. var i = 0;
  64030. var c = 0;
  64031. for (var l = 0; l < lines.length; l++) {
  64032. var points = lines[l];
  64033. for (var p = 0; p < points.length; p++) {
  64034. positions[i] = points[p].x;
  64035. positions[i + 1] = points[p].y;
  64036. positions[i + 2] = points[p].z;
  64037. if (colors && vertexColor) {
  64038. lineColors = colors[l];
  64039. vertexColor[c] = lineColors[p].r;
  64040. vertexColor[c + 1] = lineColors[p].g;
  64041. vertexColor[c + 2] = lineColors[p].b;
  64042. vertexColor[c + 3] = lineColors[p].a;
  64043. c += 4;
  64044. }
  64045. i += 3;
  64046. }
  64047. }
  64048. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64049. if (colors && vertexColor) {
  64050. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  64051. }
  64052. return instance;
  64053. }
  64054. // line system creation
  64055. var useVertexColor = (colors) ? true : false;
  64056. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  64057. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  64058. vertexData.applyToMesh(lineSystem, options.updatable);
  64059. return lineSystem;
  64060. };
  64061. /**
  64062. * Creates a line mesh
  64063. * 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
  64064. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64065. * * The parameter `points` is an array successive Vector3
  64066. * * 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
  64067. * * The optional parameter `colors` is an array of successive Color4, one per line point
  64068. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  64069. * * When updating an instance, remember that only point positions can change, not the number of points
  64070. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64071. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  64072. * @param name defines the name of the new line system
  64073. * @param options defines the options used to create the line system
  64074. * @param scene defines the hosting scene
  64075. * @returns a new line mesh
  64076. */
  64077. MeshBuilder.CreateLines = function (name, options, scene) {
  64078. if (scene === void 0) { scene = null; }
  64079. var colors = (options.colors) ? [options.colors] : null;
  64080. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  64081. return lines;
  64082. };
  64083. /**
  64084. * Creates a dashed line mesh
  64085. * * 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
  64086. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64087. * * The parameter `points` is an array successive Vector3
  64088. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  64089. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  64090. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  64091. * * 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
  64092. * * When updating an instance, remember that only point positions can change, not the number of points
  64093. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64094. * @param name defines the name of the mesh
  64095. * @param options defines the options used to create the mesh
  64096. * @param scene defines the hosting scene
  64097. * @returns the dashed line mesh
  64098. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  64099. */
  64100. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  64101. if (scene === void 0) { scene = null; }
  64102. var points = options.points;
  64103. var instance = options.instance;
  64104. var gapSize = options.gapSize || 1;
  64105. var dashSize = options.dashSize || 3;
  64106. if (instance) { // dashed lines update
  64107. var positionFunction = function (positions) {
  64108. var curvect = BABYLON.Vector3.Zero();
  64109. var nbSeg = positions.length / 6;
  64110. var lg = 0;
  64111. var nb = 0;
  64112. var shft = 0;
  64113. var dashshft = 0;
  64114. var curshft = 0;
  64115. var p = 0;
  64116. var i = 0;
  64117. var j = 0;
  64118. for (i = 0; i < points.length - 1; i++) {
  64119. points[i + 1].subtractToRef(points[i], curvect);
  64120. lg += curvect.length();
  64121. }
  64122. shft = lg / nbSeg;
  64123. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  64124. for (i = 0; i < points.length - 1; i++) {
  64125. points[i + 1].subtractToRef(points[i], curvect);
  64126. nb = Math.floor(curvect.length() / shft);
  64127. curvect.normalize();
  64128. j = 0;
  64129. while (j < nb && p < positions.length) {
  64130. curshft = shft * j;
  64131. positions[p] = points[i].x + curshft * curvect.x;
  64132. positions[p + 1] = points[i].y + curshft * curvect.y;
  64133. positions[p + 2] = points[i].z + curshft * curvect.z;
  64134. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  64135. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  64136. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  64137. p += 6;
  64138. j++;
  64139. }
  64140. }
  64141. while (p < positions.length) {
  64142. positions[p] = points[i].x;
  64143. positions[p + 1] = points[i].y;
  64144. positions[p + 2] = points[i].z;
  64145. p += 3;
  64146. }
  64147. };
  64148. instance.updateMeshPositions(positionFunction, false);
  64149. return instance;
  64150. }
  64151. // dashed lines creation
  64152. var dashedLines = new BABYLON.LinesMesh(name, scene);
  64153. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  64154. vertexData.applyToMesh(dashedLines, options.updatable);
  64155. dashedLines.dashSize = dashSize;
  64156. dashedLines.gapSize = gapSize;
  64157. return dashedLines;
  64158. };
  64159. /**
  64160. * 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.
  64161. * * 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.
  64162. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64163. * * 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.
  64164. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  64165. * * 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
  64166. * * 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
  64167. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  64168. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64169. * * 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
  64170. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  64171. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64172. * @param name defines the name of the mesh
  64173. * @param options defines the options used to create the mesh
  64174. * @param scene defines the hosting scene
  64175. * @returns the extruded shape mesh
  64176. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64177. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64178. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64179. */
  64180. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  64181. if (scene === void 0) { scene = null; }
  64182. var path = options.path;
  64183. var shape = options.shape;
  64184. var scale = options.scale || 1;
  64185. var rotation = options.rotation || 0;
  64186. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64187. var updatable = options.updatable;
  64188. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64189. var instance = options.instance || null;
  64190. var invertUV = options.invertUV || false;
  64191. 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);
  64192. };
  64193. /**
  64194. * Creates an custom extruded shape mesh.
  64195. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  64196. * * 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.
  64197. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64198. * * 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
  64199. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  64200. * * 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
  64201. * * It must returns a float value that will be the scale value applied to the shape on each path point
  64202. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  64203. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  64204. * * 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
  64205. * * 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
  64206. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  64207. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64208. * * 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
  64209. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64210. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64211. * @param name defines the name of the mesh
  64212. * @param options defines the options used to create the mesh
  64213. * @param scene defines the hosting scene
  64214. * @returns the custom extruded shape mesh
  64215. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  64216. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64217. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64218. */
  64219. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  64220. var path = options.path;
  64221. var shape = options.shape;
  64222. var scaleFunction = options.scaleFunction || (function () { return 1; });
  64223. var rotationFunction = options.rotationFunction || (function () { return 0; });
  64224. var ribbonCloseArray = options.ribbonCloseArray || false;
  64225. var ribbonClosePath = options.ribbonClosePath || false;
  64226. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64227. var updatable = options.updatable;
  64228. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64229. var instance = options.instance;
  64230. var invertUV = options.invertUV || false;
  64231. 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);
  64232. };
  64233. /**
  64234. * Creates lathe mesh.
  64235. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  64236. * * 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
  64237. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  64238. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  64239. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  64240. * * 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
  64241. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  64242. * * 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
  64243. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64244. * * 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
  64245. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64246. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64247. * @param name defines the name of the mesh
  64248. * @param options defines the options used to create the mesh
  64249. * @param scene defines the hosting scene
  64250. * @returns the lathe mesh
  64251. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  64252. */
  64253. MeshBuilder.CreateLathe = function (name, options, scene) {
  64254. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  64255. var closed = (options.closed === undefined) ? true : options.closed;
  64256. var shape = options.shape;
  64257. var radius = options.radius || 1;
  64258. var tessellation = options.tessellation || 64;
  64259. var clip = options.clip || 0;
  64260. var updatable = options.updatable;
  64261. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64262. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64263. var pi2 = Math.PI * 2;
  64264. var paths = new Array();
  64265. var invertUV = options.invertUV || false;
  64266. var i = 0;
  64267. var p = 0;
  64268. var step = pi2 / tessellation * arc;
  64269. var rotated;
  64270. var path = new Array();
  64271. for (i = 0; i <= tessellation - clip; i++) {
  64272. var path = [];
  64273. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  64274. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  64275. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  64276. }
  64277. for (p = 0; p < shape.length; p++) {
  64278. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  64279. path.push(rotated);
  64280. }
  64281. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  64282. 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));
  64283. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  64284. }
  64285. paths.push(path);
  64286. }
  64287. // lathe ribbon
  64288. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64289. return lathe;
  64290. };
  64291. /**
  64292. * Creates a plane mesh
  64293. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  64294. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  64295. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  64296. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64297. * * 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
  64298. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64299. * @param name defines the name of the mesh
  64300. * @param options defines the options used to create the mesh
  64301. * @param scene defines the hosting scene
  64302. * @returns the plane mesh
  64303. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64304. */
  64305. MeshBuilder.CreatePlane = function (name, options, scene) {
  64306. var plane = new BABYLON.Mesh(name, scene);
  64307. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64308. plane._originalBuilderSideOrientation = options.sideOrientation;
  64309. var vertexData = BABYLON.VertexData.CreatePlane(options);
  64310. vertexData.applyToMesh(plane, options.updatable);
  64311. if (options.sourcePlane) {
  64312. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  64313. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  64314. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  64315. plane.rotate(vectorProduct, product);
  64316. }
  64317. return plane;
  64318. };
  64319. /**
  64320. * Creates a ground mesh
  64321. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  64322. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  64323. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64324. * @param name defines the name of the mesh
  64325. * @param options defines the options used to create the mesh
  64326. * @param scene defines the hosting scene
  64327. * @returns the ground mesh
  64328. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64329. */
  64330. MeshBuilder.CreateGround = function (name, options, scene) {
  64331. var ground = new BABYLON.GroundMesh(name, scene);
  64332. ground._setReady(false);
  64333. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  64334. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  64335. ground._width = options.width || 1;
  64336. ground._height = options.height || 1;
  64337. ground._maxX = ground._width / 2;
  64338. ground._maxZ = ground._height / 2;
  64339. ground._minX = -ground._maxX;
  64340. ground._minZ = -ground._maxZ;
  64341. var vertexData = BABYLON.VertexData.CreateGround(options);
  64342. vertexData.applyToMesh(ground, options.updatable);
  64343. ground._setReady(true);
  64344. return ground;
  64345. };
  64346. /**
  64347. * Creates a tiled ground mesh
  64348. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  64349. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  64350. * * 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
  64351. * * 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
  64352. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64353. * @param name defines the name of the mesh
  64354. * @param options defines the options used to create the mesh
  64355. * @param scene defines the hosting scene
  64356. * @returns the tiled ground mesh
  64357. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  64358. */
  64359. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  64360. var tiledGround = new BABYLON.Mesh(name, scene);
  64361. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  64362. vertexData.applyToMesh(tiledGround, options.updatable);
  64363. return tiledGround;
  64364. };
  64365. /**
  64366. * Creates a ground mesh from a height map
  64367. * * The parameter `url` sets the URL of the height map image resource.
  64368. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  64369. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  64370. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  64371. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  64372. * * 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.
  64373. * * 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).
  64374. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64375. * @param name defines the name of the mesh
  64376. * @param url defines the url to the height map
  64377. * @param options defines the options used to create the mesh
  64378. * @param scene defines the hosting scene
  64379. * @returns the ground mesh
  64380. * @see http://doc.babylonjs.com/babylon101/height_map
  64381. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  64382. */
  64383. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  64384. var width = options.width || 10.0;
  64385. var height = options.height || 10.0;
  64386. var subdivisions = options.subdivisions || 1 | 0;
  64387. var minHeight = options.minHeight || 0.0;
  64388. var maxHeight = options.maxHeight || 1.0;
  64389. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  64390. var updatable = options.updatable;
  64391. var onReady = options.onReady;
  64392. var ground = new BABYLON.GroundMesh(name, scene);
  64393. ground._subdivisionsX = subdivisions;
  64394. ground._subdivisionsY = subdivisions;
  64395. ground._width = width;
  64396. ground._height = height;
  64397. ground._maxX = ground._width / 2.0;
  64398. ground._maxZ = ground._height / 2.0;
  64399. ground._minX = -ground._maxX;
  64400. ground._minZ = -ground._maxZ;
  64401. ground._setReady(false);
  64402. var onload = function (img) {
  64403. // Getting height map data
  64404. var canvas = document.createElement("canvas");
  64405. var context = canvas.getContext("2d");
  64406. if (!context) {
  64407. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  64408. }
  64409. if (scene.isDisposed) {
  64410. return;
  64411. }
  64412. var bufferWidth = img.width;
  64413. var bufferHeight = img.height;
  64414. canvas.width = bufferWidth;
  64415. canvas.height = bufferHeight;
  64416. context.drawImage(img, 0, 0);
  64417. // Create VertexData from map data
  64418. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  64419. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  64420. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  64421. width: width, height: height,
  64422. subdivisions: subdivisions,
  64423. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  64424. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  64425. });
  64426. vertexData.applyToMesh(ground, updatable);
  64427. //execute ready callback, if set
  64428. if (onReady) {
  64429. onReady(ground);
  64430. }
  64431. ground._setReady(true);
  64432. };
  64433. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  64434. return ground;
  64435. };
  64436. /**
  64437. * Creates a polygon mesh
  64438. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  64439. * * 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
  64440. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64441. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64442. * * 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)
  64443. * * Remember you can only change the shape positions, not their number when updating a polygon
  64444. * @param name defines the name of the mesh
  64445. * @param options defines the options used to create the mesh
  64446. * @param scene defines the hosting scene
  64447. * @returns the polygon mesh
  64448. */
  64449. MeshBuilder.CreatePolygon = function (name, options, scene) {
  64450. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64451. var shape = options.shape;
  64452. var holes = options.holes || [];
  64453. var depth = options.depth || 0;
  64454. var contours = [];
  64455. var hole = [];
  64456. for (var i = 0; i < shape.length; i++) {
  64457. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  64458. }
  64459. var epsilon = 0.00000001;
  64460. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  64461. contours.pop();
  64462. }
  64463. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  64464. for (var hNb = 0; hNb < holes.length; hNb++) {
  64465. hole = [];
  64466. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  64467. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  64468. }
  64469. polygonTriangulation.addHole(hole);
  64470. }
  64471. var polygon = polygonTriangulation.build(options.updatable, depth);
  64472. polygon._originalBuilderSideOrientation = options.sideOrientation;
  64473. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  64474. vertexData.applyToMesh(polygon, options.updatable);
  64475. return polygon;
  64476. };
  64477. ;
  64478. /**
  64479. * Creates an extruded polygon mesh, with depth in the Y direction.
  64480. * * 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)
  64481. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64482. * @param name defines the name of the mesh
  64483. * @param options defines the options used to create the mesh
  64484. * @param scene defines the hosting scene
  64485. * @returns the polygon mesh
  64486. */
  64487. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  64488. return MeshBuilder.CreatePolygon(name, options, scene);
  64489. };
  64490. ;
  64491. /**
  64492. * Creates a tube mesh.
  64493. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64494. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  64495. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  64496. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  64497. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  64498. * * 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)
  64499. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  64500. * * 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
  64501. * * 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
  64502. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64503. * * 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
  64504. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64505. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64506. * @param name defines the name of the mesh
  64507. * @param options defines the options used to create the mesh
  64508. * @param scene defines the hosting scene
  64509. * @returns the tube mesh
  64510. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64511. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  64512. */
  64513. MeshBuilder.CreateTube = function (name, options, scene) {
  64514. var path = options.path;
  64515. var instance = options.instance;
  64516. var radius = 1.0;
  64517. if (instance) {
  64518. radius = instance.radius;
  64519. }
  64520. if (options.radius !== undefined) {
  64521. radius = options.radius;
  64522. }
  64523. ;
  64524. var tessellation = options.tessellation || 64 | 0;
  64525. var radiusFunction = options.radiusFunction || null;
  64526. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64527. var invertUV = options.invertUV || false;
  64528. var updatable = options.updatable;
  64529. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64530. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  64531. // tube geometry
  64532. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  64533. var tangents = path3D.getTangents();
  64534. var normals = path3D.getNormals();
  64535. var distances = path3D.getDistances();
  64536. var pi2 = Math.PI * 2;
  64537. var step = pi2 / tessellation * arc;
  64538. var returnRadius = function () { return radius; };
  64539. var radiusFunctionFinal = radiusFunction || returnRadius;
  64540. var circlePath;
  64541. var rad;
  64542. var normal;
  64543. var rotated;
  64544. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64545. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64546. for (var i = 0; i < path.length; i++) {
  64547. rad = radiusFunctionFinal(i, distances[i]); // current radius
  64548. circlePath = Array(); // current circle array
  64549. normal = normals[i]; // current normal
  64550. for (var t = 0; t < tessellation; t++) {
  64551. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  64552. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  64553. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  64554. rotated.scaleInPlace(rad).addInPlace(path[i]);
  64555. circlePath[t] = rotated;
  64556. }
  64557. circlePaths[index] = circlePath;
  64558. index++;
  64559. }
  64560. // cap
  64561. var capPath = function (nbPoints, pathIndex) {
  64562. var pointCap = Array();
  64563. for (var i = 0; i < nbPoints; i++) {
  64564. pointCap.push(path[pathIndex]);
  64565. }
  64566. return pointCap;
  64567. };
  64568. switch (cap) {
  64569. case BABYLON.Mesh.NO_CAP:
  64570. break;
  64571. case BABYLON.Mesh.CAP_START:
  64572. circlePaths[0] = capPath(tessellation, 0);
  64573. circlePaths[1] = circlePaths[2].slice(0);
  64574. break;
  64575. case BABYLON.Mesh.CAP_END:
  64576. circlePaths[index] = circlePaths[index - 1].slice(0);
  64577. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64578. break;
  64579. case BABYLON.Mesh.CAP_ALL:
  64580. circlePaths[0] = capPath(tessellation, 0);
  64581. circlePaths[1] = circlePaths[2].slice(0);
  64582. circlePaths[index] = circlePaths[index - 1].slice(0);
  64583. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64584. break;
  64585. default:
  64586. break;
  64587. }
  64588. return circlePaths;
  64589. };
  64590. var path3D;
  64591. var pathArray;
  64592. if (instance) { // tube update
  64593. var arc = options.arc || instance.arc;
  64594. path3D = (instance.path3D).update(path);
  64595. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  64596. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  64597. instance.path3D = path3D;
  64598. instance.pathArray = pathArray;
  64599. instance.arc = arc;
  64600. instance.radius = radius;
  64601. return instance;
  64602. }
  64603. // tube creation
  64604. path3D = new BABYLON.Path3D(path);
  64605. var newPathArray = new Array();
  64606. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64607. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  64608. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64609. tube.pathArray = pathArray;
  64610. tube.path3D = path3D;
  64611. tube.tessellation = tessellation;
  64612. tube.cap = cap;
  64613. tube.arc = options.arc;
  64614. tube.radius = radius;
  64615. return tube;
  64616. };
  64617. /**
  64618. * Creates a polyhedron mesh
  64619. * * 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
  64620. * * The parameter `size` (positive float, default 1) sets the polygon size
  64621. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  64622. * * 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`
  64623. * * 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
  64624. * * 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)`)
  64625. * * 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
  64626. * * 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
  64627. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64628. * * 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
  64629. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64630. * @param name defines the name of the mesh
  64631. * @param options defines the options used to create the mesh
  64632. * @param scene defines the hosting scene
  64633. * @returns the polyhedron mesh
  64634. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  64635. */
  64636. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  64637. var polyhedron = new BABYLON.Mesh(name, scene);
  64638. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64639. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  64640. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  64641. vertexData.applyToMesh(polyhedron, options.updatable);
  64642. return polyhedron;
  64643. };
  64644. /**
  64645. * Creates a decal mesh.
  64646. * 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
  64647. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  64648. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  64649. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  64650. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  64651. * @param name defines the name of the mesh
  64652. * @param sourceMesh defines the mesh where the decal must be applied
  64653. * @param options defines the options used to create the mesh
  64654. * @param scene defines the hosting scene
  64655. * @returns the decal mesh
  64656. * @see http://doc.babylonjs.com/how_to/decals
  64657. */
  64658. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  64659. var indices = sourceMesh.getIndices();
  64660. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64661. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64662. var position = options.position || BABYLON.Vector3.Zero();
  64663. var normal = options.normal || BABYLON.Vector3.Up();
  64664. var size = options.size || BABYLON.Vector3.One();
  64665. var angle = options.angle || 0;
  64666. // Getting correct rotation
  64667. if (!normal) {
  64668. var target = new BABYLON.Vector3(0, 0, 1);
  64669. var camera = sourceMesh.getScene().activeCamera;
  64670. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  64671. normal = camera.globalPosition.subtract(cameraWorldTarget);
  64672. }
  64673. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  64674. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  64675. var pitch = Math.atan2(normal.y, len);
  64676. // Matrix
  64677. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  64678. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  64679. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  64680. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  64681. var vertexData = new BABYLON.VertexData();
  64682. vertexData.indices = [];
  64683. vertexData.positions = [];
  64684. vertexData.normals = [];
  64685. vertexData.uvs = [];
  64686. var currentVertexDataIndex = 0;
  64687. var extractDecalVector3 = function (indexId) {
  64688. var result = new BABYLON.PositionNormalVertex();
  64689. if (!indices || !positions || !normals) {
  64690. return result;
  64691. }
  64692. var vertexId = indices[indexId];
  64693. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  64694. // Send vector to decal local world
  64695. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  64696. // Get normal
  64697. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  64698. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  64699. return result;
  64700. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  64701. var clip = function (vertices, axis) {
  64702. if (vertices.length === 0) {
  64703. return vertices;
  64704. }
  64705. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  64706. var clipVertices = function (v0, v1) {
  64707. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  64708. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  64709. };
  64710. var result = new Array();
  64711. for (var index = 0; index < vertices.length; index += 3) {
  64712. var v1Out;
  64713. var v2Out;
  64714. var v3Out;
  64715. var total = 0;
  64716. var nV1 = null;
  64717. var nV2 = null;
  64718. var nV3 = null;
  64719. var nV4 = null;
  64720. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  64721. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  64722. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  64723. v1Out = d1 > 0;
  64724. v2Out = d2 > 0;
  64725. v3Out = d3 > 0;
  64726. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  64727. switch (total) {
  64728. case 0:
  64729. result.push(vertices[index]);
  64730. result.push(vertices[index + 1]);
  64731. result.push(vertices[index + 2]);
  64732. break;
  64733. case 1:
  64734. if (v1Out) {
  64735. nV1 = vertices[index + 1];
  64736. nV2 = vertices[index + 2];
  64737. nV3 = clipVertices(vertices[index], nV1);
  64738. nV4 = clipVertices(vertices[index], nV2);
  64739. }
  64740. if (v2Out) {
  64741. nV1 = vertices[index];
  64742. nV2 = vertices[index + 2];
  64743. nV3 = clipVertices(vertices[index + 1], nV1);
  64744. nV4 = clipVertices(vertices[index + 1], nV2);
  64745. result.push(nV3);
  64746. result.push(nV2.clone());
  64747. result.push(nV1.clone());
  64748. result.push(nV2.clone());
  64749. result.push(nV3.clone());
  64750. result.push(nV4);
  64751. break;
  64752. }
  64753. if (v3Out) {
  64754. nV1 = vertices[index];
  64755. nV2 = vertices[index + 1];
  64756. nV3 = clipVertices(vertices[index + 2], nV1);
  64757. nV4 = clipVertices(vertices[index + 2], nV2);
  64758. }
  64759. if (nV1 && nV2 && nV3 && nV4) {
  64760. result.push(nV1.clone());
  64761. result.push(nV2.clone());
  64762. result.push(nV3);
  64763. result.push(nV4);
  64764. result.push(nV3.clone());
  64765. result.push(nV2.clone());
  64766. }
  64767. break;
  64768. case 2:
  64769. if (!v1Out) {
  64770. nV1 = vertices[index].clone();
  64771. nV2 = clipVertices(nV1, vertices[index + 1]);
  64772. nV3 = clipVertices(nV1, vertices[index + 2]);
  64773. result.push(nV1);
  64774. result.push(nV2);
  64775. result.push(nV3);
  64776. }
  64777. if (!v2Out) {
  64778. nV1 = vertices[index + 1].clone();
  64779. nV2 = clipVertices(nV1, vertices[index + 2]);
  64780. nV3 = clipVertices(nV1, vertices[index]);
  64781. result.push(nV1);
  64782. result.push(nV2);
  64783. result.push(nV3);
  64784. }
  64785. if (!v3Out) {
  64786. nV1 = vertices[index + 2].clone();
  64787. nV2 = clipVertices(nV1, vertices[index]);
  64788. nV3 = clipVertices(nV1, vertices[index + 1]);
  64789. result.push(nV1);
  64790. result.push(nV2);
  64791. result.push(nV3);
  64792. }
  64793. break;
  64794. case 3:
  64795. break;
  64796. }
  64797. }
  64798. return result;
  64799. };
  64800. for (var index = 0; index < indices.length; index += 3) {
  64801. var faceVertices = new Array();
  64802. faceVertices.push(extractDecalVector3(index));
  64803. faceVertices.push(extractDecalVector3(index + 1));
  64804. faceVertices.push(extractDecalVector3(index + 2));
  64805. // Clip
  64806. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  64807. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  64808. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  64809. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  64810. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  64811. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  64812. if (faceVertices.length === 0) {
  64813. continue;
  64814. }
  64815. // Add UVs and get back to world
  64816. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  64817. var vertex = faceVertices[vIndex];
  64818. //TODO check for Int32Array | Uint32Array | Uint16Array
  64819. vertexData.indices.push(currentVertexDataIndex);
  64820. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  64821. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  64822. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  64823. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  64824. currentVertexDataIndex++;
  64825. }
  64826. }
  64827. // Return mesh
  64828. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  64829. vertexData.applyToMesh(decal);
  64830. decal.position = position.clone();
  64831. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  64832. return decal;
  64833. };
  64834. // Privates
  64835. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  64836. // extrusion geometry
  64837. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  64838. var tangents = path3D.getTangents();
  64839. var normals = path3D.getNormals();
  64840. var binormals = path3D.getBinormals();
  64841. var distances = path3D.getDistances();
  64842. var angle = 0;
  64843. var returnScale = function () { return scale !== null ? scale : 1; };
  64844. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  64845. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  64846. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  64847. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64848. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64849. for (var i = 0; i < curve.length; i++) {
  64850. var shapePath = new Array();
  64851. var angleStep = rotate(i, distances[i]);
  64852. var scaleRatio = scl(i, distances[i]);
  64853. for (var p = 0; p < shape.length; p++) {
  64854. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  64855. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  64856. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  64857. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  64858. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  64859. shapePath[p] = rotated;
  64860. }
  64861. shapePaths[index] = shapePath;
  64862. angle += angleStep;
  64863. index++;
  64864. }
  64865. // cap
  64866. var capPath = function (shapePath) {
  64867. var pointCap = Array();
  64868. var barycenter = BABYLON.Vector3.Zero();
  64869. var i;
  64870. for (i = 0; i < shapePath.length; i++) {
  64871. barycenter.addInPlace(shapePath[i]);
  64872. }
  64873. barycenter.scaleInPlace(1.0 / shapePath.length);
  64874. for (i = 0; i < shapePath.length; i++) {
  64875. pointCap.push(barycenter);
  64876. }
  64877. return pointCap;
  64878. };
  64879. switch (cap) {
  64880. case BABYLON.Mesh.NO_CAP:
  64881. break;
  64882. case BABYLON.Mesh.CAP_START:
  64883. shapePaths[0] = capPath(shapePaths[2]);
  64884. shapePaths[1] = shapePaths[2];
  64885. break;
  64886. case BABYLON.Mesh.CAP_END:
  64887. shapePaths[index] = shapePaths[index - 1];
  64888. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64889. break;
  64890. case BABYLON.Mesh.CAP_ALL:
  64891. shapePaths[0] = capPath(shapePaths[2]);
  64892. shapePaths[1] = shapePaths[2];
  64893. shapePaths[index] = shapePaths[index - 1];
  64894. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64895. break;
  64896. default:
  64897. break;
  64898. }
  64899. return shapePaths;
  64900. };
  64901. var path3D;
  64902. var pathArray;
  64903. if (instance) { // instance update
  64904. path3D = (instance.path3D).update(curve);
  64905. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  64906. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  64907. return instance;
  64908. }
  64909. // extruded shape creation
  64910. path3D = new BABYLON.Path3D(curve);
  64911. var newShapePaths = new Array();
  64912. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64913. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  64914. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  64915. extrudedGeneric.pathArray = pathArray;
  64916. extrudedGeneric.path3D = path3D;
  64917. extrudedGeneric.cap = cap;
  64918. return extrudedGeneric;
  64919. };
  64920. return MeshBuilder;
  64921. }());
  64922. BABYLON.MeshBuilder = MeshBuilder;
  64923. })(BABYLON || (BABYLON = {}));
  64924. //# sourceMappingURL=babylon.meshBuilder.js.map
  64925. var BABYLON;
  64926. (function (BABYLON) {
  64927. /**
  64928. * Draco compression (https://google.github.io/draco/)
  64929. *
  64930. * This class wraps the Draco module.
  64931. *
  64932. * **Encoder**
  64933. *
  64934. * The encoder is not currently implemented.
  64935. *
  64936. * **Decoder**
  64937. *
  64938. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  64939. *
  64940. * To update the configuration, use the following code:
  64941. * ```javascript
  64942. * BABYLON.DracoCompression.Configuration = {
  64943. * decoder: {
  64944. * wasmUrl: "<url to the WebAssembly library>",
  64945. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  64946. * fallbackUrl: "<url to the fallback JavaScript library>",
  64947. * }
  64948. * };
  64949. * ```
  64950. *
  64951. * 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.
  64952. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  64953. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  64954. *
  64955. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  64956. * ```javascript
  64957. * var dracoCompression = new BABYLON.DracoCompression();
  64958. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  64959. * [BABYLON.VertexBuffer.PositionKind]: 0
  64960. * });
  64961. * ```
  64962. *
  64963. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  64964. */
  64965. var DracoCompression = /** @class */ (function () {
  64966. /**
  64967. * Constructor
  64968. */
  64969. function DracoCompression() {
  64970. }
  64971. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  64972. /**
  64973. * Returns true if the decoder is available.
  64974. */
  64975. get: function () {
  64976. if (typeof DracoDecoderModule !== "undefined") {
  64977. return true;
  64978. }
  64979. var decoder = DracoCompression.Configuration.decoder;
  64980. if (decoder) {
  64981. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64982. return true;
  64983. }
  64984. if (decoder.fallbackUrl) {
  64985. return true;
  64986. }
  64987. }
  64988. return false;
  64989. },
  64990. enumerable: true,
  64991. configurable: true
  64992. });
  64993. /**
  64994. * Stop all async operations and release resources.
  64995. */
  64996. DracoCompression.prototype.dispose = function () {
  64997. };
  64998. /**
  64999. * Decode Draco compressed mesh data to vertex data.
  65000. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  65001. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  65002. * @returns A promise that resolves with the decoded vertex data
  65003. */
  65004. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  65005. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  65006. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  65007. var module = wrappedModule.module;
  65008. var vertexData = new BABYLON.VertexData();
  65009. var buffer = new module.DecoderBuffer();
  65010. buffer.Init(dataView, dataView.byteLength);
  65011. var decoder = new module.Decoder();
  65012. var geometry;
  65013. var status;
  65014. try {
  65015. var type = decoder.GetEncodedGeometryType(buffer);
  65016. switch (type) {
  65017. case module.TRIANGULAR_MESH:
  65018. geometry = new module.Mesh();
  65019. status = decoder.DecodeBufferToMesh(buffer, geometry);
  65020. break;
  65021. case module.POINT_CLOUD:
  65022. geometry = new module.PointCloud();
  65023. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  65024. break;
  65025. default:
  65026. throw new Error("Invalid geometry type " + type);
  65027. }
  65028. if (!status.ok() || !geometry.ptr) {
  65029. throw new Error(status.error_msg());
  65030. }
  65031. var numPoints = geometry.num_points();
  65032. if (type === module.TRIANGULAR_MESH) {
  65033. var numFaces = geometry.num_faces();
  65034. var faceIndices = new module.DracoInt32Array();
  65035. try {
  65036. var indices = new Uint32Array(numFaces * 3);
  65037. for (var i = 0; i < numFaces; i++) {
  65038. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  65039. var offset = i * 3;
  65040. indices[offset + 0] = faceIndices.GetValue(0);
  65041. indices[offset + 1] = faceIndices.GetValue(1);
  65042. indices[offset + 2] = faceIndices.GetValue(2);
  65043. }
  65044. vertexData.indices = indices;
  65045. }
  65046. finally {
  65047. module.destroy(faceIndices);
  65048. }
  65049. }
  65050. for (var kind in attributes) {
  65051. var uniqueId = attributes[kind];
  65052. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  65053. var dracoData = new module.DracoFloat32Array();
  65054. try {
  65055. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  65056. var babylonData = new Float32Array(numPoints * attribute.num_components());
  65057. for (var i = 0; i < babylonData.length; i++) {
  65058. babylonData[i] = dracoData.GetValue(i);
  65059. }
  65060. vertexData.set(babylonData, kind);
  65061. }
  65062. finally {
  65063. module.destroy(dracoData);
  65064. }
  65065. }
  65066. }
  65067. finally {
  65068. if (geometry) {
  65069. module.destroy(geometry);
  65070. }
  65071. module.destroy(decoder);
  65072. module.destroy(buffer);
  65073. }
  65074. return vertexData;
  65075. });
  65076. };
  65077. DracoCompression._GetDecoderModule = function () {
  65078. if (!DracoCompression._DecoderModulePromise) {
  65079. var promise = null;
  65080. var config_1 = {};
  65081. if (typeof DracoDecoderModule !== "undefined") {
  65082. promise = Promise.resolve();
  65083. }
  65084. else {
  65085. var decoder = DracoCompression.Configuration.decoder;
  65086. if (decoder) {
  65087. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65088. promise = Promise.all([
  65089. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  65090. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  65091. config_1.wasmBinary = data;
  65092. })
  65093. ]);
  65094. }
  65095. else if (decoder.fallbackUrl) {
  65096. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  65097. }
  65098. }
  65099. }
  65100. if (!promise) {
  65101. throw new Error("Draco decoder module is not available");
  65102. }
  65103. DracoCompression._DecoderModulePromise = promise.then(function () {
  65104. return new Promise(function (resolve) {
  65105. config_1.onModuleLoaded = function (decoderModule) {
  65106. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  65107. resolve({ module: decoderModule });
  65108. };
  65109. DracoDecoderModule(config_1);
  65110. });
  65111. });
  65112. }
  65113. return DracoCompression._DecoderModulePromise;
  65114. };
  65115. DracoCompression._LoadScriptAsync = function (url) {
  65116. return new Promise(function (resolve, reject) {
  65117. BABYLON.Tools.LoadScript(url, function () {
  65118. resolve();
  65119. }, function (message) {
  65120. reject(new Error(message));
  65121. });
  65122. });
  65123. };
  65124. DracoCompression._LoadFileAsync = function (url) {
  65125. return new Promise(function (resolve, reject) {
  65126. BABYLON.Tools.LoadFile(url, function (data) {
  65127. resolve(data);
  65128. }, undefined, undefined, true, function (request, exception) {
  65129. reject(exception);
  65130. });
  65131. });
  65132. };
  65133. /**
  65134. * The configuration. Defaults to the following urls:
  65135. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  65136. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  65137. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65138. */
  65139. DracoCompression.Configuration = {
  65140. decoder: {
  65141. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  65142. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  65143. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65144. }
  65145. };
  65146. return DracoCompression;
  65147. }());
  65148. BABYLON.DracoCompression = DracoCompression;
  65149. })(BABYLON || (BABYLON = {}));
  65150. //# sourceMappingURL=babylon.dracoCompression.js.map
  65151. var BABYLON;
  65152. (function (BABYLON) {
  65153. var AudioEngine = /** @class */ (function () {
  65154. function AudioEngine() {
  65155. this._audioContext = null;
  65156. this._audioContextInitialized = false;
  65157. this.canUseWebAudio = false;
  65158. this.WarnedWebAudioUnsupported = false;
  65159. this.unlocked = false;
  65160. this.isMP3supported = false;
  65161. this.isOGGsupported = false;
  65162. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  65163. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  65164. this.canUseWebAudio = true;
  65165. }
  65166. var audioElem = document.createElement('audio');
  65167. try {
  65168. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  65169. this.isMP3supported = true;
  65170. }
  65171. }
  65172. catch (e) {
  65173. // protect error during capability check.
  65174. }
  65175. try {
  65176. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  65177. this.isOGGsupported = true;
  65178. }
  65179. }
  65180. catch (e) {
  65181. // protect error during capability check.
  65182. }
  65183. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  65184. this._unlockiOSaudio();
  65185. }
  65186. else {
  65187. this.unlocked = true;
  65188. }
  65189. }
  65190. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  65191. get: function () {
  65192. if (!this._audioContextInitialized) {
  65193. this._initializeAudioContext();
  65194. }
  65195. return this._audioContext;
  65196. },
  65197. enumerable: true,
  65198. configurable: true
  65199. });
  65200. AudioEngine.prototype._unlockiOSaudio = function () {
  65201. var _this = this;
  65202. var unlockaudio = function () {
  65203. if (!_this.audioContext) {
  65204. return;
  65205. }
  65206. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  65207. var source = _this.audioContext.createBufferSource();
  65208. source.buffer = buffer;
  65209. source.connect(_this.audioContext.destination);
  65210. source.start(0);
  65211. setTimeout(function () {
  65212. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  65213. _this.unlocked = true;
  65214. window.removeEventListener('touchend', unlockaudio, false);
  65215. if (_this.onAudioUnlocked) {
  65216. _this.onAudioUnlocked();
  65217. }
  65218. }
  65219. }, 0);
  65220. };
  65221. window.addEventListener('touchend', unlockaudio, false);
  65222. };
  65223. AudioEngine.prototype._initializeAudioContext = function () {
  65224. try {
  65225. if (this.canUseWebAudio) {
  65226. this._audioContext = new AudioContext();
  65227. // create a global volume gain node
  65228. this.masterGain = this._audioContext.createGain();
  65229. this.masterGain.gain.value = 1;
  65230. this.masterGain.connect(this._audioContext.destination);
  65231. this._audioContextInitialized = true;
  65232. }
  65233. }
  65234. catch (e) {
  65235. this.canUseWebAudio = false;
  65236. BABYLON.Tools.Error("Web Audio: " + e.message);
  65237. }
  65238. };
  65239. AudioEngine.prototype.dispose = function () {
  65240. if (this.canUseWebAudio && this._audioContextInitialized) {
  65241. if (this._connectedAnalyser && this._audioContext) {
  65242. this._connectedAnalyser.stopDebugCanvas();
  65243. this._connectedAnalyser.dispose();
  65244. this.masterGain.disconnect();
  65245. this.masterGain.connect(this._audioContext.destination);
  65246. this._connectedAnalyser = null;
  65247. }
  65248. this.masterGain.gain.value = 1;
  65249. }
  65250. this.WarnedWebAudioUnsupported = false;
  65251. };
  65252. AudioEngine.prototype.getGlobalVolume = function () {
  65253. if (this.canUseWebAudio && this._audioContextInitialized) {
  65254. return this.masterGain.gain.value;
  65255. }
  65256. else {
  65257. return -1;
  65258. }
  65259. };
  65260. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  65261. if (this.canUseWebAudio && this._audioContextInitialized) {
  65262. this.masterGain.gain.value = newVolume;
  65263. }
  65264. };
  65265. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  65266. if (this._connectedAnalyser) {
  65267. this._connectedAnalyser.stopDebugCanvas();
  65268. }
  65269. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  65270. this._connectedAnalyser = analyser;
  65271. this.masterGain.disconnect();
  65272. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  65273. }
  65274. };
  65275. return AudioEngine;
  65276. }());
  65277. BABYLON.AudioEngine = AudioEngine;
  65278. })(BABYLON || (BABYLON = {}));
  65279. //# sourceMappingURL=babylon.audioEngine.js.map
  65280. var BABYLON;
  65281. (function (BABYLON) {
  65282. var Sound = /** @class */ (function () {
  65283. /**
  65284. * Create a sound and attach it to a scene
  65285. * @param name Name of your sound
  65286. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  65287. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  65288. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  65289. */
  65290. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  65291. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  65292. var _this = this;
  65293. this.autoplay = false;
  65294. this.loop = false;
  65295. this.useCustomAttenuation = false;
  65296. this.spatialSound = false;
  65297. this.refDistance = 1;
  65298. this.rolloffFactor = 1;
  65299. this.maxDistance = 100;
  65300. this.distanceModel = "linear";
  65301. this._panningModel = "equalpower";
  65302. /**
  65303. * Observable event when the current playing sound finishes.
  65304. */
  65305. this.onEndedObservable = new BABYLON.Observable();
  65306. this._playbackRate = 1;
  65307. this._streaming = false;
  65308. this._startTime = 0;
  65309. this._startOffset = 0;
  65310. this._position = BABYLON.Vector3.Zero();
  65311. /** @hidden */
  65312. this._positionInEmitterSpace = false;
  65313. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  65314. this._volume = 1;
  65315. this._isReadyToPlay = false;
  65316. this.isPlaying = false;
  65317. this.isPaused = false;
  65318. this._isDirectional = false;
  65319. // Used if you'd like to create a directional sound.
  65320. // If not set, the sound will be omnidirectional
  65321. this._coneInnerAngle = 360;
  65322. this._coneOuterAngle = 360;
  65323. this._coneOuterGain = 0;
  65324. this._isOutputConnected = false;
  65325. this._urlType = "Unknown";
  65326. this.name = name;
  65327. this._scene = scene;
  65328. this._readyToPlayCallback = readyToPlayCallback;
  65329. // Default custom attenuation function is a linear attenuation
  65330. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  65331. if (currentDistance < maxDistance) {
  65332. return currentVolume * (1 - currentDistance / maxDistance);
  65333. }
  65334. else {
  65335. return 0;
  65336. }
  65337. };
  65338. if (options) {
  65339. this.autoplay = options.autoplay || false;
  65340. this.loop = options.loop || false;
  65341. // if volume === 0, we need another way to check this option
  65342. if (options.volume !== undefined) {
  65343. this._volume = options.volume;
  65344. }
  65345. this.spatialSound = options.spatialSound || false;
  65346. this.maxDistance = options.maxDistance || 100;
  65347. this.useCustomAttenuation = options.useCustomAttenuation || false;
  65348. this.rolloffFactor = options.rolloffFactor || 1;
  65349. this.refDistance = options.refDistance || 1;
  65350. this.distanceModel = options.distanceModel || "linear";
  65351. this._playbackRate = options.playbackRate || 1;
  65352. this._streaming = options.streaming || false;
  65353. }
  65354. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65355. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  65356. this._soundGain.gain.value = this._volume;
  65357. this._inputAudioNode = this._soundGain;
  65358. this._outputAudioNode = this._soundGain;
  65359. if (this.spatialSound) {
  65360. this._createSpatialParameters();
  65361. }
  65362. this._scene.mainSoundTrack.AddSound(this);
  65363. var validParameter = true;
  65364. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  65365. if (urlOrArrayBuffer) {
  65366. try {
  65367. if (typeof (urlOrArrayBuffer) === "string") {
  65368. this._urlType = "String";
  65369. }
  65370. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  65371. this._urlType = "ArrayBuffer";
  65372. }
  65373. else if (urlOrArrayBuffer instanceof MediaStream) {
  65374. this._urlType = "MediaStream";
  65375. }
  65376. else if (Array.isArray(urlOrArrayBuffer)) {
  65377. this._urlType = "Array";
  65378. }
  65379. var urls = [];
  65380. var codecSupportedFound = false;
  65381. switch (this._urlType) {
  65382. case "MediaStream":
  65383. this._streaming = true;
  65384. this._isReadyToPlay = true;
  65385. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  65386. if (this.autoplay) {
  65387. this.play();
  65388. }
  65389. if (this._readyToPlayCallback) {
  65390. this._readyToPlayCallback();
  65391. }
  65392. break;
  65393. case "ArrayBuffer":
  65394. if (urlOrArrayBuffer.byteLength > 0) {
  65395. codecSupportedFound = true;
  65396. this._soundLoaded(urlOrArrayBuffer);
  65397. }
  65398. break;
  65399. case "String":
  65400. urls.push(urlOrArrayBuffer);
  65401. case "Array":
  65402. if (urls.length === 0)
  65403. urls = urlOrArrayBuffer;
  65404. // If we found a supported format, we load it immediately and stop the loop
  65405. for (var i = 0; i < urls.length; i++) {
  65406. var url = urls[i];
  65407. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  65408. codecSupportedFound = true;
  65409. }
  65410. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  65411. codecSupportedFound = true;
  65412. }
  65413. if (url.indexOf(".wav", url.length - 4) !== -1) {
  65414. codecSupportedFound = true;
  65415. }
  65416. if (url.indexOf("blob:") !== -1) {
  65417. codecSupportedFound = true;
  65418. }
  65419. if (codecSupportedFound) {
  65420. // Loading sound using XHR2
  65421. if (!this._streaming) {
  65422. this._scene._loadFile(url, function (data) {
  65423. _this._soundLoaded(data);
  65424. }, undefined, true, true, function (exception) {
  65425. if (exception) {
  65426. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  65427. }
  65428. BABYLON.Tools.Error("Sound creation aborted.");
  65429. _this._scene.mainSoundTrack.RemoveSound(_this);
  65430. });
  65431. }
  65432. // Streaming sound using HTML5 Audio tag
  65433. else {
  65434. this._htmlAudioElement = new Audio(url);
  65435. this._htmlAudioElement.controls = false;
  65436. this._htmlAudioElement.loop = this.loop;
  65437. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  65438. this._htmlAudioElement.preload = "auto";
  65439. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  65440. _this._isReadyToPlay = true;
  65441. if (_this.autoplay) {
  65442. _this.play();
  65443. }
  65444. if (_this._readyToPlayCallback) {
  65445. _this._readyToPlayCallback();
  65446. }
  65447. });
  65448. document.body.appendChild(this._htmlAudioElement);
  65449. }
  65450. break;
  65451. }
  65452. }
  65453. break;
  65454. default:
  65455. validParameter = false;
  65456. break;
  65457. }
  65458. if (!validParameter) {
  65459. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  65460. }
  65461. else {
  65462. if (!codecSupportedFound) {
  65463. this._isReadyToPlay = true;
  65464. // Simulating a ready to play event to avoid breaking code path
  65465. if (this._readyToPlayCallback) {
  65466. window.setTimeout(function () {
  65467. if (_this._readyToPlayCallback) {
  65468. _this._readyToPlayCallback();
  65469. }
  65470. }, 1000);
  65471. }
  65472. }
  65473. }
  65474. }
  65475. catch (ex) {
  65476. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  65477. this._scene.mainSoundTrack.RemoveSound(this);
  65478. }
  65479. }
  65480. }
  65481. else {
  65482. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  65483. this._scene.mainSoundTrack.AddSound(this);
  65484. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  65485. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  65486. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  65487. }
  65488. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  65489. if (this._readyToPlayCallback) {
  65490. window.setTimeout(function () {
  65491. if (_this._readyToPlayCallback) {
  65492. _this._readyToPlayCallback();
  65493. }
  65494. }, 1000);
  65495. }
  65496. }
  65497. }
  65498. Sound.prototype.dispose = function () {
  65499. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65500. if (this.isPlaying) {
  65501. this.stop();
  65502. }
  65503. this._isReadyToPlay = false;
  65504. if (this.soundTrackId === -1) {
  65505. this._scene.mainSoundTrack.RemoveSound(this);
  65506. }
  65507. else {
  65508. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  65509. }
  65510. if (this._soundGain) {
  65511. this._soundGain.disconnect();
  65512. this._soundGain = null;
  65513. }
  65514. if (this._soundPanner) {
  65515. this._soundPanner.disconnect();
  65516. this._soundPanner = null;
  65517. }
  65518. if (this._soundSource) {
  65519. this._soundSource.disconnect();
  65520. this._soundSource = null;
  65521. }
  65522. this._audioBuffer = null;
  65523. if (this._htmlAudioElement) {
  65524. this._htmlAudioElement.pause();
  65525. this._htmlAudioElement.src = "";
  65526. document.body.removeChild(this._htmlAudioElement);
  65527. }
  65528. if (this._streamingSource) {
  65529. this._streamingSource.disconnect();
  65530. }
  65531. if (this._connectedMesh && this._registerFunc) {
  65532. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65533. this._connectedMesh = null;
  65534. }
  65535. }
  65536. };
  65537. Sound.prototype.isReady = function () {
  65538. return this._isReadyToPlay;
  65539. };
  65540. Sound.prototype._soundLoaded = function (audioData) {
  65541. var _this = this;
  65542. if (!BABYLON.Engine.audioEngine.audioContext) {
  65543. return;
  65544. }
  65545. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  65546. _this._audioBuffer = buffer;
  65547. _this._isReadyToPlay = true;
  65548. if (_this.autoplay) {
  65549. _this.play();
  65550. }
  65551. if (_this._readyToPlayCallback) {
  65552. _this._readyToPlayCallback();
  65553. }
  65554. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  65555. };
  65556. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  65557. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65558. this._audioBuffer = audioBuffer;
  65559. this._isReadyToPlay = true;
  65560. }
  65561. };
  65562. Sound.prototype.updateOptions = function (options) {
  65563. if (options) {
  65564. this.loop = options.loop || this.loop;
  65565. this.maxDistance = options.maxDistance || this.maxDistance;
  65566. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  65567. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  65568. this.refDistance = options.refDistance || this.refDistance;
  65569. this.distanceModel = options.distanceModel || this.distanceModel;
  65570. this._playbackRate = options.playbackRate || this._playbackRate;
  65571. this._updateSpatialParameters();
  65572. if (this.isPlaying) {
  65573. if (this._streaming && this._htmlAudioElement) {
  65574. this._htmlAudioElement.playbackRate = this._playbackRate;
  65575. }
  65576. else {
  65577. if (this._soundSource) {
  65578. this._soundSource.playbackRate.value = this._playbackRate;
  65579. }
  65580. }
  65581. }
  65582. }
  65583. };
  65584. Sound.prototype._createSpatialParameters = function () {
  65585. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65586. if (this._scene.headphone) {
  65587. this._panningModel = "HRTF";
  65588. }
  65589. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  65590. this._updateSpatialParameters();
  65591. this._soundPanner.connect(this._outputAudioNode);
  65592. this._inputAudioNode = this._soundPanner;
  65593. }
  65594. };
  65595. Sound.prototype._updateSpatialParameters = function () {
  65596. if (this.spatialSound && this._soundPanner) {
  65597. if (this.useCustomAttenuation) {
  65598. // Tricks to disable in a way embedded Web Audio attenuation
  65599. this._soundPanner.distanceModel = "linear";
  65600. this._soundPanner.maxDistance = Number.MAX_VALUE;
  65601. this._soundPanner.refDistance = 1;
  65602. this._soundPanner.rolloffFactor = 1;
  65603. this._soundPanner.panningModel = this._panningModel;
  65604. }
  65605. else {
  65606. this._soundPanner.distanceModel = this.distanceModel;
  65607. this._soundPanner.maxDistance = this.maxDistance;
  65608. this._soundPanner.refDistance = this.refDistance;
  65609. this._soundPanner.rolloffFactor = this.rolloffFactor;
  65610. this._soundPanner.panningModel = this._panningModel;
  65611. }
  65612. }
  65613. };
  65614. Sound.prototype.switchPanningModelToHRTF = function () {
  65615. this._panningModel = "HRTF";
  65616. this._switchPanningModel();
  65617. };
  65618. Sound.prototype.switchPanningModelToEqualPower = function () {
  65619. this._panningModel = "equalpower";
  65620. this._switchPanningModel();
  65621. };
  65622. Sound.prototype._switchPanningModel = function () {
  65623. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65624. this._soundPanner.panningModel = this._panningModel;
  65625. }
  65626. };
  65627. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  65628. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65629. if (this._isOutputConnected) {
  65630. this._outputAudioNode.disconnect();
  65631. }
  65632. this._outputAudioNode.connect(soundTrackAudioNode);
  65633. this._isOutputConnected = true;
  65634. }
  65635. };
  65636. /**
  65637. * Transform this sound into a directional source
  65638. * @param coneInnerAngle Size of the inner cone in degree
  65639. * @param coneOuterAngle Size of the outer cone in degree
  65640. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  65641. */
  65642. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  65643. if (coneOuterAngle < coneInnerAngle) {
  65644. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  65645. return;
  65646. }
  65647. this._coneInnerAngle = coneInnerAngle;
  65648. this._coneOuterAngle = coneOuterAngle;
  65649. this._coneOuterGain = coneOuterGain;
  65650. this._isDirectional = true;
  65651. if (this.isPlaying && this.loop) {
  65652. this.stop();
  65653. this.play();
  65654. }
  65655. };
  65656. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  65657. /**
  65658. * Gets or sets the inner angle for the directional cone.
  65659. */
  65660. get: function () {
  65661. return this._coneInnerAngle;
  65662. },
  65663. /**
  65664. * Gets or sets the inner angle for the directional cone.
  65665. */
  65666. set: function (value) {
  65667. if (value != this._coneInnerAngle) {
  65668. if (this._coneOuterAngle < value) {
  65669. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65670. return;
  65671. }
  65672. this._coneInnerAngle = value;
  65673. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65674. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  65675. }
  65676. }
  65677. },
  65678. enumerable: true,
  65679. configurable: true
  65680. });
  65681. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  65682. /**
  65683. * Gets or sets the outer angle for the directional cone.
  65684. */
  65685. get: function () {
  65686. return this._coneOuterAngle;
  65687. },
  65688. /**
  65689. * Gets or sets the outer angle for the directional cone.
  65690. */
  65691. set: function (value) {
  65692. if (value != this._coneOuterAngle) {
  65693. if (value < this._coneInnerAngle) {
  65694. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65695. return;
  65696. }
  65697. this._coneOuterAngle = value;
  65698. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65699. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65700. }
  65701. }
  65702. },
  65703. enumerable: true,
  65704. configurable: true
  65705. });
  65706. Sound.prototype.setPosition = function (newPosition) {
  65707. this._position = newPosition;
  65708. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65709. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65710. }
  65711. };
  65712. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  65713. this._localDirection = newLocalDirection;
  65714. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  65715. this._updateDirection();
  65716. }
  65717. };
  65718. Sound.prototype._updateDirection = function () {
  65719. if (!this._connectedMesh || !this._soundPanner) {
  65720. return;
  65721. }
  65722. var mat = this._connectedMesh.getWorldMatrix();
  65723. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  65724. direction.normalize();
  65725. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  65726. };
  65727. Sound.prototype.updateDistanceFromListener = function () {
  65728. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  65729. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  65730. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  65731. }
  65732. };
  65733. Sound.prototype.setAttenuationFunction = function (callback) {
  65734. this._customAttenuationFunction = callback;
  65735. };
  65736. /**
  65737. * Play the sound
  65738. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  65739. * @param offset (optional) Start the sound setting it at a specific time
  65740. */
  65741. Sound.prototype.play = function (time, offset) {
  65742. var _this = this;
  65743. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  65744. try {
  65745. if (this._startOffset < 0) {
  65746. time = -this._startOffset;
  65747. this._startOffset = 0;
  65748. }
  65749. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65750. if (!this._soundSource || !this._streamingSource) {
  65751. if (this.spatialSound && this._soundPanner) {
  65752. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65753. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65754. }
  65755. if (this._isDirectional) {
  65756. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  65757. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65758. this._soundPanner.coneOuterGain = this._coneOuterGain;
  65759. if (this._connectedMesh) {
  65760. this._updateDirection();
  65761. }
  65762. else {
  65763. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  65764. }
  65765. }
  65766. }
  65767. }
  65768. if (this._streaming) {
  65769. if (!this._streamingSource) {
  65770. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  65771. this._htmlAudioElement.onended = function () { _this._onended(); };
  65772. this._htmlAudioElement.playbackRate = this._playbackRate;
  65773. }
  65774. this._streamingSource.disconnect();
  65775. this._streamingSource.connect(this._inputAudioNode);
  65776. if (this._htmlAudioElement) {
  65777. this._htmlAudioElement.play();
  65778. }
  65779. }
  65780. else {
  65781. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  65782. this._soundSource.buffer = this._audioBuffer;
  65783. this._soundSource.connect(this._inputAudioNode);
  65784. this._soundSource.loop = this.loop;
  65785. this._soundSource.playbackRate.value = this._playbackRate;
  65786. this._soundSource.onended = function () { _this._onended(); };
  65787. if (this._soundSource.buffer) {
  65788. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  65789. }
  65790. }
  65791. this._startTime = startTime;
  65792. this.isPlaying = true;
  65793. this.isPaused = false;
  65794. }
  65795. catch (ex) {
  65796. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  65797. }
  65798. }
  65799. };
  65800. Sound.prototype._onended = function () {
  65801. this.isPlaying = false;
  65802. if (this.onended) {
  65803. this.onended();
  65804. }
  65805. this.onEndedObservable.notifyObservers(this);
  65806. };
  65807. /**
  65808. * Stop the sound
  65809. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  65810. */
  65811. Sound.prototype.stop = function (time) {
  65812. if (this.isPlaying) {
  65813. if (this._streaming) {
  65814. if (this._htmlAudioElement) {
  65815. this._htmlAudioElement.pause();
  65816. // Test needed for Firefox or it will generate an Invalid State Error
  65817. if (this._htmlAudioElement.currentTime > 0) {
  65818. this._htmlAudioElement.currentTime = 0;
  65819. }
  65820. }
  65821. else {
  65822. this._streamingSource.disconnect();
  65823. }
  65824. }
  65825. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  65826. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65827. this._soundSource.stop(stopTime);
  65828. this._soundSource.onended = function () { };
  65829. if (!this.isPaused) {
  65830. this._startOffset = 0;
  65831. }
  65832. }
  65833. this.isPlaying = false;
  65834. }
  65835. };
  65836. Sound.prototype.pause = function () {
  65837. if (this.isPlaying) {
  65838. this.isPaused = true;
  65839. if (this._streaming) {
  65840. if (this._htmlAudioElement) {
  65841. this._htmlAudioElement.pause();
  65842. }
  65843. else {
  65844. this._streamingSource.disconnect();
  65845. }
  65846. }
  65847. else if (BABYLON.Engine.audioEngine.audioContext) {
  65848. this.stop(0);
  65849. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  65850. }
  65851. }
  65852. };
  65853. Sound.prototype.setVolume = function (newVolume, time) {
  65854. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  65855. if (time && BABYLON.Engine.audioEngine.audioContext) {
  65856. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  65857. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  65858. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  65859. }
  65860. else {
  65861. this._soundGain.gain.value = newVolume;
  65862. }
  65863. }
  65864. this._volume = newVolume;
  65865. };
  65866. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  65867. this._playbackRate = newPlaybackRate;
  65868. if (this.isPlaying) {
  65869. if (this._streaming && this._htmlAudioElement) {
  65870. this._htmlAudioElement.playbackRate = this._playbackRate;
  65871. }
  65872. else if (this._soundSource) {
  65873. this._soundSource.playbackRate.value = this._playbackRate;
  65874. }
  65875. }
  65876. };
  65877. Sound.prototype.getVolume = function () {
  65878. return this._volume;
  65879. };
  65880. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  65881. var _this = this;
  65882. if (this._connectedMesh && this._registerFunc) {
  65883. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65884. this._registerFunc = null;
  65885. }
  65886. this._connectedMesh = meshToConnectTo;
  65887. if (!this.spatialSound) {
  65888. this.spatialSound = true;
  65889. this._createSpatialParameters();
  65890. if (this.isPlaying && this.loop) {
  65891. this.stop();
  65892. this.play();
  65893. }
  65894. }
  65895. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  65896. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  65897. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  65898. };
  65899. Sound.prototype.detachFromMesh = function () {
  65900. if (this._connectedMesh && this._registerFunc) {
  65901. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65902. this._registerFunc = null;
  65903. this._connectedMesh = null;
  65904. }
  65905. };
  65906. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  65907. if (!node.getBoundingInfo) {
  65908. return;
  65909. }
  65910. var mesh = node;
  65911. if (this._positionInEmitterSpace) {
  65912. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  65913. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  65914. }
  65915. else {
  65916. var boundingInfo = mesh.getBoundingInfo();
  65917. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  65918. }
  65919. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  65920. this._updateDirection();
  65921. }
  65922. };
  65923. Sound.prototype.clone = function () {
  65924. var _this = this;
  65925. if (!this._streaming) {
  65926. var setBufferAndRun = function () {
  65927. if (_this._isReadyToPlay) {
  65928. clonedSound._audioBuffer = _this.getAudioBuffer();
  65929. clonedSound._isReadyToPlay = true;
  65930. if (clonedSound.autoplay) {
  65931. clonedSound.play();
  65932. }
  65933. }
  65934. else {
  65935. window.setTimeout(setBufferAndRun, 300);
  65936. }
  65937. };
  65938. var currentOptions = {
  65939. autoplay: this.autoplay, loop: this.loop,
  65940. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  65941. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  65942. refDistance: this.refDistance, distanceModel: this.distanceModel
  65943. };
  65944. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  65945. if (this.useCustomAttenuation) {
  65946. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  65947. }
  65948. clonedSound.setPosition(this._position);
  65949. clonedSound.setPlaybackRate(this._playbackRate);
  65950. setBufferAndRun();
  65951. return clonedSound;
  65952. }
  65953. // Can't clone a streaming sound
  65954. else {
  65955. return null;
  65956. }
  65957. };
  65958. Sound.prototype.getAudioBuffer = function () {
  65959. return this._audioBuffer;
  65960. };
  65961. Sound.prototype.serialize = function () {
  65962. var serializationObject = {
  65963. name: this.name,
  65964. url: this.name,
  65965. autoplay: this.autoplay,
  65966. loop: this.loop,
  65967. volume: this._volume,
  65968. spatialSound: this.spatialSound,
  65969. maxDistance: this.maxDistance,
  65970. rolloffFactor: this.rolloffFactor,
  65971. refDistance: this.refDistance,
  65972. distanceModel: this.distanceModel,
  65973. playbackRate: this._playbackRate,
  65974. panningModel: this._panningModel,
  65975. soundTrackId: this.soundTrackId
  65976. };
  65977. if (this.spatialSound) {
  65978. if (this._connectedMesh)
  65979. serializationObject.connectedMeshId = this._connectedMesh.id;
  65980. serializationObject.position = this._position.asArray();
  65981. serializationObject.refDistance = this.refDistance;
  65982. serializationObject.distanceModel = this.distanceModel;
  65983. serializationObject.isDirectional = this._isDirectional;
  65984. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  65985. serializationObject.coneInnerAngle = this._coneInnerAngle;
  65986. serializationObject.coneOuterAngle = this._coneOuterAngle;
  65987. serializationObject.coneOuterGain = this._coneOuterGain;
  65988. }
  65989. return serializationObject;
  65990. };
  65991. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  65992. var soundName = parsedSound.name;
  65993. var soundUrl;
  65994. if (parsedSound.url) {
  65995. soundUrl = rootUrl + parsedSound.url;
  65996. }
  65997. else {
  65998. soundUrl = rootUrl + soundName;
  65999. }
  66000. var options = {
  66001. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  66002. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  66003. rolloffFactor: parsedSound.rolloffFactor,
  66004. refDistance: parsedSound.refDistance,
  66005. distanceModel: parsedSound.distanceModel,
  66006. playbackRate: parsedSound.playbackRate
  66007. };
  66008. var newSound;
  66009. if (!sourceSound) {
  66010. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  66011. scene._addPendingData(newSound);
  66012. }
  66013. else {
  66014. var setBufferAndRun = function () {
  66015. if (sourceSound._isReadyToPlay) {
  66016. newSound._audioBuffer = sourceSound.getAudioBuffer();
  66017. newSound._isReadyToPlay = true;
  66018. if (newSound.autoplay) {
  66019. newSound.play();
  66020. }
  66021. }
  66022. else {
  66023. window.setTimeout(setBufferAndRun, 300);
  66024. }
  66025. };
  66026. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  66027. setBufferAndRun();
  66028. }
  66029. if (parsedSound.position) {
  66030. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  66031. newSound.setPosition(soundPosition);
  66032. }
  66033. if (parsedSound.isDirectional) {
  66034. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  66035. if (parsedSound.localDirectionToMesh) {
  66036. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  66037. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  66038. }
  66039. }
  66040. if (parsedSound.connectedMeshId) {
  66041. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  66042. if (connectedMesh) {
  66043. newSound.attachToMesh(connectedMesh);
  66044. }
  66045. }
  66046. return newSound;
  66047. };
  66048. return Sound;
  66049. }());
  66050. BABYLON.Sound = Sound;
  66051. })(BABYLON || (BABYLON = {}));
  66052. //# sourceMappingURL=babylon.sound.js.map
  66053. var BABYLON;
  66054. (function (BABYLON) {
  66055. var SoundTrack = /** @class */ (function () {
  66056. function SoundTrack(scene, options) {
  66057. this.id = -1;
  66058. this._isMainTrack = false;
  66059. this._isInitialized = false;
  66060. this._scene = scene;
  66061. this.soundCollection = new Array();
  66062. this._options = options;
  66063. if (!this._isMainTrack) {
  66064. this._scene.soundTracks.push(this);
  66065. this.id = this._scene.soundTracks.length - 1;
  66066. }
  66067. }
  66068. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  66069. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66070. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  66071. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  66072. if (this._options) {
  66073. if (this._options.volume) {
  66074. this._outputAudioNode.gain.value = this._options.volume;
  66075. }
  66076. if (this._options.mainTrack) {
  66077. this._isMainTrack = this._options.mainTrack;
  66078. }
  66079. }
  66080. this._isInitialized = true;
  66081. }
  66082. };
  66083. SoundTrack.prototype.dispose = function () {
  66084. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  66085. if (this._connectedAnalyser) {
  66086. this._connectedAnalyser.stopDebugCanvas();
  66087. }
  66088. while (this.soundCollection.length) {
  66089. this.soundCollection[0].dispose();
  66090. }
  66091. if (this._outputAudioNode) {
  66092. this._outputAudioNode.disconnect();
  66093. }
  66094. this._outputAudioNode = null;
  66095. }
  66096. };
  66097. SoundTrack.prototype.AddSound = function (sound) {
  66098. if (!this._isInitialized) {
  66099. this._initializeSoundTrackAudioGraph();
  66100. }
  66101. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66102. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  66103. }
  66104. if (sound.soundTrackId) {
  66105. if (sound.soundTrackId === -1) {
  66106. this._scene.mainSoundTrack.RemoveSound(sound);
  66107. }
  66108. else {
  66109. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  66110. }
  66111. }
  66112. this.soundCollection.push(sound);
  66113. sound.soundTrackId = this.id;
  66114. };
  66115. SoundTrack.prototype.RemoveSound = function (sound) {
  66116. var index = this.soundCollection.indexOf(sound);
  66117. if (index !== -1) {
  66118. this.soundCollection.splice(index, 1);
  66119. }
  66120. };
  66121. SoundTrack.prototype.setVolume = function (newVolume) {
  66122. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66123. this._outputAudioNode.gain.value = newVolume;
  66124. }
  66125. };
  66126. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  66127. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66128. for (var i = 0; i < this.soundCollection.length; i++) {
  66129. this.soundCollection[i].switchPanningModelToHRTF();
  66130. }
  66131. }
  66132. };
  66133. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  66134. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66135. for (var i = 0; i < this.soundCollection.length; i++) {
  66136. this.soundCollection[i].switchPanningModelToEqualPower();
  66137. }
  66138. }
  66139. };
  66140. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  66141. if (this._connectedAnalyser) {
  66142. this._connectedAnalyser.stopDebugCanvas();
  66143. }
  66144. this._connectedAnalyser = analyser;
  66145. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66146. this._outputAudioNode.disconnect();
  66147. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  66148. }
  66149. };
  66150. return SoundTrack;
  66151. }());
  66152. BABYLON.SoundTrack = SoundTrack;
  66153. })(BABYLON || (BABYLON = {}));
  66154. //# sourceMappingURL=babylon.soundtrack.js.map
  66155. var BABYLON;
  66156. (function (BABYLON) {
  66157. /**
  66158. * Class used to work with sound analyzer using fast fourier transform (FFT)
  66159. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  66160. */
  66161. var Analyser = /** @class */ (function () {
  66162. /**
  66163. * Creates a new analyser
  66164. * @param scene defines hosting scene
  66165. */
  66166. function Analyser(scene) {
  66167. /**
  66168. * Gets or sets the smoothing
  66169. * @ignorenaming
  66170. */
  66171. this.SMOOTHING = 0.75;
  66172. /**
  66173. * Gets or sets the FFT table size
  66174. * @ignorenaming
  66175. */
  66176. this.FFT_SIZE = 512;
  66177. /**
  66178. * Gets or sets the bar graph amplitude
  66179. * @ignorenaming
  66180. */
  66181. this.BARGRAPHAMPLITUDE = 256;
  66182. /**
  66183. * Gets or sets the position of the debug canvas
  66184. * @ignorenaming
  66185. */
  66186. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  66187. /**
  66188. * Gets or sets the debug canvas size
  66189. * @ignorenaming
  66190. */
  66191. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  66192. this._scene = scene;
  66193. this._audioEngine = BABYLON.Engine.audioEngine;
  66194. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  66195. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  66196. this._webAudioAnalyser.minDecibels = -140;
  66197. this._webAudioAnalyser.maxDecibels = 0;
  66198. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66199. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66200. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  66201. }
  66202. }
  66203. /**
  66204. * Get the number of data values you will have to play with for the visualization
  66205. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  66206. * @returns a number
  66207. */
  66208. Analyser.prototype.getFrequencyBinCount = function () {
  66209. if (this._audioEngine.canUseWebAudio) {
  66210. return this._webAudioAnalyser.frequencyBinCount;
  66211. }
  66212. else {
  66213. return 0;
  66214. }
  66215. };
  66216. /**
  66217. * Gets the current frequency data as a byte array
  66218. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66219. * @returns a Uint8Array
  66220. */
  66221. Analyser.prototype.getByteFrequencyData = function () {
  66222. if (this._audioEngine.canUseWebAudio) {
  66223. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66224. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66225. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  66226. }
  66227. return this._byteFreqs;
  66228. };
  66229. /**
  66230. * Gets the current waveform as a byte array
  66231. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  66232. * @returns a Uint8Array
  66233. */
  66234. Analyser.prototype.getByteTimeDomainData = function () {
  66235. if (this._audioEngine.canUseWebAudio) {
  66236. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66237. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66238. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  66239. }
  66240. return this._byteTime;
  66241. };
  66242. /**
  66243. * Gets the current frequency data as a float array
  66244. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66245. * @returns a Float32Array
  66246. */
  66247. Analyser.prototype.getFloatFrequencyData = function () {
  66248. if (this._audioEngine.canUseWebAudio) {
  66249. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66250. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66251. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  66252. }
  66253. return this._floatFreqs;
  66254. };
  66255. /**
  66256. * Renders the debug canvas
  66257. */
  66258. Analyser.prototype.drawDebugCanvas = function () {
  66259. var _this = this;
  66260. if (this._audioEngine.canUseWebAudio) {
  66261. if (!this._debugCanvas) {
  66262. this._debugCanvas = document.createElement("canvas");
  66263. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  66264. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  66265. this._debugCanvas.style.position = "absolute";
  66266. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  66267. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  66268. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  66269. document.body.appendChild(this._debugCanvas);
  66270. this._registerFunc = function () {
  66271. _this.drawDebugCanvas();
  66272. };
  66273. this._scene.registerBeforeRender(this._registerFunc);
  66274. }
  66275. if (this._registerFunc && this._debugCanvasContext) {
  66276. var workingArray = this.getByteFrequencyData();
  66277. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  66278. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  66279. // Draw the frequency domain chart.
  66280. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  66281. var value = workingArray[i];
  66282. var percent = value / this.BARGRAPHAMPLITUDE;
  66283. var height = this.DEBUGCANVASSIZE.height * percent;
  66284. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  66285. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  66286. var hue = i / this.getFrequencyBinCount() * 360;
  66287. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  66288. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  66289. }
  66290. }
  66291. }
  66292. };
  66293. /**
  66294. * Stops rendering the debug canvas and removes it
  66295. */
  66296. Analyser.prototype.stopDebugCanvas = function () {
  66297. if (this._debugCanvas) {
  66298. if (this._registerFunc) {
  66299. this._scene.unregisterBeforeRender(this._registerFunc);
  66300. this._registerFunc = null;
  66301. }
  66302. document.body.removeChild(this._debugCanvas);
  66303. this._debugCanvas = null;
  66304. this._debugCanvasContext = null;
  66305. }
  66306. };
  66307. /**
  66308. * Connects two audio nodes
  66309. * @param inputAudioNode defines first node to connect
  66310. * @param outputAudioNode defines second node to connect
  66311. */
  66312. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  66313. if (this._audioEngine.canUseWebAudio) {
  66314. inputAudioNode.connect(this._webAudioAnalyser);
  66315. this._webAudioAnalyser.connect(outputAudioNode);
  66316. }
  66317. };
  66318. /**
  66319. * Releases all associated resources
  66320. */
  66321. Analyser.prototype.dispose = function () {
  66322. if (this._audioEngine.canUseWebAudio) {
  66323. this._webAudioAnalyser.disconnect();
  66324. }
  66325. };
  66326. return Analyser;
  66327. }());
  66328. BABYLON.Analyser = Analyser;
  66329. })(BABYLON || (BABYLON = {}));
  66330. //# sourceMappingURL=babylon.analyser.js.map
  66331. var BABYLON;
  66332. (function (BABYLON) {
  66333. /**
  66334. * Wraps one or more Sound objects and selects one with random weight for playback.
  66335. */
  66336. var WeightedSound = /** @class */ (function () {
  66337. /**
  66338. * Creates a new WeightedSound from the list of sounds given.
  66339. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  66340. * @param sounds Array of Sounds that will be selected from.
  66341. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  66342. */
  66343. function WeightedSound(loop, sounds, weights) {
  66344. var _this = this;
  66345. /** When true a Sound will be selected and played when the current playing Sound completes. */
  66346. this.loop = false;
  66347. this._coneInnerAngle = 360;
  66348. this._coneOuterAngle = 360;
  66349. this._volume = 1;
  66350. /** A Sound is currently playing. */
  66351. this.isPlaying = false;
  66352. /** A Sound is currently paused. */
  66353. this.isPaused = false;
  66354. this._sounds = [];
  66355. this._weights = [];
  66356. if (sounds.length !== weights.length) {
  66357. throw new Error('Sounds length does not equal weights length');
  66358. }
  66359. this.loop = loop;
  66360. this._weights = weights;
  66361. // Normalize the weights
  66362. var weightSum = 0;
  66363. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  66364. var weight = weights_1[_i];
  66365. weightSum += weight;
  66366. }
  66367. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  66368. for (var i = 0; i < this._weights.length; i++) {
  66369. this._weights[i] *= invWeightSum;
  66370. }
  66371. this._sounds = sounds;
  66372. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  66373. var sound = _b[_a];
  66374. sound.onEndedObservable.add(function () { _this._onended(); });
  66375. }
  66376. }
  66377. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  66378. /**
  66379. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  66380. */
  66381. get: function () {
  66382. return this._coneInnerAngle;
  66383. },
  66384. /**
  66385. * The size of cone in degress for a directional sound in which there will be no attenuation.
  66386. */
  66387. set: function (value) {
  66388. if (value !== this._coneInnerAngle) {
  66389. if (this._coneOuterAngle < value) {
  66390. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66391. return;
  66392. }
  66393. this._coneInnerAngle = value;
  66394. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66395. var sound = _a[_i];
  66396. sound.directionalConeInnerAngle = value;
  66397. }
  66398. }
  66399. },
  66400. enumerable: true,
  66401. configurable: true
  66402. });
  66403. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  66404. /**
  66405. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66406. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66407. */
  66408. get: function () {
  66409. return this._coneOuterAngle;
  66410. },
  66411. /**
  66412. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66413. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66414. */
  66415. set: function (value) {
  66416. if (value !== this._coneOuterAngle) {
  66417. if (value < this._coneInnerAngle) {
  66418. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66419. return;
  66420. }
  66421. this._coneOuterAngle = value;
  66422. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66423. var sound = _a[_i];
  66424. sound.directionalConeOuterAngle = value;
  66425. }
  66426. }
  66427. },
  66428. enumerable: true,
  66429. configurable: true
  66430. });
  66431. Object.defineProperty(WeightedSound.prototype, "volume", {
  66432. /**
  66433. * Playback volume.
  66434. */
  66435. get: function () {
  66436. return this._volume;
  66437. },
  66438. /**
  66439. * Playback volume.
  66440. */
  66441. set: function (value) {
  66442. if (value !== this._volume) {
  66443. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66444. var sound = _a[_i];
  66445. sound.setVolume(value);
  66446. }
  66447. }
  66448. },
  66449. enumerable: true,
  66450. configurable: true
  66451. });
  66452. WeightedSound.prototype._onended = function () {
  66453. if (this._currentIndex !== undefined) {
  66454. this._sounds[this._currentIndex].autoplay = false;
  66455. }
  66456. if (this.loop && this.isPlaying) {
  66457. this.play();
  66458. }
  66459. else {
  66460. this.isPlaying = false;
  66461. }
  66462. };
  66463. /**
  66464. * Suspend playback
  66465. */
  66466. WeightedSound.prototype.pause = function () {
  66467. this.isPaused = true;
  66468. if (this._currentIndex !== undefined) {
  66469. this._sounds[this._currentIndex].pause();
  66470. }
  66471. };
  66472. /**
  66473. * Stop playback
  66474. */
  66475. WeightedSound.prototype.stop = function () {
  66476. this.isPlaying = false;
  66477. if (this._currentIndex !== undefined) {
  66478. this._sounds[this._currentIndex].stop();
  66479. }
  66480. };
  66481. /**
  66482. * Start playback.
  66483. * @param startOffset Position the clip head at a specific time in seconds.
  66484. */
  66485. WeightedSound.prototype.play = function (startOffset) {
  66486. if (!this.isPaused) {
  66487. this.stop();
  66488. var randomValue = Math.random();
  66489. var total = 0;
  66490. for (var i = 0; i < this._weights.length; i++) {
  66491. total += this._weights[i];
  66492. if (randomValue <= total) {
  66493. this._currentIndex = i;
  66494. break;
  66495. }
  66496. }
  66497. }
  66498. var sound = this._sounds[this._currentIndex];
  66499. if (sound.isReady()) {
  66500. sound.play(0, this.isPaused ? undefined : startOffset);
  66501. }
  66502. else {
  66503. sound.autoplay = true;
  66504. }
  66505. this.isPlaying = true;
  66506. this.isPaused = false;
  66507. };
  66508. return WeightedSound;
  66509. }());
  66510. BABYLON.WeightedSound = WeightedSound;
  66511. })(BABYLON || (BABYLON = {}));
  66512. //# sourceMappingURL=babylon.weightedsound.js.map
  66513. var BABYLON;
  66514. (function (BABYLON) {
  66515. var CubeTexture = /** @class */ (function (_super) {
  66516. __extends(CubeTexture, _super);
  66517. /**
  66518. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  66519. * as prefiltered data.
  66520. * @param rootUrl defines the url of the texture or the root name of the six images
  66521. * @param scene defines the scene the texture is attached to
  66522. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  66523. * @param noMipmap defines if mipmaps should be created or not
  66524. * @param files defines the six files to load for the different faces
  66525. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  66526. * @param onError defines a callback triggered in case of error during load
  66527. * @param format defines the internal format to use for the texture once loaded
  66528. * @param prefiltered defines whether or not the texture is created from prefiltered data
  66529. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  66530. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  66531. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66532. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66533. * @return the cube texture
  66534. */
  66535. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  66536. if (extensions === void 0) { extensions = null; }
  66537. if (noMipmap === void 0) { noMipmap = false; }
  66538. if (files === void 0) { files = null; }
  66539. if (onLoad === void 0) { onLoad = null; }
  66540. if (onError === void 0) { onError = null; }
  66541. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66542. if (prefiltered === void 0) { prefiltered = false; }
  66543. if (forcedExtension === void 0) { forcedExtension = null; }
  66544. if (createPolynomials === void 0) { createPolynomials = false; }
  66545. if (lodScale === void 0) { lodScale = 0.8; }
  66546. if (lodOffset === void 0) { lodOffset = 0; }
  66547. var _this = _super.call(this, scene) || this;
  66548. /**
  66549. * Gets or sets the center of the bounding box associated with the cube texture
  66550. * It must define where the camera used to render the texture was set
  66551. */
  66552. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66553. _this._rotationY = 0;
  66554. /** @hidden */
  66555. _this._prefiltered = false;
  66556. _this.name = rootUrl;
  66557. _this.url = rootUrl;
  66558. _this._noMipmap = noMipmap;
  66559. _this.hasAlpha = false;
  66560. _this._format = format;
  66561. _this.isCube = true;
  66562. _this._textureMatrix = BABYLON.Matrix.Identity();
  66563. _this._createPolynomials = createPolynomials;
  66564. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  66565. if (!rootUrl && !files) {
  66566. return _this;
  66567. }
  66568. var lastDot = rootUrl.lastIndexOf(".");
  66569. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  66570. var isDDS = (extension === ".dds");
  66571. var isEnv = (extension === ".env");
  66572. if (isEnv) {
  66573. _this.gammaSpace = false;
  66574. _this._prefiltered = false;
  66575. }
  66576. else {
  66577. _this._prefiltered = prefiltered;
  66578. if (prefiltered) {
  66579. _this.gammaSpace = false;
  66580. }
  66581. }
  66582. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  66583. if (!files) {
  66584. if (!isEnv && !isDDS && !extensions) {
  66585. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  66586. }
  66587. files = [];
  66588. if (extensions) {
  66589. for (var index = 0; index < extensions.length; index++) {
  66590. files.push(rootUrl + extensions[index]);
  66591. }
  66592. }
  66593. }
  66594. _this._files = files;
  66595. if (!_this._texture) {
  66596. if (!scene.useDelayedTextureLoading) {
  66597. if (prefiltered) {
  66598. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  66599. }
  66600. else {
  66601. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  66602. }
  66603. }
  66604. else {
  66605. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  66606. }
  66607. }
  66608. else if (onLoad) {
  66609. if (_this._texture.isReady) {
  66610. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  66611. }
  66612. else {
  66613. _this._texture.onLoadedObservable.add(onLoad);
  66614. }
  66615. }
  66616. return _this;
  66617. }
  66618. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  66619. get: function () {
  66620. return this._boundingBoxSize;
  66621. },
  66622. /**
  66623. * Gets or sets the size of the bounding box associated with the cube texture
  66624. * When defined, the cubemap will switch to local mode
  66625. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  66626. * @example https://www.babylonjs-playground.com/#RNASML
  66627. */
  66628. set: function (value) {
  66629. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  66630. return;
  66631. }
  66632. this._boundingBoxSize = value;
  66633. var scene = this.getScene();
  66634. if (scene) {
  66635. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  66636. }
  66637. },
  66638. enumerable: true,
  66639. configurable: true
  66640. });
  66641. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  66642. /**
  66643. * Gets texture matrix rotation angle around Y axis radians.
  66644. */
  66645. get: function () {
  66646. return this._rotationY;
  66647. },
  66648. /**
  66649. * Sets texture matrix rotation angle around Y axis in radians.
  66650. */
  66651. set: function (value) {
  66652. this._rotationY = value;
  66653. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  66654. },
  66655. enumerable: true,
  66656. configurable: true
  66657. });
  66658. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  66659. var rootUrlKey = "";
  66660. files.forEach(function (url) { return rootUrlKey += url; });
  66661. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  66662. };
  66663. /**
  66664. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  66665. * @param url defines the url of the prefiltered texture
  66666. * @param scene defines the scene the texture is attached to
  66667. * @param forcedExtension defines the extension of the file if different from the url
  66668. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  66669. * @return the prefiltered texture
  66670. */
  66671. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  66672. if (forcedExtension === void 0) { forcedExtension = null; }
  66673. if (createPolynomials === void 0) { createPolynomials = true; }
  66674. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  66675. };
  66676. // Methods
  66677. CubeTexture.prototype.delayLoad = function () {
  66678. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  66679. return;
  66680. }
  66681. var scene = this.getScene();
  66682. if (!scene) {
  66683. return;
  66684. }
  66685. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  66686. this._texture = this._getFromCache(this.url, this._noMipmap);
  66687. if (!this._texture) {
  66688. if (this._prefiltered) {
  66689. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  66690. }
  66691. else {
  66692. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  66693. }
  66694. }
  66695. };
  66696. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  66697. return this._textureMatrix;
  66698. };
  66699. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  66700. this._textureMatrix = value;
  66701. };
  66702. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  66703. var texture = BABYLON.SerializationHelper.Parse(function () {
  66704. var prefiltered = false;
  66705. if (parsedTexture.prefiltered) {
  66706. prefiltered = parsedTexture.prefiltered;
  66707. }
  66708. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  66709. }, parsedTexture, scene);
  66710. // Local Cubemaps
  66711. if (parsedTexture.boundingBoxPosition) {
  66712. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  66713. }
  66714. if (parsedTexture.boundingBoxSize) {
  66715. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  66716. }
  66717. // Animations
  66718. if (parsedTexture.animations) {
  66719. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  66720. var parsedAnimation = parsedTexture.animations[animationIndex];
  66721. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  66722. }
  66723. }
  66724. return texture;
  66725. };
  66726. CubeTexture.prototype.clone = function () {
  66727. var _this = this;
  66728. return BABYLON.SerializationHelper.Clone(function () {
  66729. var scene = _this.getScene();
  66730. if (!scene) {
  66731. return _this;
  66732. }
  66733. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  66734. }, this);
  66735. };
  66736. __decorate([
  66737. BABYLON.serialize("rotationY")
  66738. ], CubeTexture.prototype, "rotationY", null);
  66739. return CubeTexture;
  66740. }(BABYLON.BaseTexture));
  66741. BABYLON.CubeTexture = CubeTexture;
  66742. })(BABYLON || (BABYLON = {}));
  66743. //# sourceMappingURL=babylon.cubeTexture.js.map
  66744. var BABYLON;
  66745. (function (BABYLON) {
  66746. /**
  66747. * Raw cube texture where the raw buffers are passed in
  66748. */
  66749. var RawCubeTexture = /** @class */ (function (_super) {
  66750. __extends(RawCubeTexture, _super);
  66751. /**
  66752. * Creates a cube texture where the raw buffers are passed in.
  66753. * @param scene defines the scene the texture is attached to
  66754. * @param data defines the array of data to use to create each face
  66755. * @param size defines the size of the textures
  66756. * @param format defines the format of the data
  66757. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  66758. * @param generateMipMaps defines if the engine should generate the mip levels
  66759. * @param invertY defines if data must be stored with Y axis inverted
  66760. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  66761. * @param compression defines the compression used (null by default)
  66762. */
  66763. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  66764. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66765. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66766. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66767. if (invertY === void 0) { invertY = false; }
  66768. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66769. if (compression === void 0) { compression = null; }
  66770. var _this = _super.call(this, "", scene) || this;
  66771. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  66772. return _this;
  66773. }
  66774. /**
  66775. * Updates the raw cube texture.
  66776. * @param data defines the data to store
  66777. * @param format defines the data format
  66778. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  66779. * @param invertY defines if data must be stored with Y axis inverted
  66780. * @param compression defines the compression used (null by default)
  66781. * @param level defines which level of the texture to update
  66782. */
  66783. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  66784. if (compression === void 0) { compression = null; }
  66785. if (level === void 0) { level = 0; }
  66786. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  66787. };
  66788. /**
  66789. * Updates a raw cube texture with RGBD encoded data.
  66790. * @param data defines the array of data [mipmap][face] to use to create each face
  66791. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  66792. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66793. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66794. * @returns a promsie that resolves when the operation is complete
  66795. */
  66796. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  66797. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  66798. if (lodScale === void 0) { lodScale = 0.8; }
  66799. if (lodOffset === void 0) { lodOffset = 0; }
  66800. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  66801. };
  66802. /**
  66803. * Clones the raw cube texture.
  66804. * @return a new cube texture
  66805. */
  66806. RawCubeTexture.prototype.clone = function () {
  66807. var _this = this;
  66808. return BABYLON.SerializationHelper.Clone(function () {
  66809. var scene = _this.getScene();
  66810. var internalTexture = _this._texture;
  66811. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  66812. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  66813. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  66814. }
  66815. return texture;
  66816. }, this);
  66817. };
  66818. /** @hidden */
  66819. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  66820. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  66821. internalTexture._bufferViewArrayArray = data;
  66822. internalTexture._lodGenerationScale = lodScale;
  66823. internalTexture._lodGenerationOffset = lodOffset;
  66824. internalTexture._sphericalPolynomial = sphericalPolynomial;
  66825. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  66826. internalTexture.isReady = true;
  66827. });
  66828. };
  66829. return RawCubeTexture;
  66830. }(BABYLON.CubeTexture));
  66831. BABYLON.RawCubeTexture = RawCubeTexture;
  66832. })(BABYLON || (BABYLON = {}));
  66833. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  66834. var BABYLON;
  66835. (function (BABYLON) {
  66836. var RenderTargetTexture = /** @class */ (function (_super) {
  66837. __extends(RenderTargetTexture, _super);
  66838. /**
  66839. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  66840. * or used a shadow, depth texture...
  66841. * @param name The friendly name of the texture
  66842. * @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)
  66843. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  66844. * @param generateMipMaps True if mip maps need to be generated after render.
  66845. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  66846. * @param type The type of the buffer in the RTT (int, half float, float...)
  66847. * @param isCube True if a cube texture needs to be created
  66848. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  66849. * @param generateDepthBuffer True to generate a depth buffer
  66850. * @param generateStencilBuffer True to generate a stencil buffer
  66851. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  66852. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  66853. */
  66854. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  66855. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  66856. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66857. if (isCube === void 0) { isCube = false; }
  66858. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66859. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  66860. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  66861. if (isMulti === void 0) { isMulti = false; }
  66862. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66863. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  66864. _this.isCube = isCube;
  66865. _this.renderParticles = true;
  66866. _this.renderSprites = false;
  66867. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  66868. _this.ignoreCameraViewport = false;
  66869. // Events
  66870. /**
  66871. * An event triggered when the texture is unbind.
  66872. */
  66873. _this.onBeforeBindObservable = new BABYLON.Observable();
  66874. /**
  66875. * An event triggered when the texture is unbind.
  66876. */
  66877. _this.onAfterUnbindObservable = new BABYLON.Observable();
  66878. /**
  66879. * An event triggered before rendering the texture
  66880. */
  66881. _this.onBeforeRenderObservable = new BABYLON.Observable();
  66882. /**
  66883. * An event triggered after rendering the texture
  66884. */
  66885. _this.onAfterRenderObservable = new BABYLON.Observable();
  66886. /**
  66887. * An event triggered after the texture clear
  66888. */
  66889. _this.onClearObservable = new BABYLON.Observable();
  66890. _this._currentRefreshId = -1;
  66891. _this._refreshRate = 1;
  66892. _this._samples = 1;
  66893. /**
  66894. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  66895. * It must define where the camera used to render the texture is set
  66896. */
  66897. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66898. scene = _this.getScene();
  66899. if (!scene) {
  66900. return _this;
  66901. }
  66902. _this.renderList = new Array();
  66903. _this._engine = scene.getEngine();
  66904. _this.name = name;
  66905. _this.isRenderTarget = true;
  66906. _this._initialSizeParameter = size;
  66907. _this._processSizeParameter(size);
  66908. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  66909. });
  66910. _this._generateMipMaps = generateMipMaps ? true : false;
  66911. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  66912. // Rendering groups
  66913. _this._renderingManager = new BABYLON.RenderingManager(scene);
  66914. _this._renderingManager._useSceneAutoClearSetup = true;
  66915. if (isMulti) {
  66916. return _this;
  66917. }
  66918. _this._renderTargetOptions = {
  66919. generateMipMaps: generateMipMaps,
  66920. type: type,
  66921. format: format,
  66922. samplingMode: samplingMode,
  66923. generateDepthBuffer: generateDepthBuffer,
  66924. generateStencilBuffer: generateStencilBuffer
  66925. };
  66926. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  66927. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66928. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66929. }
  66930. if (isCube) {
  66931. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  66932. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  66933. _this._textureMatrix = BABYLON.Matrix.Identity();
  66934. }
  66935. else {
  66936. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  66937. }
  66938. return _this;
  66939. }
  66940. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  66941. get: function () {
  66942. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  66943. },
  66944. enumerable: true,
  66945. configurable: true
  66946. });
  66947. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  66948. get: function () {
  66949. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  66950. },
  66951. enumerable: true,
  66952. configurable: true
  66953. });
  66954. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  66955. get: function () {
  66956. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  66957. },
  66958. enumerable: true,
  66959. configurable: true
  66960. });
  66961. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  66962. /**
  66963. * Use this list to define the list of mesh you want to render.
  66964. */
  66965. get: function () {
  66966. return this._renderList;
  66967. },
  66968. set: function (value) {
  66969. this._renderList = value;
  66970. if (this._renderList) {
  66971. this._hookArray(this._renderList);
  66972. }
  66973. },
  66974. enumerable: true,
  66975. configurable: true
  66976. });
  66977. RenderTargetTexture.prototype._hookArray = function (array) {
  66978. var _this = this;
  66979. var oldPush = array.push;
  66980. array.push = function () {
  66981. var items = [];
  66982. for (var _i = 0; _i < arguments.length; _i++) {
  66983. items[_i] = arguments[_i];
  66984. }
  66985. var result = oldPush.apply(array, items);
  66986. _this.getScene().meshes.forEach(function (mesh) {
  66987. mesh._markSubMeshesAsLightDirty();
  66988. });
  66989. return result;
  66990. };
  66991. var oldSplice = array.splice;
  66992. array.splice = function (index, deleteCount) {
  66993. var deleted = oldSplice.apply(array, [index, deleteCount]);
  66994. _this.getScene().meshes.forEach(function (mesh) {
  66995. mesh._markSubMeshesAsLightDirty();
  66996. });
  66997. return deleted;
  66998. };
  66999. };
  67000. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  67001. set: function (callback) {
  67002. if (this._onAfterUnbindObserver) {
  67003. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  67004. }
  67005. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  67006. },
  67007. enumerable: true,
  67008. configurable: true
  67009. });
  67010. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  67011. set: function (callback) {
  67012. if (this._onBeforeRenderObserver) {
  67013. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67014. }
  67015. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67016. },
  67017. enumerable: true,
  67018. configurable: true
  67019. });
  67020. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  67021. set: function (callback) {
  67022. if (this._onAfterRenderObserver) {
  67023. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67024. }
  67025. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67026. },
  67027. enumerable: true,
  67028. configurable: true
  67029. });
  67030. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  67031. set: function (callback) {
  67032. if (this._onClearObserver) {
  67033. this.onClearObservable.remove(this._onClearObserver);
  67034. }
  67035. this._onClearObserver = this.onClearObservable.add(callback);
  67036. },
  67037. enumerable: true,
  67038. configurable: true
  67039. });
  67040. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  67041. get: function () {
  67042. return this._renderTargetOptions;
  67043. },
  67044. enumerable: true,
  67045. configurable: true
  67046. });
  67047. RenderTargetTexture.prototype._onRatioRescale = function () {
  67048. if (this._sizeRatio) {
  67049. this.resize(this._initialSizeParameter);
  67050. }
  67051. };
  67052. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  67053. get: function () {
  67054. return this._boundingBoxSize;
  67055. },
  67056. /**
  67057. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  67058. * When defined, the cubemap will switch to local mode
  67059. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67060. * @example https://www.babylonjs-playground.com/#RNASML
  67061. */
  67062. set: function (value) {
  67063. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67064. return;
  67065. }
  67066. this._boundingBoxSize = value;
  67067. var scene = this.getScene();
  67068. if (scene) {
  67069. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67070. }
  67071. },
  67072. enumerable: true,
  67073. configurable: true
  67074. });
  67075. /**
  67076. * Creates a depth stencil texture.
  67077. * This is only available in WebGL 2 or with the depth texture extension available.
  67078. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  67079. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  67080. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  67081. */
  67082. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  67083. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  67084. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  67085. if (generateStencil === void 0) { generateStencil = false; }
  67086. if (!this.getScene()) {
  67087. return;
  67088. }
  67089. var engine = this.getScene().getEngine();
  67090. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  67091. bilinearFiltering: bilinearFiltering,
  67092. comparisonFunction: comparisonFunction,
  67093. generateStencil: generateStencil,
  67094. isCube: this.isCube
  67095. });
  67096. engine.setFrameBufferDepthStencilTexture(this);
  67097. };
  67098. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  67099. if (size.ratio) {
  67100. this._sizeRatio = size.ratio;
  67101. this._size = {
  67102. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  67103. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  67104. };
  67105. }
  67106. else {
  67107. this._size = size;
  67108. }
  67109. };
  67110. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  67111. get: function () {
  67112. return this._samples;
  67113. },
  67114. set: function (value) {
  67115. if (this._samples === value) {
  67116. return;
  67117. }
  67118. var scene = this.getScene();
  67119. if (!scene) {
  67120. return;
  67121. }
  67122. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  67123. },
  67124. enumerable: true,
  67125. configurable: true
  67126. });
  67127. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  67128. this._currentRefreshId = -1;
  67129. };
  67130. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  67131. get: function () {
  67132. return this._refreshRate;
  67133. },
  67134. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  67135. set: function (value) {
  67136. this._refreshRate = value;
  67137. this.resetRefreshCounter();
  67138. },
  67139. enumerable: true,
  67140. configurable: true
  67141. });
  67142. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  67143. if (!this._postProcessManager) {
  67144. var scene = this.getScene();
  67145. if (!scene) {
  67146. return;
  67147. }
  67148. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  67149. this._postProcesses = new Array();
  67150. }
  67151. this._postProcesses.push(postProcess);
  67152. this._postProcesses[0].autoClear = false;
  67153. };
  67154. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  67155. if (!this._postProcesses) {
  67156. return;
  67157. }
  67158. if (dispose) {
  67159. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  67160. var postProcess = _a[_i];
  67161. postProcess.dispose();
  67162. }
  67163. }
  67164. this._postProcesses = [];
  67165. };
  67166. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  67167. if (!this._postProcesses) {
  67168. return;
  67169. }
  67170. var index = this._postProcesses.indexOf(postProcess);
  67171. if (index === -1) {
  67172. return;
  67173. }
  67174. this._postProcesses.splice(index, 1);
  67175. if (this._postProcesses.length > 0) {
  67176. this._postProcesses[0].autoClear = false;
  67177. }
  67178. };
  67179. /** @hidden */
  67180. RenderTargetTexture.prototype._shouldRender = function () {
  67181. if (this._currentRefreshId === -1) { // At least render once
  67182. this._currentRefreshId = 1;
  67183. return true;
  67184. }
  67185. if (this.refreshRate === this._currentRefreshId) {
  67186. this._currentRefreshId = 1;
  67187. return true;
  67188. }
  67189. this._currentRefreshId++;
  67190. return false;
  67191. };
  67192. RenderTargetTexture.prototype.getRenderSize = function () {
  67193. if (this._size.width) {
  67194. return this._size.width;
  67195. }
  67196. return this._size;
  67197. };
  67198. RenderTargetTexture.prototype.getRenderWidth = function () {
  67199. if (this._size.width) {
  67200. return this._size.width;
  67201. }
  67202. return this._size;
  67203. };
  67204. RenderTargetTexture.prototype.getRenderHeight = function () {
  67205. if (this._size.width) {
  67206. return this._size.height;
  67207. }
  67208. return this._size;
  67209. };
  67210. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  67211. get: function () {
  67212. return true;
  67213. },
  67214. enumerable: true,
  67215. configurable: true
  67216. });
  67217. RenderTargetTexture.prototype.scale = function (ratio) {
  67218. var newSize = this.getRenderSize() * ratio;
  67219. this.resize(newSize);
  67220. };
  67221. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  67222. if (this.isCube) {
  67223. return this._textureMatrix;
  67224. }
  67225. return _super.prototype.getReflectionTextureMatrix.call(this);
  67226. };
  67227. RenderTargetTexture.prototype.resize = function (size) {
  67228. this.releaseInternalTexture();
  67229. var scene = this.getScene();
  67230. if (!scene) {
  67231. return;
  67232. }
  67233. this._processSizeParameter(size);
  67234. if (this.isCube) {
  67235. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  67236. }
  67237. else {
  67238. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  67239. }
  67240. };
  67241. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  67242. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  67243. if (dumpForDebug === void 0) { dumpForDebug = false; }
  67244. var scene = this.getScene();
  67245. if (!scene) {
  67246. return;
  67247. }
  67248. var engine = scene.getEngine();
  67249. if (this.useCameraPostProcesses !== undefined) {
  67250. useCameraPostProcess = this.useCameraPostProcesses;
  67251. }
  67252. if (this._waitingRenderList) {
  67253. this.renderList = [];
  67254. for (var index = 0; index < this._waitingRenderList.length; index++) {
  67255. var id = this._waitingRenderList[index];
  67256. var mesh_1 = scene.getMeshByID(id);
  67257. if (mesh_1) {
  67258. this.renderList.push(mesh_1);
  67259. }
  67260. }
  67261. delete this._waitingRenderList;
  67262. }
  67263. // Is predicate defined?
  67264. if (this.renderListPredicate) {
  67265. if (this.renderList) {
  67266. this.renderList.splice(0); // Clear previous renderList
  67267. }
  67268. else {
  67269. this.renderList = [];
  67270. }
  67271. var scene = this.getScene();
  67272. if (!scene) {
  67273. return;
  67274. }
  67275. var sceneMeshes = scene.meshes;
  67276. for (var index = 0; index < sceneMeshes.length; index++) {
  67277. var mesh = sceneMeshes[index];
  67278. if (this.renderListPredicate(mesh)) {
  67279. this.renderList.push(mesh);
  67280. }
  67281. }
  67282. }
  67283. this.onBeforeBindObservable.notifyObservers(this);
  67284. // Set custom projection.
  67285. // Needs to be before binding to prevent changing the aspect ratio.
  67286. var camera;
  67287. if (this.activeCamera) {
  67288. camera = this.activeCamera;
  67289. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  67290. if (this.activeCamera !== scene.activeCamera) {
  67291. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  67292. }
  67293. }
  67294. else {
  67295. camera = scene.activeCamera;
  67296. if (camera) {
  67297. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  67298. }
  67299. }
  67300. // Prepare renderingManager
  67301. this._renderingManager.reset();
  67302. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  67303. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  67304. var sceneRenderId = scene.getRenderId();
  67305. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  67306. var mesh = currentRenderList[meshIndex];
  67307. if (mesh) {
  67308. if (!mesh.isReady(this.refreshRate === 0)) {
  67309. this.resetRefreshCounter();
  67310. continue;
  67311. }
  67312. mesh._preActivateForIntermediateRendering(sceneRenderId);
  67313. var isMasked = void 0;
  67314. if (!this.renderList && camera) {
  67315. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  67316. }
  67317. else {
  67318. isMasked = false;
  67319. }
  67320. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  67321. mesh._activate(sceneRenderId);
  67322. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  67323. var subMesh = mesh.subMeshes[subIndex];
  67324. scene._activeIndices.addCount(subMesh.indexCount, false);
  67325. this._renderingManager.dispatch(subMesh, mesh);
  67326. }
  67327. }
  67328. }
  67329. }
  67330. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  67331. var particleSystem = scene.particleSystems[particleIndex];
  67332. var emitter = particleSystem.emitter;
  67333. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  67334. continue;
  67335. }
  67336. if (currentRenderList.indexOf(emitter) >= 0) {
  67337. this._renderingManager.dispatchParticles(particleSystem);
  67338. }
  67339. }
  67340. if (this.isCube) {
  67341. for (var face = 0; face < 6; face++) {
  67342. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  67343. scene.incrementRenderId();
  67344. scene.resetCachedMaterial();
  67345. }
  67346. }
  67347. else {
  67348. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  67349. }
  67350. this.onAfterUnbindObservable.notifyObservers(this);
  67351. if (scene.activeCamera) {
  67352. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  67353. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  67354. }
  67355. engine.setViewport(scene.activeCamera.viewport);
  67356. }
  67357. scene.resetCachedMaterial();
  67358. };
  67359. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  67360. var minimum = 128;
  67361. var x = renderDimension * scale;
  67362. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  67363. // Ensure we don't exceed the render dimension (while staying POT)
  67364. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  67365. };
  67366. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  67367. var _this = this;
  67368. if (!this._texture) {
  67369. return;
  67370. }
  67371. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  67372. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  67373. });
  67374. };
  67375. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  67376. var scene = this.getScene();
  67377. if (!scene) {
  67378. return;
  67379. }
  67380. var engine = scene.getEngine();
  67381. if (!this._texture) {
  67382. return;
  67383. }
  67384. // Bind
  67385. if (this._postProcessManager) {
  67386. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  67387. }
  67388. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  67389. if (this._texture) {
  67390. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  67391. }
  67392. }
  67393. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  67394. // Clear
  67395. if (this.onClearObservable.hasObservers()) {
  67396. this.onClearObservable.notifyObservers(engine);
  67397. }
  67398. else {
  67399. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  67400. }
  67401. if (!this._doNotChangeAspectRatio) {
  67402. scene.updateTransformMatrix(true);
  67403. }
  67404. // Render
  67405. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  67406. if (this._postProcessManager) {
  67407. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  67408. }
  67409. else if (useCameraPostProcess) {
  67410. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  67411. }
  67412. if (!this._doNotChangeAspectRatio) {
  67413. scene.updateTransformMatrix(true);
  67414. }
  67415. // Dump ?
  67416. if (dumpForDebug) {
  67417. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  67418. }
  67419. // Unbind
  67420. if (!this.isCube || faceIndex === 5) {
  67421. if (this.isCube) {
  67422. if (faceIndex === 5) {
  67423. engine.generateMipMapsForCubemap(this._texture);
  67424. }
  67425. }
  67426. this.unbindFrameBuffer(engine, faceIndex);
  67427. }
  67428. else {
  67429. this.onAfterRenderObservable.notifyObservers(faceIndex);
  67430. }
  67431. };
  67432. /**
  67433. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  67434. * This allowed control for front to back rendering or reversly depending of the special needs.
  67435. *
  67436. * @param renderingGroupId The rendering group id corresponding to its index
  67437. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  67438. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  67439. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  67440. */
  67441. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  67442. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  67443. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  67444. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  67445. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  67446. };
  67447. /**
  67448. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  67449. *
  67450. * @param renderingGroupId The rendering group id corresponding to its index
  67451. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  67452. */
  67453. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  67454. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  67455. this._renderingManager._useSceneAutoClearSetup = false;
  67456. };
  67457. RenderTargetTexture.prototype.clone = function () {
  67458. var textureSize = this.getSize();
  67459. 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);
  67460. // Base texture
  67461. newTexture.hasAlpha = this.hasAlpha;
  67462. newTexture.level = this.level;
  67463. // RenderTarget Texture
  67464. newTexture.coordinatesMode = this.coordinatesMode;
  67465. if (this.renderList) {
  67466. newTexture.renderList = this.renderList.slice(0);
  67467. }
  67468. return newTexture;
  67469. };
  67470. RenderTargetTexture.prototype.serialize = function () {
  67471. if (!this.name) {
  67472. return null;
  67473. }
  67474. var serializationObject = _super.prototype.serialize.call(this);
  67475. serializationObject.renderTargetSize = this.getRenderSize();
  67476. serializationObject.renderList = [];
  67477. if (this.renderList) {
  67478. for (var index = 0; index < this.renderList.length; index++) {
  67479. serializationObject.renderList.push(this.renderList[index].id);
  67480. }
  67481. }
  67482. return serializationObject;
  67483. };
  67484. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  67485. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  67486. var objBuffer = this.getInternalTexture();
  67487. var scene = this.getScene();
  67488. if (objBuffer && scene) {
  67489. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  67490. }
  67491. };
  67492. RenderTargetTexture.prototype.dispose = function () {
  67493. if (this._postProcessManager) {
  67494. this._postProcessManager.dispose();
  67495. this._postProcessManager = null;
  67496. }
  67497. this.clearPostProcesses(true);
  67498. if (this._resizeObserver) {
  67499. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  67500. this._resizeObserver = null;
  67501. }
  67502. this.renderList = null;
  67503. // Remove from custom render targets
  67504. var scene = this.getScene();
  67505. if (!scene) {
  67506. return;
  67507. }
  67508. var index = scene.customRenderTargets.indexOf(this);
  67509. if (index >= 0) {
  67510. scene.customRenderTargets.splice(index, 1);
  67511. }
  67512. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  67513. var camera = _a[_i];
  67514. index = camera.customRenderTargets.indexOf(this);
  67515. if (index >= 0) {
  67516. camera.customRenderTargets.splice(index, 1);
  67517. }
  67518. }
  67519. _super.prototype.dispose.call(this);
  67520. };
  67521. /** @hidden */
  67522. RenderTargetTexture.prototype._rebuild = function () {
  67523. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  67524. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  67525. }
  67526. if (this._postProcessManager) {
  67527. this._postProcessManager._rebuild();
  67528. }
  67529. };
  67530. /**
  67531. * Clear the info related to rendering groups preventing retention point in material dispose.
  67532. */
  67533. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  67534. if (this._renderingManager) {
  67535. this._renderingManager.freeRenderingGroups();
  67536. }
  67537. };
  67538. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  67539. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  67540. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  67541. return RenderTargetTexture;
  67542. }(BABYLON.Texture));
  67543. BABYLON.RenderTargetTexture = RenderTargetTexture;
  67544. })(BABYLON || (BABYLON = {}));
  67545. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  67546. var BABYLON;
  67547. (function (BABYLON) {
  67548. ;
  67549. var MultiRenderTarget = /** @class */ (function (_super) {
  67550. __extends(MultiRenderTarget, _super);
  67551. function MultiRenderTarget(name, size, count, scene, options) {
  67552. var _this = this;
  67553. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  67554. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  67555. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  67556. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  67557. _this._engine = scene.getEngine();
  67558. if (!_this.isSupported) {
  67559. _this.dispose();
  67560. return;
  67561. }
  67562. var types = [];
  67563. var samplingModes = [];
  67564. for (var i = 0; i < count; i++) {
  67565. if (options && options.types && options.types[i] !== undefined) {
  67566. types.push(options.types[i]);
  67567. }
  67568. else {
  67569. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67570. }
  67571. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  67572. samplingModes.push(options.samplingModes[i]);
  67573. }
  67574. else {
  67575. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67576. }
  67577. }
  67578. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  67579. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  67580. _this._size = size;
  67581. _this._multiRenderTargetOptions = {
  67582. samplingModes: samplingModes,
  67583. generateMipMaps: generateMipMaps,
  67584. generateDepthBuffer: generateDepthBuffer,
  67585. generateStencilBuffer: generateStencilBuffer,
  67586. generateDepthTexture: generateDepthTexture,
  67587. types: types,
  67588. textureCount: count
  67589. };
  67590. _this._createInternalTextures();
  67591. _this._createTextures();
  67592. return _this;
  67593. }
  67594. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  67595. get: function () {
  67596. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  67597. },
  67598. enumerable: true,
  67599. configurable: true
  67600. });
  67601. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  67602. get: function () {
  67603. return this._textures;
  67604. },
  67605. enumerable: true,
  67606. configurable: true
  67607. });
  67608. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  67609. get: function () {
  67610. return this._textures[this._textures.length - 1];
  67611. },
  67612. enumerable: true,
  67613. configurable: true
  67614. });
  67615. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  67616. set: function (wrap) {
  67617. if (this._textures) {
  67618. for (var i = 0; i < this._textures.length; i++) {
  67619. this._textures[i].wrapU = wrap;
  67620. }
  67621. }
  67622. },
  67623. enumerable: true,
  67624. configurable: true
  67625. });
  67626. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  67627. set: function (wrap) {
  67628. if (this._textures) {
  67629. for (var i = 0; i < this._textures.length; i++) {
  67630. this._textures[i].wrapV = wrap;
  67631. }
  67632. }
  67633. },
  67634. enumerable: true,
  67635. configurable: true
  67636. });
  67637. /** @hidden */
  67638. MultiRenderTarget.prototype._rebuild = function () {
  67639. this.releaseInternalTextures();
  67640. this._createInternalTextures();
  67641. for (var i = 0; i < this._internalTextures.length; i++) {
  67642. var texture = this._textures[i];
  67643. texture._texture = this._internalTextures[i];
  67644. }
  67645. // Keeps references to frame buffer and stencil/depth buffer
  67646. this._texture = this._internalTextures[0];
  67647. };
  67648. MultiRenderTarget.prototype._createInternalTextures = function () {
  67649. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  67650. };
  67651. MultiRenderTarget.prototype._createTextures = function () {
  67652. this._textures = [];
  67653. for (var i = 0; i < this._internalTextures.length; i++) {
  67654. var texture = new BABYLON.Texture(null, this.getScene());
  67655. texture._texture = this._internalTextures[i];
  67656. this._textures.push(texture);
  67657. }
  67658. // Keeps references to frame buffer and stencil/depth buffer
  67659. this._texture = this._internalTextures[0];
  67660. };
  67661. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  67662. get: function () {
  67663. return this._samples;
  67664. },
  67665. set: function (value) {
  67666. if (this._samples === value) {
  67667. return;
  67668. }
  67669. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  67670. },
  67671. enumerable: true,
  67672. configurable: true
  67673. });
  67674. MultiRenderTarget.prototype.resize = function (size) {
  67675. this.releaseInternalTextures();
  67676. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  67677. this._createInternalTextures();
  67678. };
  67679. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  67680. var _this = this;
  67681. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  67682. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  67683. });
  67684. };
  67685. MultiRenderTarget.prototype.dispose = function () {
  67686. this.releaseInternalTextures();
  67687. _super.prototype.dispose.call(this);
  67688. };
  67689. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  67690. if (!this._internalTextures) {
  67691. return;
  67692. }
  67693. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  67694. if (this._internalTextures[i] !== undefined) {
  67695. this._internalTextures[i].dispose();
  67696. this._internalTextures.splice(i, 1);
  67697. }
  67698. }
  67699. };
  67700. return MultiRenderTarget;
  67701. }(BABYLON.RenderTargetTexture));
  67702. BABYLON.MultiRenderTarget = MultiRenderTarget;
  67703. })(BABYLON || (BABYLON = {}));
  67704. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  67705. var BABYLON;
  67706. (function (BABYLON) {
  67707. var MirrorTexture = /** @class */ (function (_super) {
  67708. __extends(MirrorTexture, _super);
  67709. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  67710. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67711. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67712. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67713. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  67714. _this.scene = scene;
  67715. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  67716. _this._transformMatrix = BABYLON.Matrix.Zero();
  67717. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  67718. _this._adaptiveBlurKernel = 0;
  67719. _this._blurKernelX = 0;
  67720. _this._blurKernelY = 0;
  67721. _this._blurRatio = 1.0;
  67722. _this.ignoreCameraViewport = true;
  67723. _this._updateGammaSpace();
  67724. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  67725. _this._updateGammaSpace;
  67726. });
  67727. _this.onBeforeRenderObservable.add(function () {
  67728. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  67729. _this._savedViewMatrix = scene.getViewMatrix();
  67730. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  67731. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  67732. scene.clipPlane = _this.mirrorPlane;
  67733. scene.getEngine().cullBackFaces = false;
  67734. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  67735. });
  67736. _this.onAfterRenderObservable.add(function () {
  67737. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  67738. scene.getEngine().cullBackFaces = true;
  67739. scene._mirroredCameraPosition = null;
  67740. delete scene.clipPlane;
  67741. });
  67742. return _this;
  67743. }
  67744. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  67745. get: function () {
  67746. return this._blurRatio;
  67747. },
  67748. set: function (value) {
  67749. if (this._blurRatio === value) {
  67750. return;
  67751. }
  67752. this._blurRatio = value;
  67753. this._preparePostProcesses();
  67754. },
  67755. enumerable: true,
  67756. configurable: true
  67757. });
  67758. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  67759. set: function (value) {
  67760. this._adaptiveBlurKernel = value;
  67761. this._autoComputeBlurKernel();
  67762. },
  67763. enumerable: true,
  67764. configurable: true
  67765. });
  67766. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  67767. set: function (value) {
  67768. this.blurKernelX = value;
  67769. this.blurKernelY = value;
  67770. },
  67771. enumerable: true,
  67772. configurable: true
  67773. });
  67774. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  67775. get: function () {
  67776. return this._blurKernelX;
  67777. },
  67778. set: function (value) {
  67779. if (this._blurKernelX === value) {
  67780. return;
  67781. }
  67782. this._blurKernelX = value;
  67783. this._preparePostProcesses();
  67784. },
  67785. enumerable: true,
  67786. configurable: true
  67787. });
  67788. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  67789. get: function () {
  67790. return this._blurKernelY;
  67791. },
  67792. set: function (value) {
  67793. if (this._blurKernelY === value) {
  67794. return;
  67795. }
  67796. this._blurKernelY = value;
  67797. this._preparePostProcesses();
  67798. },
  67799. enumerable: true,
  67800. configurable: true
  67801. });
  67802. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  67803. var engine = this.getScene().getEngine();
  67804. var dw = this.getRenderWidth() / engine.getRenderWidth();
  67805. var dh = this.getRenderHeight() / engine.getRenderHeight();
  67806. this.blurKernelX = this._adaptiveBlurKernel * dw;
  67807. this.blurKernelY = this._adaptiveBlurKernel * dh;
  67808. };
  67809. MirrorTexture.prototype._onRatioRescale = function () {
  67810. if (this._sizeRatio) {
  67811. this.resize(this._initialSizeParameter);
  67812. if (!this._adaptiveBlurKernel) {
  67813. this._preparePostProcesses();
  67814. }
  67815. }
  67816. if (this._adaptiveBlurKernel) {
  67817. this._autoComputeBlurKernel();
  67818. }
  67819. };
  67820. MirrorTexture.prototype._updateGammaSpace = function () {
  67821. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  67822. };
  67823. MirrorTexture.prototype._preparePostProcesses = function () {
  67824. this.clearPostProcesses(true);
  67825. if (this._blurKernelX && this._blurKernelY) {
  67826. var engine = this.getScene().getEngine();
  67827. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67828. 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);
  67829. this._blurX.autoClear = false;
  67830. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  67831. this._blurX.inputTexture = this._texture;
  67832. }
  67833. else {
  67834. this._blurX.alwaysForcePOT = true;
  67835. }
  67836. 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);
  67837. this._blurY.autoClear = false;
  67838. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  67839. this.addPostProcess(this._blurX);
  67840. this.addPostProcess(this._blurY);
  67841. }
  67842. else {
  67843. if (this._blurY) {
  67844. this.removePostProcess(this._blurY);
  67845. this._blurY.dispose();
  67846. this._blurY = null;
  67847. }
  67848. if (this._blurX) {
  67849. this.removePostProcess(this._blurX);
  67850. this._blurX.dispose();
  67851. this._blurX = null;
  67852. }
  67853. }
  67854. };
  67855. MirrorTexture.prototype.clone = function () {
  67856. var scene = this.getScene();
  67857. if (!scene) {
  67858. return this;
  67859. }
  67860. var textureSize = this.getSize();
  67861. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  67862. // Base texture
  67863. newTexture.hasAlpha = this.hasAlpha;
  67864. newTexture.level = this.level;
  67865. // Mirror Texture
  67866. newTexture.mirrorPlane = this.mirrorPlane.clone();
  67867. if (this.renderList) {
  67868. newTexture.renderList = this.renderList.slice(0);
  67869. }
  67870. return newTexture;
  67871. };
  67872. MirrorTexture.prototype.serialize = function () {
  67873. if (!this.name) {
  67874. return null;
  67875. }
  67876. var serializationObject = _super.prototype.serialize.call(this);
  67877. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  67878. return serializationObject;
  67879. };
  67880. MirrorTexture.prototype.dispose = function () {
  67881. _super.prototype.dispose.call(this);
  67882. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  67883. };
  67884. return MirrorTexture;
  67885. }(BABYLON.RenderTargetTexture));
  67886. BABYLON.MirrorTexture = MirrorTexture;
  67887. })(BABYLON || (BABYLON = {}));
  67888. //# sourceMappingURL=babylon.mirrorTexture.js.map
  67889. var BABYLON;
  67890. (function (BABYLON) {
  67891. /**
  67892. * Creates a refraction texture used by refraction channel of the standard material.
  67893. * @param name the texture name
  67894. * @param size size of the underlying texture
  67895. * @param scene root scene
  67896. */
  67897. var RefractionTexture = /** @class */ (function (_super) {
  67898. __extends(RefractionTexture, _super);
  67899. function RefractionTexture(name, size, scene, generateMipMaps) {
  67900. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  67901. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  67902. _this.depth = 2.0;
  67903. _this.onBeforeRenderObservable.add(function () {
  67904. scene.clipPlane = _this.refractionPlane;
  67905. });
  67906. _this.onAfterRenderObservable.add(function () {
  67907. delete scene.clipPlane;
  67908. });
  67909. return _this;
  67910. }
  67911. RefractionTexture.prototype.clone = function () {
  67912. var scene = this.getScene();
  67913. if (!scene) {
  67914. return this;
  67915. }
  67916. var textureSize = this.getSize();
  67917. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  67918. // Base texture
  67919. newTexture.hasAlpha = this.hasAlpha;
  67920. newTexture.level = this.level;
  67921. // Refraction Texture
  67922. newTexture.refractionPlane = this.refractionPlane.clone();
  67923. if (this.renderList) {
  67924. newTexture.renderList = this.renderList.slice(0);
  67925. }
  67926. newTexture.depth = this.depth;
  67927. return newTexture;
  67928. };
  67929. RefractionTexture.prototype.serialize = function () {
  67930. if (!this.name) {
  67931. return null;
  67932. }
  67933. var serializationObject = _super.prototype.serialize.call(this);
  67934. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  67935. serializationObject.depth = this.depth;
  67936. return serializationObject;
  67937. };
  67938. return RefractionTexture;
  67939. }(BABYLON.RenderTargetTexture));
  67940. BABYLON.RefractionTexture = RefractionTexture;
  67941. })(BABYLON || (BABYLON = {}));
  67942. //# sourceMappingURL=babylon.refractionTexture.js.map
  67943. var BABYLON;
  67944. (function (BABYLON) {
  67945. /**
  67946. * A class extending {BABYLON.Texture} allowing drawing on a texture
  67947. * @see http://doc.babylonjs.com/how_to/dynamictexture
  67948. */
  67949. var DynamicTexture = /** @class */ (function (_super) {
  67950. __extends(DynamicTexture, _super);
  67951. /**
  67952. * Creates a {BABYLON.DynamicTexture}
  67953. * @param name defines the name of the texture
  67954. * @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
  67955. * @param scene defines the scene where you want the texture
  67956. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  67957. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  67958. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  67959. */
  67960. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  67961. if (scene === void 0) { scene = null; }
  67962. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67963. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67964. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  67965. _this.name = name;
  67966. _this._engine = _this.getScene().getEngine();
  67967. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67968. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67969. _this._generateMipMaps = generateMipMaps;
  67970. if (options.getContext) {
  67971. _this._canvas = options;
  67972. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67973. }
  67974. else {
  67975. _this._canvas = document.createElement("canvas");
  67976. if (options.width || options.width === 0) {
  67977. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67978. }
  67979. else {
  67980. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  67981. }
  67982. }
  67983. var textureSize = _this.getSize();
  67984. _this._canvas.width = textureSize.width;
  67985. _this._canvas.height = textureSize.height;
  67986. _this._context = _this._canvas.getContext("2d");
  67987. return _this;
  67988. }
  67989. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  67990. /**
  67991. * Gets the current state of canRescale
  67992. */
  67993. get: function () {
  67994. return true;
  67995. },
  67996. enumerable: true,
  67997. configurable: true
  67998. });
  67999. DynamicTexture.prototype._recreate = function (textureSize) {
  68000. this._canvas.width = textureSize.width;
  68001. this._canvas.height = textureSize.height;
  68002. this.releaseInternalTexture();
  68003. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  68004. };
  68005. /**
  68006. * Scales the texture
  68007. * @param ratio the scale factor to apply to both width and height
  68008. */
  68009. DynamicTexture.prototype.scale = function (ratio) {
  68010. var textureSize = this.getSize();
  68011. textureSize.width *= ratio;
  68012. textureSize.height *= ratio;
  68013. this._recreate(textureSize);
  68014. };
  68015. /**
  68016. * Resizes the texture
  68017. * @param width the new width
  68018. * @param height the new height
  68019. */
  68020. DynamicTexture.prototype.scaleTo = function (width, height) {
  68021. var textureSize = this.getSize();
  68022. textureSize.width = width;
  68023. textureSize.height = height;
  68024. this._recreate(textureSize);
  68025. };
  68026. /**
  68027. * Gets the context of the canvas used by the texture
  68028. * @returns the canvas context of the dynamic texture
  68029. */
  68030. DynamicTexture.prototype.getContext = function () {
  68031. return this._context;
  68032. };
  68033. /**
  68034. * Clears the texture
  68035. */
  68036. DynamicTexture.prototype.clear = function () {
  68037. var size = this.getSize();
  68038. this._context.fillRect(0, 0, size.width, size.height);
  68039. };
  68040. /**
  68041. * Updates the texture
  68042. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68043. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  68044. */
  68045. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  68046. if (premulAlpha === void 0) { premulAlpha = false; }
  68047. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  68048. };
  68049. /**
  68050. * Draws text onto the texture
  68051. * @param text defines the text to be drawn
  68052. * @param x defines the placement of the text from the left
  68053. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  68054. * @param font defines the font to be used with font-style, font-size, font-name
  68055. * @param color defines the color used for the text
  68056. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  68057. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68058. * @param update defines whether texture is immediately update (default is true)
  68059. */
  68060. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  68061. if (update === void 0) { update = true; }
  68062. var size = this.getSize();
  68063. if (clearColor) {
  68064. this._context.fillStyle = clearColor;
  68065. this._context.fillRect(0, 0, size.width, size.height);
  68066. }
  68067. this._context.font = font;
  68068. if (x === null || x === undefined) {
  68069. var textSize = this._context.measureText(text);
  68070. x = (size.width - textSize.width) / 2;
  68071. }
  68072. if (y === null || y === undefined) {
  68073. var fontSize = parseInt((font.replace(/\D/g, '')));
  68074. y = (size.height / 2) + (fontSize / 3.65);
  68075. }
  68076. this._context.fillStyle = color;
  68077. this._context.fillText(text, x, y);
  68078. if (update) {
  68079. this.update(invertY);
  68080. }
  68081. };
  68082. /**
  68083. * Clones the texture
  68084. * @returns the clone of the texture.
  68085. */
  68086. DynamicTexture.prototype.clone = function () {
  68087. var scene = this.getScene();
  68088. if (!scene) {
  68089. return this;
  68090. }
  68091. var textureSize = this.getSize();
  68092. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  68093. // Base texture
  68094. newTexture.hasAlpha = this.hasAlpha;
  68095. newTexture.level = this.level;
  68096. // Dynamic Texture
  68097. newTexture.wrapU = this.wrapU;
  68098. newTexture.wrapV = this.wrapV;
  68099. return newTexture;
  68100. };
  68101. /**
  68102. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  68103. * @returns a serialized dynamic texture object
  68104. */
  68105. DynamicTexture.prototype.serialize = function () {
  68106. var scene = this.getScene();
  68107. if (scene && !scene.isReady()) {
  68108. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  68109. }
  68110. var serializationObject = _super.prototype.serialize.call(this);
  68111. serializationObject.base64String = this._canvas.toDataURL();
  68112. serializationObject.invertY = this._invertY;
  68113. serializationObject.samplingMode = this.samplingMode;
  68114. return serializationObject;
  68115. };
  68116. /** @hidden */
  68117. DynamicTexture.prototype._rebuild = function () {
  68118. this.update();
  68119. };
  68120. return DynamicTexture;
  68121. }(BABYLON.Texture));
  68122. BABYLON.DynamicTexture = DynamicTexture;
  68123. })(BABYLON || (BABYLON = {}));
  68124. //# sourceMappingURL=babylon.dynamicTexture.js.map
  68125. var BABYLON;
  68126. (function (BABYLON) {
  68127. var VideoTexture = /** @class */ (function (_super) {
  68128. __extends(VideoTexture, _super);
  68129. /**
  68130. * Creates a video texture.
  68131. * Sample : https://doc.babylonjs.com/how_to/video_texture
  68132. * @param {string | null} name optional name, will detect from video source, if not defined
  68133. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  68134. * @param {BABYLON.Scene} scene is obviously the current scene.
  68135. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  68136. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  68137. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  68138. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  68139. */
  68140. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  68141. if (generateMipMaps === void 0) { generateMipMaps = false; }
  68142. if (invertY === void 0) { invertY = false; }
  68143. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68144. if (settings === void 0) { settings = {
  68145. autoPlay: true,
  68146. loop: true,
  68147. autoUpdateTexture: true,
  68148. }; }
  68149. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68150. _this._onUserActionRequestedObservable = null;
  68151. _this._stillImageCaptured = false;
  68152. _this._poster = false;
  68153. _this._createInternalTexture = function () {
  68154. if (_this._texture != null) {
  68155. if (_this._poster) {
  68156. _this._texture.dispose();
  68157. _this._poster = false;
  68158. }
  68159. else {
  68160. return;
  68161. }
  68162. }
  68163. if (!_this._engine.needPOTTextures ||
  68164. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  68165. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68166. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68167. }
  68168. else {
  68169. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68170. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68171. _this._generateMipMaps = false;
  68172. }
  68173. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  68174. if (!_this.video.autoplay) {
  68175. var oldHandler_1 = _this.video.onplaying;
  68176. var error_1 = false;
  68177. _this.video.onplaying = function () {
  68178. _this.video.onplaying = oldHandler_1;
  68179. _this._texture.isReady = true;
  68180. _this._updateInternalTexture();
  68181. if (!error_1) {
  68182. _this.video.pause();
  68183. }
  68184. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68185. _this.onLoadObservable.notifyObservers(_this);
  68186. }
  68187. };
  68188. var playing = _this.video.play();
  68189. if (playing) {
  68190. playing.then(function () {
  68191. // Everything is good.
  68192. })
  68193. .catch(function () {
  68194. error_1 = true;
  68195. // On Chrome for instance, new policies might prevent playing without user interaction.
  68196. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  68197. _this._onUserActionRequestedObservable.notifyObservers(_this);
  68198. }
  68199. });
  68200. }
  68201. else {
  68202. _this.video.onplaying = oldHandler_1;
  68203. _this._texture.isReady = true;
  68204. _this._updateInternalTexture();
  68205. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68206. _this.onLoadObservable.notifyObservers(_this);
  68207. }
  68208. }
  68209. }
  68210. else {
  68211. _this._texture.isReady = true;
  68212. _this._updateInternalTexture();
  68213. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68214. _this.onLoadObservable.notifyObservers(_this);
  68215. }
  68216. }
  68217. };
  68218. _this.reset = function () {
  68219. if (_this._texture == null) {
  68220. return;
  68221. }
  68222. if (!_this._poster) {
  68223. _this._texture.dispose();
  68224. _this._texture = null;
  68225. }
  68226. };
  68227. _this._updateInternalTexture = function (e) {
  68228. if (_this._texture == null || !_this._texture.isReady) {
  68229. return;
  68230. }
  68231. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  68232. return;
  68233. }
  68234. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  68235. };
  68236. _this._engine = _this.getScene().getEngine();
  68237. _this._generateMipMaps = generateMipMaps;
  68238. _this._samplingMode = samplingMode;
  68239. _this.autoUpdateTexture = settings.autoUpdateTexture;
  68240. _this.name = name || _this._getName(src);
  68241. _this.video = _this._getVideo(src);
  68242. if (settings.poster) {
  68243. _this.video.poster = settings.poster;
  68244. }
  68245. if (settings.autoPlay !== undefined) {
  68246. _this.video.autoplay = settings.autoPlay;
  68247. }
  68248. if (settings.loop !== undefined) {
  68249. _this.video.loop = settings.loop;
  68250. }
  68251. _this.video.setAttribute("playsinline", "");
  68252. _this.video.addEventListener("canplay", _this._createInternalTexture);
  68253. _this.video.addEventListener("paused", _this._updateInternalTexture);
  68254. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  68255. _this.video.addEventListener("emptied", _this.reset);
  68256. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  68257. _this._createInternalTexture();
  68258. }
  68259. if (settings.poster) {
  68260. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  68261. _this._poster = true;
  68262. }
  68263. return _this;
  68264. }
  68265. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  68266. get: function () {
  68267. if (!this._onUserActionRequestedObservable) {
  68268. this._onUserActionRequestedObservable = new BABYLON.Observable();
  68269. }
  68270. return this._onUserActionRequestedObservable;
  68271. },
  68272. enumerable: true,
  68273. configurable: true
  68274. });
  68275. VideoTexture.prototype._getName = function (src) {
  68276. if (src instanceof HTMLVideoElement) {
  68277. return src.currentSrc;
  68278. }
  68279. if (typeof src === "object") {
  68280. return src.toString();
  68281. }
  68282. return src;
  68283. };
  68284. ;
  68285. VideoTexture.prototype._getVideo = function (src) {
  68286. if (src instanceof HTMLVideoElement) {
  68287. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  68288. return src;
  68289. }
  68290. var video = document.createElement("video");
  68291. if (typeof src === "string") {
  68292. BABYLON.Tools.SetCorsBehavior(src, video);
  68293. video.src = src;
  68294. }
  68295. else {
  68296. BABYLON.Tools.SetCorsBehavior(src[0], video);
  68297. src.forEach(function (url) {
  68298. var source = document.createElement("source");
  68299. source.src = url;
  68300. video.appendChild(source);
  68301. });
  68302. }
  68303. return video;
  68304. };
  68305. ;
  68306. /**
  68307. * @hidden Internal method to initiate `update`.
  68308. */
  68309. VideoTexture.prototype._rebuild = function () {
  68310. this.update();
  68311. };
  68312. /**
  68313. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  68314. */
  68315. VideoTexture.prototype.update = function () {
  68316. if (!this.autoUpdateTexture) {
  68317. // Expecting user to call `updateTexture` manually
  68318. return;
  68319. }
  68320. this.updateTexture(true);
  68321. };
  68322. /**
  68323. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  68324. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  68325. */
  68326. VideoTexture.prototype.updateTexture = function (isVisible) {
  68327. if (!isVisible) {
  68328. return;
  68329. }
  68330. if (this.video.paused && this._stillImageCaptured) {
  68331. return;
  68332. }
  68333. this._stillImageCaptured = true;
  68334. this._updateInternalTexture();
  68335. };
  68336. /**
  68337. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  68338. * @param url New url.
  68339. */
  68340. VideoTexture.prototype.updateURL = function (url) {
  68341. this.video.src = url;
  68342. };
  68343. VideoTexture.prototype.dispose = function () {
  68344. _super.prototype.dispose.call(this);
  68345. if (this._onUserActionRequestedObservable) {
  68346. this._onUserActionRequestedObservable.clear();
  68347. this._onUserActionRequestedObservable = null;
  68348. }
  68349. this.video.removeEventListener("canplay", this._createInternalTexture);
  68350. this.video.removeEventListener("paused", this._updateInternalTexture);
  68351. this.video.removeEventListener("seeked", this._updateInternalTexture);
  68352. this.video.removeEventListener("emptied", this.reset);
  68353. this.video.pause();
  68354. };
  68355. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  68356. var video = document.createElement("video");
  68357. video.setAttribute('autoplay', '');
  68358. video.setAttribute('muted', '');
  68359. video.setAttribute('playsinline', '');
  68360. var constraintsDeviceId;
  68361. if (constraints && constraints.deviceId) {
  68362. constraintsDeviceId = {
  68363. exact: constraints.deviceId,
  68364. };
  68365. }
  68366. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  68367. if (navigator.mediaDevices) {
  68368. navigator.mediaDevices.getUserMedia({ video: constraints })
  68369. .then(function (stream) {
  68370. if (video.mozSrcObject !== undefined) {
  68371. // hack for Firefox < 19
  68372. video.mozSrcObject = stream;
  68373. }
  68374. else {
  68375. video.srcObject = stream;
  68376. }
  68377. var onPlaying = function () {
  68378. if (onReady) {
  68379. onReady(new VideoTexture("video", video, scene, true, true));
  68380. }
  68381. video.removeEventListener("playing", onPlaying);
  68382. };
  68383. video.addEventListener("playing", onPlaying);
  68384. video.play();
  68385. })
  68386. .catch(function (err) {
  68387. BABYLON.Tools.Error(err.name);
  68388. });
  68389. }
  68390. else {
  68391. navigator.getUserMedia =
  68392. navigator.getUserMedia ||
  68393. navigator.webkitGetUserMedia ||
  68394. navigator.mozGetUserMedia ||
  68395. navigator.msGetUserMedia;
  68396. if (navigator.getUserMedia) {
  68397. navigator.getUserMedia({
  68398. video: {
  68399. deviceId: constraintsDeviceId,
  68400. width: {
  68401. min: (constraints && constraints.minWidth) || 256,
  68402. max: (constraints && constraints.maxWidth) || 640,
  68403. },
  68404. height: {
  68405. min: (constraints && constraints.minHeight) || 256,
  68406. max: (constraints && constraints.maxHeight) || 480,
  68407. },
  68408. },
  68409. }, function (stream) {
  68410. if (video.mozSrcObject !== undefined) {
  68411. // hack for Firefox < 19
  68412. video.mozSrcObject = stream;
  68413. }
  68414. else {
  68415. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  68416. }
  68417. video.play();
  68418. if (onReady) {
  68419. onReady(new VideoTexture("video", video, scene, true, true));
  68420. }
  68421. }, function (e) {
  68422. BABYLON.Tools.Error(e.name);
  68423. });
  68424. }
  68425. }
  68426. };
  68427. return VideoTexture;
  68428. }(BABYLON.Texture));
  68429. BABYLON.VideoTexture = VideoTexture;
  68430. })(BABYLON || (BABYLON = {}));
  68431. //# sourceMappingURL=babylon.videoTexture.js.map
  68432. var BABYLON;
  68433. (function (BABYLON) {
  68434. var RawTexture = /** @class */ (function (_super) {
  68435. __extends(RawTexture, _super);
  68436. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  68437. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68438. if (invertY === void 0) { invertY = false; }
  68439. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68440. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68441. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68442. _this.format = format;
  68443. _this._engine = scene.getEngine();
  68444. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  68445. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68446. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68447. return _this;
  68448. }
  68449. RawTexture.prototype.update = function (data) {
  68450. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68451. };
  68452. // Statics
  68453. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68454. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68455. if (invertY === void 0) { invertY = false; }
  68456. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68457. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  68458. };
  68459. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68460. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68461. if (invertY === void 0) { invertY = false; }
  68462. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68463. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68464. };
  68465. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68466. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68467. if (invertY === void 0) { invertY = false; }
  68468. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68469. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68470. };
  68471. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68472. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68473. if (invertY === void 0) { invertY = false; }
  68474. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68475. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68476. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  68477. };
  68478. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68479. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68480. if (invertY === void 0) { invertY = false; }
  68481. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68482. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68483. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  68484. };
  68485. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68486. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68487. if (invertY === void 0) { invertY = false; }
  68488. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68489. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68490. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  68491. };
  68492. return RawTexture;
  68493. }(BABYLON.Texture));
  68494. BABYLON.RawTexture = RawTexture;
  68495. })(BABYLON || (BABYLON = {}));
  68496. //# sourceMappingURL=babylon.rawTexture.js.map
  68497. var BABYLON;
  68498. (function (BABYLON) {
  68499. /**
  68500. * Class used to store 3D textures containing user data
  68501. */
  68502. var RawTexture3D = /** @class */ (function (_super) {
  68503. __extends(RawTexture3D, _super);
  68504. /**
  68505. * Create a new RawTexture3D
  68506. * @param data defines the data of the texture
  68507. * @param width defines the width of the texture
  68508. * @param height defines the height of the texture
  68509. * @param depth defines the depth of the texture
  68510. * @param format defines the texture format to use
  68511. * @param scene defines the hosting scene
  68512. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  68513. * @param invertY defines if texture must be stored with Y axis inverted
  68514. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  68515. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  68516. */
  68517. function RawTexture3D(data, width, height, depth,
  68518. /** Gets or sets the texture format to use */
  68519. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  68520. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68521. if (invertY === void 0) { invertY = false; }
  68522. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68523. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68524. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68525. _this.format = format;
  68526. _this._engine = scene.getEngine();
  68527. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  68528. _this.is3D = true;
  68529. return _this;
  68530. }
  68531. /**
  68532. * Update the texture with new data
  68533. * @param data defines the data to store in the texture
  68534. */
  68535. RawTexture3D.prototype.update = function (data) {
  68536. if (!this._texture) {
  68537. return;
  68538. }
  68539. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68540. };
  68541. return RawTexture3D;
  68542. }(BABYLON.Texture));
  68543. BABYLON.RawTexture3D = RawTexture3D;
  68544. })(BABYLON || (BABYLON = {}));
  68545. //# sourceMappingURL=babylon.rawTexture3D.js.map
  68546. var BABYLON;
  68547. (function (BABYLON) {
  68548. /**
  68549. * PostProcessManager is used to manage one or more post processes or post process pipelines
  68550. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68551. */
  68552. var PostProcessManager = /** @class */ (function () {
  68553. /**
  68554. * Creates a new instance PostProcess
  68555. * @param scene The scene that the post process is associated with.
  68556. */
  68557. function PostProcessManager(scene) {
  68558. this._vertexBuffers = {};
  68559. this._scene = scene;
  68560. }
  68561. PostProcessManager.prototype._prepareBuffers = function () {
  68562. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  68563. return;
  68564. }
  68565. // VBO
  68566. var vertices = [];
  68567. vertices.push(1, 1);
  68568. vertices.push(-1, 1);
  68569. vertices.push(-1, -1);
  68570. vertices.push(1, -1);
  68571. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68572. this._buildIndexBuffer();
  68573. };
  68574. PostProcessManager.prototype._buildIndexBuffer = function () {
  68575. // Indices
  68576. var indices = [];
  68577. indices.push(0);
  68578. indices.push(1);
  68579. indices.push(2);
  68580. indices.push(0);
  68581. indices.push(2);
  68582. indices.push(3);
  68583. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  68584. };
  68585. /**
  68586. * Rebuilds the vertex buffers of the manager.
  68587. * @hidden
  68588. */
  68589. PostProcessManager.prototype._rebuild = function () {
  68590. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68591. if (!vb) {
  68592. return;
  68593. }
  68594. vb._rebuild();
  68595. this._buildIndexBuffer();
  68596. };
  68597. // Methods
  68598. /**
  68599. * Prepares a frame to be run through a post process.
  68600. * @param sourceTexture The input texture to the post procesess. (default: null)
  68601. * @param postProcesses An array of post processes to be run. (default: null)
  68602. * @returns True if the post processes were able to be run.
  68603. * @hidden
  68604. */
  68605. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  68606. if (sourceTexture === void 0) { sourceTexture = null; }
  68607. if (postProcesses === void 0) { postProcesses = null; }
  68608. var camera = this._scene.activeCamera;
  68609. if (!camera) {
  68610. return false;
  68611. }
  68612. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  68613. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  68614. return false;
  68615. }
  68616. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  68617. return true;
  68618. };
  68619. /**
  68620. * Manually render a set of post processes to a texture.
  68621. * @param postProcesses An array of post processes to be run.
  68622. * @param targetTexture The target texture to render to.
  68623. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  68624. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  68625. * @param lodLevel defines which lod of the texture to render to
  68626. */
  68627. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  68628. if (targetTexture === void 0) { targetTexture = null; }
  68629. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  68630. if (faceIndex === void 0) { faceIndex = 0; }
  68631. if (lodLevel === void 0) { lodLevel = 0; }
  68632. var engine = this._scene.getEngine();
  68633. for (var index = 0; index < postProcesses.length; index++) {
  68634. if (index < postProcesses.length - 1) {
  68635. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  68636. }
  68637. else {
  68638. if (targetTexture) {
  68639. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  68640. }
  68641. else {
  68642. engine.restoreDefaultFramebuffer();
  68643. }
  68644. }
  68645. var pp = postProcesses[index];
  68646. var effect = pp.apply();
  68647. if (effect) {
  68648. pp.onBeforeRenderObservable.notifyObservers(effect);
  68649. // VBOs
  68650. this._prepareBuffers();
  68651. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  68652. // Draw order
  68653. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68654. pp.onAfterRenderObservable.notifyObservers(effect);
  68655. }
  68656. }
  68657. // Restore depth buffer
  68658. engine.setDepthBuffer(true);
  68659. engine.setDepthWrite(true);
  68660. };
  68661. /**
  68662. * Finalize the result of the output of the postprocesses.
  68663. * @param doNotPresent If true the result will not be displayed to the screen.
  68664. * @param targetTexture The target texture to render to.
  68665. * @param faceIndex The index of the face to bind the target texture to.
  68666. * @param postProcesses The array of post processes to render.
  68667. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  68668. * @hidden
  68669. */
  68670. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  68671. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  68672. var camera = this._scene.activeCamera;
  68673. if (!camera) {
  68674. return;
  68675. }
  68676. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  68677. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  68678. return;
  68679. }
  68680. var engine = this._scene.getEngine();
  68681. for (var index = 0, len = postProcesses.length; index < len; index++) {
  68682. var pp = postProcesses[index];
  68683. if (index < len - 1) {
  68684. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  68685. }
  68686. else {
  68687. if (targetTexture) {
  68688. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  68689. pp._outputTexture = targetTexture;
  68690. }
  68691. else {
  68692. engine.restoreDefaultFramebuffer();
  68693. pp._outputTexture = null;
  68694. }
  68695. }
  68696. if (doNotPresent) {
  68697. break;
  68698. }
  68699. var effect = pp.apply();
  68700. if (effect) {
  68701. pp.onBeforeRenderObservable.notifyObservers(effect);
  68702. // VBOs
  68703. this._prepareBuffers();
  68704. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  68705. // Draw order
  68706. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68707. pp.onAfterRenderObservable.notifyObservers(effect);
  68708. }
  68709. }
  68710. // Restore states
  68711. engine.setDepthBuffer(true);
  68712. engine.setDepthWrite(true);
  68713. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68714. };
  68715. /**
  68716. * Disposes of the post process manager.
  68717. */
  68718. PostProcessManager.prototype.dispose = function () {
  68719. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68720. if (buffer) {
  68721. buffer.dispose();
  68722. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68723. }
  68724. if (this._indexBuffer) {
  68725. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68726. this._indexBuffer = null;
  68727. }
  68728. };
  68729. return PostProcessManager;
  68730. }());
  68731. BABYLON.PostProcessManager = PostProcessManager;
  68732. })(BABYLON || (BABYLON = {}));
  68733. //# sourceMappingURL=babylon.postProcessManager.js.map
  68734. var BABYLON;
  68735. (function (BABYLON) {
  68736. /**
  68737. * PostProcess can be used to apply a shader to a texture after it has been rendered
  68738. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68739. */
  68740. var PostProcess = /** @class */ (function () {
  68741. /**
  68742. * Creates a new instance PostProcess
  68743. * @param name The name of the PostProcess.
  68744. * @param fragmentUrl The url of the fragment shader to be used.
  68745. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  68746. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  68747. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68748. * @param camera The camera to apply the render pass to.
  68749. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68750. * @param engine The engine which the post process will be applied. (default: current engine)
  68751. * @param reusable If the post process can be reused on the same frame. (default: false)
  68752. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  68753. * @param textureType Type of textures used when performing the post process. (default: 0)
  68754. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  68755. * @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
  68756. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  68757. */
  68758. function PostProcess(
  68759. /** Name of the PostProcess. */
  68760. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  68761. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  68762. if (defines === void 0) { defines = null; }
  68763. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68764. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  68765. if (blockCompilation === void 0) { blockCompilation = false; }
  68766. this.name = name;
  68767. /**
  68768. * Width of the texture to apply the post process on
  68769. */
  68770. this.width = -1;
  68771. /**
  68772. * Height of the texture to apply the post process on
  68773. */
  68774. this.height = -1;
  68775. /**
  68776. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  68777. * @hidden
  68778. */
  68779. this._outputTexture = null;
  68780. /**
  68781. * If the buffer needs to be cleared before applying the post process. (default: true)
  68782. * Should be set to false if shader will overwrite all previous pixels.
  68783. */
  68784. this.autoClear = true;
  68785. /**
  68786. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  68787. */
  68788. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  68789. /**
  68790. * Animations to be used for the post processing
  68791. */
  68792. this.animations = new Array();
  68793. /**
  68794. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  68795. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  68796. */
  68797. this.enablePixelPerfectMode = false;
  68798. /**
  68799. * Force the postprocess to be applied without taking in account viewport
  68800. */
  68801. this.forceFullscreenViewport = true;
  68802. /**
  68803. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  68804. *
  68805. * | Value | Type | Description |
  68806. * | ----- | ----------------------------------- | ----------- |
  68807. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  68808. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  68809. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  68810. *
  68811. */
  68812. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  68813. /**
  68814. * Force textures to be a power of two (default: false)
  68815. */
  68816. this.alwaysForcePOT = false;
  68817. this._samples = 1;
  68818. /**
  68819. * Modify the scale of the post process to be the same as the viewport (default: false)
  68820. */
  68821. this.adaptScaleToCurrentViewport = false;
  68822. this._reusable = false;
  68823. /**
  68824. * Smart array of input and output textures for the post process.
  68825. * @hidden
  68826. */
  68827. this._textures = new BABYLON.SmartArray(2);
  68828. /**
  68829. * The index in _textures that corresponds to the output texture.
  68830. * @hidden
  68831. */
  68832. this._currentRenderTextureInd = 0;
  68833. this._scaleRatio = new BABYLON.Vector2(1, 1);
  68834. this._texelSize = BABYLON.Vector2.Zero();
  68835. // Events
  68836. /**
  68837. * An event triggered when the postprocess is activated.
  68838. */
  68839. this.onActivateObservable = new BABYLON.Observable();
  68840. /**
  68841. * An event triggered when the postprocess changes its size.
  68842. */
  68843. this.onSizeChangedObservable = new BABYLON.Observable();
  68844. /**
  68845. * An event triggered when the postprocess applies its effect.
  68846. */
  68847. this.onApplyObservable = new BABYLON.Observable();
  68848. /**
  68849. * An event triggered before rendering the postprocess
  68850. */
  68851. this.onBeforeRenderObservable = new BABYLON.Observable();
  68852. /**
  68853. * An event triggered after rendering the postprocess
  68854. */
  68855. this.onAfterRenderObservable = new BABYLON.Observable();
  68856. if (camera != null) {
  68857. this._camera = camera;
  68858. this._scene = camera.getScene();
  68859. camera.attachPostProcess(this);
  68860. this._engine = this._scene.getEngine();
  68861. this._scene.postProcesses.push(this);
  68862. }
  68863. else if (engine) {
  68864. this._engine = engine;
  68865. this._engine.postProcesses.push(this);
  68866. }
  68867. this._options = options;
  68868. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  68869. this._reusable = reusable || false;
  68870. this._textureType = textureType;
  68871. this._samplers = samplers || [];
  68872. this._samplers.push("textureSampler");
  68873. this._fragmentUrl = fragmentUrl;
  68874. this._vertexUrl = vertexUrl;
  68875. this._parameters = parameters || [];
  68876. this._parameters.push("scale");
  68877. this._indexParameters = indexParameters;
  68878. if (!blockCompilation) {
  68879. this.updateEffect(defines);
  68880. }
  68881. }
  68882. Object.defineProperty(PostProcess.prototype, "samples", {
  68883. /**
  68884. * Number of sample textures (default: 1)
  68885. */
  68886. get: function () {
  68887. return this._samples;
  68888. },
  68889. set: function (n) {
  68890. var _this = this;
  68891. this._samples = n;
  68892. this._textures.forEach(function (texture) {
  68893. if (texture.samples !== _this._samples) {
  68894. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  68895. }
  68896. });
  68897. },
  68898. enumerable: true,
  68899. configurable: true
  68900. });
  68901. Object.defineProperty(PostProcess.prototype, "onActivate", {
  68902. /**
  68903. * A function that is added to the onActivateObservable
  68904. */
  68905. set: function (callback) {
  68906. if (this._onActivateObserver) {
  68907. this.onActivateObservable.remove(this._onActivateObserver);
  68908. }
  68909. if (callback) {
  68910. this._onActivateObserver = this.onActivateObservable.add(callback);
  68911. }
  68912. },
  68913. enumerable: true,
  68914. configurable: true
  68915. });
  68916. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  68917. /**
  68918. * A function that is added to the onSizeChangedObservable
  68919. */
  68920. set: function (callback) {
  68921. if (this._onSizeChangedObserver) {
  68922. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  68923. }
  68924. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  68925. },
  68926. enumerable: true,
  68927. configurable: true
  68928. });
  68929. Object.defineProperty(PostProcess.prototype, "onApply", {
  68930. /**
  68931. * A function that is added to the onApplyObservable
  68932. */
  68933. set: function (callback) {
  68934. if (this._onApplyObserver) {
  68935. this.onApplyObservable.remove(this._onApplyObserver);
  68936. }
  68937. this._onApplyObserver = this.onApplyObservable.add(callback);
  68938. },
  68939. enumerable: true,
  68940. configurable: true
  68941. });
  68942. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  68943. /**
  68944. * A function that is added to the onBeforeRenderObservable
  68945. */
  68946. set: function (callback) {
  68947. if (this._onBeforeRenderObserver) {
  68948. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  68949. }
  68950. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  68951. },
  68952. enumerable: true,
  68953. configurable: true
  68954. });
  68955. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  68956. /**
  68957. * A function that is added to the onAfterRenderObservable
  68958. */
  68959. set: function (callback) {
  68960. if (this._onAfterRenderObserver) {
  68961. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  68962. }
  68963. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  68964. },
  68965. enumerable: true,
  68966. configurable: true
  68967. });
  68968. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  68969. /**
  68970. * 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
  68971. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  68972. */
  68973. get: function () {
  68974. return this._textures.data[this._currentRenderTextureInd];
  68975. },
  68976. set: function (value) {
  68977. this._forcedOutputTexture = value;
  68978. },
  68979. enumerable: true,
  68980. configurable: true
  68981. });
  68982. /**
  68983. * Gets the camera which post process is applied to.
  68984. * @returns The camera the post process is applied to.
  68985. */
  68986. PostProcess.prototype.getCamera = function () {
  68987. return this._camera;
  68988. };
  68989. Object.defineProperty(PostProcess.prototype, "texelSize", {
  68990. /**
  68991. * Gets the texel size of the postprocess.
  68992. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  68993. */
  68994. get: function () {
  68995. if (this._shareOutputWithPostProcess) {
  68996. return this._shareOutputWithPostProcess.texelSize;
  68997. }
  68998. if (this._forcedOutputTexture) {
  68999. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  69000. }
  69001. return this._texelSize;
  69002. },
  69003. enumerable: true,
  69004. configurable: true
  69005. });
  69006. /**
  69007. * Gets the engine which this post process belongs to.
  69008. * @returns The engine the post process was enabled with.
  69009. */
  69010. PostProcess.prototype.getEngine = function () {
  69011. return this._engine;
  69012. };
  69013. /**
  69014. * The effect that is created when initializing the post process.
  69015. * @returns The created effect corrisponding the the postprocess.
  69016. */
  69017. PostProcess.prototype.getEffect = function () {
  69018. return this._effect;
  69019. };
  69020. /**
  69021. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  69022. * @param postProcess The post process to share the output with.
  69023. * @returns This post process.
  69024. */
  69025. PostProcess.prototype.shareOutputWith = function (postProcess) {
  69026. this._disposeTextures();
  69027. this._shareOutputWithPostProcess = postProcess;
  69028. return this;
  69029. };
  69030. /**
  69031. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  69032. * This should be called if the post process that shares output with this post process is disabled/disposed.
  69033. */
  69034. PostProcess.prototype.useOwnOutput = function () {
  69035. if (this._textures.length == 0) {
  69036. this._textures = new BABYLON.SmartArray(2);
  69037. }
  69038. this._shareOutputWithPostProcess = null;
  69039. };
  69040. /**
  69041. * Updates the effect with the current post process compile time values and recompiles the shader.
  69042. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69043. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69044. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69045. * @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
  69046. * @param onCompiled Called when the shader has been compiled.
  69047. * @param onError Called if there is an error when compiling a shader.
  69048. */
  69049. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69050. if (defines === void 0) { defines = null; }
  69051. if (uniforms === void 0) { uniforms = null; }
  69052. if (samplers === void 0) { samplers = null; }
  69053. 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);
  69054. };
  69055. /**
  69056. * The post process is reusable if it can be used multiple times within one frame.
  69057. * @returns If the post process is reusable
  69058. */
  69059. PostProcess.prototype.isReusable = function () {
  69060. return this._reusable;
  69061. };
  69062. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  69063. PostProcess.prototype.markTextureDirty = function () {
  69064. this.width = -1;
  69065. };
  69066. /**
  69067. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  69068. * 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.
  69069. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  69070. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  69071. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  69072. * @returns The target texture that was bound to be written to.
  69073. */
  69074. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  69075. var _this = this;
  69076. if (sourceTexture === void 0) { sourceTexture = null; }
  69077. camera = camera || this._camera;
  69078. var scene = camera.getScene();
  69079. var engine = scene.getEngine();
  69080. var maxSize = engine.getCaps().maxTextureSize;
  69081. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  69082. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  69083. // 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
  69084. var webVRCamera = camera.parent;
  69085. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  69086. requiredWidth /= 2;
  69087. }
  69088. var desiredWidth = (this._options.width || requiredWidth);
  69089. var desiredHeight = this._options.height || requiredHeight;
  69090. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  69091. if (this.adaptScaleToCurrentViewport) {
  69092. var currentViewport = engine.currentViewport;
  69093. if (currentViewport) {
  69094. desiredWidth *= currentViewport.width;
  69095. desiredHeight *= currentViewport.height;
  69096. }
  69097. }
  69098. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  69099. if (!this._options.width) {
  69100. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  69101. }
  69102. if (!this._options.height) {
  69103. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  69104. }
  69105. }
  69106. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  69107. if (this._textures.length > 0) {
  69108. for (var i = 0; i < this._textures.length; i++) {
  69109. this._engine._releaseTexture(this._textures.data[i]);
  69110. }
  69111. this._textures.reset();
  69112. }
  69113. this.width = desiredWidth;
  69114. this.height = desiredHeight;
  69115. var textureSize = { width: this.width, height: this.height };
  69116. var textureOptions = {
  69117. generateMipMaps: false,
  69118. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  69119. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  69120. samplingMode: this.renderTargetSamplingMode,
  69121. type: this._textureType
  69122. };
  69123. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69124. if (this._reusable) {
  69125. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69126. }
  69127. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  69128. this.onSizeChangedObservable.notifyObservers(this);
  69129. }
  69130. this._textures.forEach(function (texture) {
  69131. if (texture.samples !== _this.samples) {
  69132. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  69133. }
  69134. });
  69135. }
  69136. var target;
  69137. if (this._shareOutputWithPostProcess) {
  69138. target = this._shareOutputWithPostProcess.inputTexture;
  69139. }
  69140. else if (this._forcedOutputTexture) {
  69141. target = this._forcedOutputTexture;
  69142. this.width = this._forcedOutputTexture.width;
  69143. this.height = this._forcedOutputTexture.height;
  69144. }
  69145. else {
  69146. target = this.inputTexture;
  69147. }
  69148. // Bind the input of this post process to be used as the output of the previous post process.
  69149. if (this.enablePixelPerfectMode) {
  69150. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  69151. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  69152. }
  69153. else {
  69154. this._scaleRatio.copyFromFloats(1, 1);
  69155. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  69156. }
  69157. this.onActivateObservable.notifyObservers(camera);
  69158. // Clear
  69159. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  69160. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  69161. }
  69162. if (this._reusable) {
  69163. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  69164. }
  69165. return target;
  69166. };
  69167. Object.defineProperty(PostProcess.prototype, "isSupported", {
  69168. /**
  69169. * If the post process is supported.
  69170. */
  69171. get: function () {
  69172. return this._effect.isSupported;
  69173. },
  69174. enumerable: true,
  69175. configurable: true
  69176. });
  69177. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  69178. /**
  69179. * The aspect ratio of the output texture.
  69180. */
  69181. get: function () {
  69182. if (this._shareOutputWithPostProcess) {
  69183. return this._shareOutputWithPostProcess.aspectRatio;
  69184. }
  69185. if (this._forcedOutputTexture) {
  69186. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  69187. }
  69188. return this.width / this.height;
  69189. },
  69190. enumerable: true,
  69191. configurable: true
  69192. });
  69193. /**
  69194. * Get a value indicating if the post-process is ready to be used
  69195. * @returns true if the post-process is ready (shader is compiled)
  69196. */
  69197. PostProcess.prototype.isReady = function () {
  69198. return this._effect && this._effect.isReady();
  69199. };
  69200. /**
  69201. * Binds all textures and uniforms to the shader, this will be run on every pass.
  69202. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  69203. */
  69204. PostProcess.prototype.apply = function () {
  69205. // Check
  69206. if (!this._effect || !this._effect.isReady())
  69207. return null;
  69208. // States
  69209. this._engine.enableEffect(this._effect);
  69210. this._engine.setState(false);
  69211. this._engine.setDepthBuffer(false);
  69212. this._engine.setDepthWrite(false);
  69213. // Alpha
  69214. this._engine.setAlphaMode(this.alphaMode);
  69215. if (this.alphaConstants) {
  69216. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  69217. }
  69218. // Bind the output texture of the preivous post process as the input to this post process.
  69219. var source;
  69220. if (this._shareOutputWithPostProcess) {
  69221. source = this._shareOutputWithPostProcess.inputTexture;
  69222. }
  69223. else if (this._forcedOutputTexture) {
  69224. source = this._forcedOutputTexture;
  69225. }
  69226. else {
  69227. source = this.inputTexture;
  69228. }
  69229. this._effect._bindTexture("textureSampler", source);
  69230. // Parameters
  69231. this._effect.setVector2("scale", this._scaleRatio);
  69232. this.onApplyObservable.notifyObservers(this._effect);
  69233. return this._effect;
  69234. };
  69235. PostProcess.prototype._disposeTextures = function () {
  69236. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  69237. return;
  69238. }
  69239. if (this._textures.length > 0) {
  69240. for (var i = 0; i < this._textures.length; i++) {
  69241. this._engine._releaseTexture(this._textures.data[i]);
  69242. }
  69243. }
  69244. this._textures.dispose();
  69245. };
  69246. /**
  69247. * Disposes the post process.
  69248. * @param camera The camera to dispose the post process on.
  69249. */
  69250. PostProcess.prototype.dispose = function (camera) {
  69251. camera = camera || this._camera;
  69252. this._disposeTextures();
  69253. if (this._scene) {
  69254. var index_1 = this._scene.postProcesses.indexOf(this);
  69255. if (index_1 !== -1) {
  69256. this._scene.postProcesses.splice(index_1, 1);
  69257. }
  69258. }
  69259. else {
  69260. var index_2 = this._engine.postProcesses.indexOf(this);
  69261. if (index_2 !== -1) {
  69262. this._engine.postProcesses.splice(index_2, 1);
  69263. }
  69264. }
  69265. if (!camera) {
  69266. return;
  69267. }
  69268. camera.detachPostProcess(this);
  69269. var index = camera._postProcesses.indexOf(this);
  69270. if (index === 0 && camera._postProcesses.length > 0) {
  69271. var firstPostProcess = this._camera._getFirstPostProcess();
  69272. if (firstPostProcess) {
  69273. firstPostProcess.markTextureDirty();
  69274. }
  69275. }
  69276. this.onActivateObservable.clear();
  69277. this.onAfterRenderObservable.clear();
  69278. this.onApplyObservable.clear();
  69279. this.onBeforeRenderObservable.clear();
  69280. this.onSizeChangedObservable.clear();
  69281. };
  69282. return PostProcess;
  69283. }());
  69284. BABYLON.PostProcess = PostProcess;
  69285. })(BABYLON || (BABYLON = {}));
  69286. //# sourceMappingURL=babylon.postProcess.js.map
  69287. var BABYLON;
  69288. (function (BABYLON) {
  69289. var PassPostProcess = /** @class */ (function (_super) {
  69290. __extends(PassPostProcess, _super);
  69291. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69292. if (camera === void 0) { camera = null; }
  69293. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69294. if (blockCompilation === void 0) { blockCompilation = false; }
  69295. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  69296. }
  69297. return PassPostProcess;
  69298. }(BABYLON.PostProcess));
  69299. BABYLON.PassPostProcess = PassPostProcess;
  69300. })(BABYLON || (BABYLON = {}));
  69301. //# sourceMappingURL=babylon.passPostProcess.js.map
  69302. var __assign = (this && this.__assign) || function () {
  69303. __assign = Object.assign || function(t) {
  69304. for (var s, i = 1, n = arguments.length; i < n; i++) {
  69305. s = arguments[i];
  69306. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  69307. t[p] = s[p];
  69308. }
  69309. return t;
  69310. };
  69311. return __assign.apply(this, arguments);
  69312. };
  69313. var BABYLON;
  69314. (function (BABYLON) {
  69315. /**
  69316. * Default implementation IShadowGenerator.
  69317. * This is the main object responsible of generating shadows in the framework.
  69318. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  69319. */
  69320. var ShadowGenerator = /** @class */ (function () {
  69321. /**
  69322. * Creates a ShadowGenerator object.
  69323. * A ShadowGenerator is the required tool to use the shadows.
  69324. * Each light casting shadows needs to use its own ShadowGenerator.
  69325. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  69326. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  69327. * @param light The light object generating the shadows.
  69328. * @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.
  69329. */
  69330. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  69331. this._bias = 0.00005;
  69332. this._normalBias = 0;
  69333. this._blurBoxOffset = 1;
  69334. this._blurScale = 2;
  69335. this._blurKernel = 1;
  69336. this._useKernelBlur = false;
  69337. this._filter = ShadowGenerator.FILTER_NONE;
  69338. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  69339. this._contactHardeningLightSizeUVRatio = 0.1;
  69340. this._darkness = 0;
  69341. this._transparencyShadow = false;
  69342. /**
  69343. * Controls the extent to which the shadows fade out at the edge of the frustum
  69344. * Used only by directionals and spots
  69345. */
  69346. this.frustumEdgeFalloff = 0;
  69347. /**
  69348. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  69349. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  69350. * It might on the other hand introduce peter panning.
  69351. */
  69352. this.forceBackFacesOnly = false;
  69353. this._lightDirection = BABYLON.Vector3.Zero();
  69354. this._viewMatrix = BABYLON.Matrix.Zero();
  69355. this._projectionMatrix = BABYLON.Matrix.Zero();
  69356. this._transformMatrix = BABYLON.Matrix.Zero();
  69357. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69358. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69359. this._currentFaceIndex = 0;
  69360. this._currentFaceIndexCache = 0;
  69361. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  69362. this._mapSize = mapSize;
  69363. this._light = light;
  69364. this._scene = light.getScene();
  69365. light._shadowGenerator = this;
  69366. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  69367. if (!component) {
  69368. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  69369. this._scene._addComponent(component);
  69370. }
  69371. // Texture type fallback from float to int if not supported.
  69372. var caps = this._scene.getEngine().getCaps();
  69373. if (!useFullFloatFirst) {
  69374. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  69375. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69376. }
  69377. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  69378. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69379. }
  69380. else {
  69381. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69382. }
  69383. }
  69384. else {
  69385. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  69386. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69387. }
  69388. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  69389. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69390. }
  69391. else {
  69392. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69393. }
  69394. }
  69395. this._initializeGenerator();
  69396. this._applyFilterValues();
  69397. }
  69398. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  69399. /**
  69400. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  69401. */
  69402. get: function () {
  69403. return this._bias;
  69404. },
  69405. /**
  69406. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  69407. */
  69408. set: function (bias) {
  69409. this._bias = bias;
  69410. },
  69411. enumerable: true,
  69412. configurable: true
  69413. });
  69414. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  69415. /**
  69416. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  69417. */
  69418. get: function () {
  69419. return this._normalBias;
  69420. },
  69421. /**
  69422. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  69423. */
  69424. set: function (normalBias) {
  69425. this._normalBias = normalBias;
  69426. },
  69427. enumerable: true,
  69428. configurable: true
  69429. });
  69430. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  69431. /**
  69432. * Gets the blur box offset: offset applied during the blur pass.
  69433. * Only usefull if useKernelBlur = false
  69434. */
  69435. get: function () {
  69436. return this._blurBoxOffset;
  69437. },
  69438. /**
  69439. * Sets the blur box offset: offset applied during the blur pass.
  69440. * Only usefull if useKernelBlur = false
  69441. */
  69442. set: function (value) {
  69443. if (this._blurBoxOffset === value) {
  69444. return;
  69445. }
  69446. this._blurBoxOffset = value;
  69447. this._disposeBlurPostProcesses();
  69448. },
  69449. enumerable: true,
  69450. configurable: true
  69451. });
  69452. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  69453. /**
  69454. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  69455. * 2 means half of the size.
  69456. */
  69457. get: function () {
  69458. return this._blurScale;
  69459. },
  69460. /**
  69461. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  69462. * 2 means half of the size.
  69463. */
  69464. set: function (value) {
  69465. if (this._blurScale === value) {
  69466. return;
  69467. }
  69468. this._blurScale = value;
  69469. this._disposeBlurPostProcesses();
  69470. },
  69471. enumerable: true,
  69472. configurable: true
  69473. });
  69474. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  69475. /**
  69476. * Gets the blur kernel: kernel size of the blur pass.
  69477. * Only usefull if useKernelBlur = true
  69478. */
  69479. get: function () {
  69480. return this._blurKernel;
  69481. },
  69482. /**
  69483. * Sets the blur kernel: kernel size of the blur pass.
  69484. * Only usefull if useKernelBlur = true
  69485. */
  69486. set: function (value) {
  69487. if (this._blurKernel === value) {
  69488. return;
  69489. }
  69490. this._blurKernel = value;
  69491. this._disposeBlurPostProcesses();
  69492. },
  69493. enumerable: true,
  69494. configurable: true
  69495. });
  69496. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  69497. /**
  69498. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  69499. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69500. */
  69501. get: function () {
  69502. return this._useKernelBlur;
  69503. },
  69504. /**
  69505. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  69506. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69507. */
  69508. set: function (value) {
  69509. if (this._useKernelBlur === value) {
  69510. return;
  69511. }
  69512. this._useKernelBlur = value;
  69513. this._disposeBlurPostProcesses();
  69514. },
  69515. enumerable: true,
  69516. configurable: true
  69517. });
  69518. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  69519. /**
  69520. * Gets the depth scale used in ESM mode.
  69521. */
  69522. get: function () {
  69523. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  69524. },
  69525. /**
  69526. * Sets the depth scale used in ESM mode.
  69527. * This can override the scale stored on the light.
  69528. */
  69529. set: function (value) {
  69530. this._depthScale = value;
  69531. },
  69532. enumerable: true,
  69533. configurable: true
  69534. });
  69535. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  69536. /**
  69537. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  69538. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69539. */
  69540. get: function () {
  69541. return this._filter;
  69542. },
  69543. /**
  69544. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  69545. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69546. */
  69547. set: function (value) {
  69548. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  69549. if (this._light.needCube()) {
  69550. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  69551. this.useExponentialShadowMap = true;
  69552. return;
  69553. }
  69554. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  69555. this.useCloseExponentialShadowMap = true;
  69556. return;
  69557. }
  69558. // PCF on cubemap would also be expensive
  69559. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  69560. this.usePoissonSampling = true;
  69561. return;
  69562. }
  69563. }
  69564. // Weblg1 fallback for PCF.
  69565. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  69566. if (this._scene.getEngine().webGLVersion === 1) {
  69567. this.usePoissonSampling = true;
  69568. return;
  69569. }
  69570. }
  69571. if (this._filter === value) {
  69572. return;
  69573. }
  69574. this._filter = value;
  69575. this._disposeBlurPostProcesses();
  69576. this._applyFilterValues();
  69577. this._light._markMeshesAsLightDirty();
  69578. },
  69579. enumerable: true,
  69580. configurable: true
  69581. });
  69582. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  69583. /**
  69584. * Gets if the current filter is set to Poisson Sampling.
  69585. */
  69586. get: function () {
  69587. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  69588. },
  69589. /**
  69590. * Sets the current filter to Poisson Sampling.
  69591. */
  69592. set: function (value) {
  69593. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  69594. return;
  69595. }
  69596. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  69597. },
  69598. enumerable: true,
  69599. configurable: true
  69600. });
  69601. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  69602. /**
  69603. * Gets if the current filter is set to VSM.
  69604. * DEPRECATED. Should use useExponentialShadowMap instead.
  69605. */
  69606. get: function () {
  69607. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  69608. return this.useExponentialShadowMap;
  69609. },
  69610. /**
  69611. * Sets the current filter is to VSM.
  69612. * DEPRECATED. Should use useExponentialShadowMap instead.
  69613. */
  69614. set: function (value) {
  69615. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  69616. this.useExponentialShadowMap = value;
  69617. },
  69618. enumerable: true,
  69619. configurable: true
  69620. });
  69621. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  69622. /**
  69623. * Gets if the current filter is set to blurred VSM.
  69624. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  69625. */
  69626. get: function () {
  69627. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  69628. return this.useBlurExponentialShadowMap;
  69629. },
  69630. /**
  69631. * Sets the current filter is to blurred VSM.
  69632. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  69633. */
  69634. set: function (value) {
  69635. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  69636. this.useBlurExponentialShadowMap = value;
  69637. },
  69638. enumerable: true,
  69639. configurable: true
  69640. });
  69641. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  69642. /**
  69643. * Gets if the current filter is set to ESM.
  69644. */
  69645. get: function () {
  69646. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  69647. },
  69648. /**
  69649. * Sets the current filter is to ESM.
  69650. */
  69651. set: function (value) {
  69652. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  69653. return;
  69654. }
  69655. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69656. },
  69657. enumerable: true,
  69658. configurable: true
  69659. });
  69660. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  69661. /**
  69662. * Gets if the current filter is set to filtered ESM.
  69663. */
  69664. get: function () {
  69665. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  69666. },
  69667. /**
  69668. * Gets if the current filter is set to filtered ESM.
  69669. */
  69670. set: function (value) {
  69671. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  69672. return;
  69673. }
  69674. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69675. },
  69676. enumerable: true,
  69677. configurable: true
  69678. });
  69679. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  69680. /**
  69681. * Gets if the current filter is set to "close ESM" (using the inverse of the
  69682. * exponential to prevent steep falloff artifacts).
  69683. */
  69684. get: function () {
  69685. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  69686. },
  69687. /**
  69688. * Sets the current filter to "close ESM" (using the inverse of the
  69689. * exponential to prevent steep falloff artifacts).
  69690. */
  69691. set: function (value) {
  69692. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  69693. return;
  69694. }
  69695. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69696. },
  69697. enumerable: true,
  69698. configurable: true
  69699. });
  69700. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  69701. /**
  69702. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  69703. * exponential to prevent steep falloff artifacts).
  69704. */
  69705. get: function () {
  69706. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  69707. },
  69708. /**
  69709. * Sets the current filter to filtered "close ESM" (using the inverse of the
  69710. * exponential to prevent steep falloff artifacts).
  69711. */
  69712. set: function (value) {
  69713. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  69714. return;
  69715. }
  69716. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69717. },
  69718. enumerable: true,
  69719. configurable: true
  69720. });
  69721. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  69722. /**
  69723. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  69724. */
  69725. get: function () {
  69726. return this.filter === ShadowGenerator.FILTER_PCF;
  69727. },
  69728. /**
  69729. * Sets the current filter to "PCF" (percentage closer filtering).
  69730. */
  69731. set: function (value) {
  69732. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  69733. return;
  69734. }
  69735. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  69736. },
  69737. enumerable: true,
  69738. configurable: true
  69739. });
  69740. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  69741. /**
  69742. * Gets the PCF or PCSS Quality.
  69743. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69744. */
  69745. get: function () {
  69746. return this._filteringQuality;
  69747. },
  69748. /**
  69749. * Sets the PCF or PCSS Quality.
  69750. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69751. */
  69752. set: function (filteringQuality) {
  69753. this._filteringQuality = filteringQuality;
  69754. },
  69755. enumerable: true,
  69756. configurable: true
  69757. });
  69758. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  69759. /**
  69760. * Gets if the current filter is set to "PCSS" (contact hardening).
  69761. */
  69762. get: function () {
  69763. return this.filter === ShadowGenerator.FILTER_PCSS;
  69764. },
  69765. /**
  69766. * Sets the current filter to "PCSS" (contact hardening).
  69767. */
  69768. set: function (value) {
  69769. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  69770. return;
  69771. }
  69772. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  69773. },
  69774. enumerable: true,
  69775. configurable: true
  69776. });
  69777. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  69778. /**
  69779. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69780. * Using a ratio helps keeping shape stability independently of the map size.
  69781. *
  69782. * It does not account for the light projection as it was having too much
  69783. * instability during the light setup or during light position changes.
  69784. *
  69785. * Only valid if useContactHardeningShadow is true.
  69786. */
  69787. get: function () {
  69788. return this._contactHardeningLightSizeUVRatio;
  69789. },
  69790. /**
  69791. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69792. * Using a ratio helps keeping shape stability independently of the map size.
  69793. *
  69794. * It does not account for the light projection as it was having too much
  69795. * instability during the light setup or during light position changes.
  69796. *
  69797. * Only valid if useContactHardeningShadow is true.
  69798. */
  69799. set: function (contactHardeningLightSizeUVRatio) {
  69800. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  69801. },
  69802. enumerable: true,
  69803. configurable: true
  69804. });
  69805. /**
  69806. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  69807. * 0 means strongest and 1 would means no shadow.
  69808. * @returns the darkness.
  69809. */
  69810. ShadowGenerator.prototype.getDarkness = function () {
  69811. return this._darkness;
  69812. };
  69813. /**
  69814. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  69815. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  69816. * @returns the shadow generator allowing fluent coding.
  69817. */
  69818. ShadowGenerator.prototype.setDarkness = function (darkness) {
  69819. if (darkness >= 1.0)
  69820. this._darkness = 1.0;
  69821. else if (darkness <= 0.0)
  69822. this._darkness = 0.0;
  69823. else
  69824. this._darkness = darkness;
  69825. return this;
  69826. };
  69827. /**
  69828. * Sets the ability to have transparent shadow (boolean).
  69829. * @param transparent True if transparent else False
  69830. * @returns the shadow generator allowing fluent coding
  69831. */
  69832. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  69833. this._transparencyShadow = transparent;
  69834. return this;
  69835. };
  69836. /**
  69837. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  69838. * @returns The render target texture if present otherwise, null
  69839. */
  69840. ShadowGenerator.prototype.getShadowMap = function () {
  69841. return this._shadowMap;
  69842. };
  69843. /**
  69844. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  69845. * @returns The render target texture if the shadow map is present otherwise, null
  69846. */
  69847. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  69848. if (this._shadowMap2) {
  69849. return this._shadowMap2;
  69850. }
  69851. return this._shadowMap;
  69852. };
  69853. /**
  69854. * Helper function to add a mesh and its descendants to the list of shadow casters.
  69855. * @param mesh Mesh to add
  69856. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  69857. * @returns the Shadow Generator itself
  69858. */
  69859. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  69860. if (includeDescendants === void 0) { includeDescendants = true; }
  69861. var _a;
  69862. if (!this._shadowMap) {
  69863. return this;
  69864. }
  69865. if (!this._shadowMap.renderList) {
  69866. this._shadowMap.renderList = [];
  69867. }
  69868. this._shadowMap.renderList.push(mesh);
  69869. if (includeDescendants) {
  69870. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  69871. }
  69872. return this;
  69873. };
  69874. /**
  69875. * Helper function to remove a mesh and its descendants from the list of shadow casters
  69876. * @param mesh Mesh to remove
  69877. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  69878. * @returns the Shadow Generator itself
  69879. */
  69880. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  69881. if (includeDescendants === void 0) { includeDescendants = true; }
  69882. if (!this._shadowMap || !this._shadowMap.renderList) {
  69883. return this;
  69884. }
  69885. var index = this._shadowMap.renderList.indexOf(mesh);
  69886. if (index !== -1) {
  69887. this._shadowMap.renderList.splice(index, 1);
  69888. }
  69889. if (includeDescendants) {
  69890. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  69891. var child = _a[_i];
  69892. this.removeShadowCaster(child);
  69893. }
  69894. }
  69895. return this;
  69896. };
  69897. /**
  69898. * Returns the associated light object.
  69899. * @returns the light generating the shadow
  69900. */
  69901. ShadowGenerator.prototype.getLight = function () {
  69902. return this._light;
  69903. };
  69904. ShadowGenerator.prototype._initializeGenerator = function () {
  69905. this._light._markMeshesAsLightDirty();
  69906. this._initializeShadowMap();
  69907. };
  69908. ShadowGenerator.prototype._initializeShadowMap = function () {
  69909. var _this = this;
  69910. // Render target
  69911. var engine = this._scene.getEngine();
  69912. if (engine.webGLVersion > 1) {
  69913. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  69914. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  69915. }
  69916. else {
  69917. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  69918. }
  69919. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69920. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69921. this._shadowMap.anisotropicFilteringLevel = 1;
  69922. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69923. this._shadowMap.renderParticles = false;
  69924. this._shadowMap.ignoreCameraViewport = true;
  69925. // Record Face Index before render.
  69926. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  69927. _this._currentFaceIndex = faceIndex;
  69928. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69929. engine.setColorWrite(false);
  69930. }
  69931. });
  69932. // Custom render function.
  69933. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  69934. // Blur if required afer render.
  69935. this._shadowMap.onAfterUnbindObservable.add(function () {
  69936. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69937. engine.setColorWrite(true);
  69938. }
  69939. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  69940. return;
  69941. }
  69942. var shadowMap = _this.getShadowMapForRendering();
  69943. if (shadowMap) {
  69944. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  69945. }
  69946. });
  69947. // Clear according to the chosen filter.
  69948. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  69949. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  69950. this._shadowMap.onClearObservable.add(function (engine) {
  69951. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69952. engine.clear(clearOne, false, true, false);
  69953. }
  69954. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  69955. engine.clear(clearZero, true, true, false);
  69956. }
  69957. else {
  69958. engine.clear(clearOne, true, true, false);
  69959. }
  69960. });
  69961. };
  69962. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  69963. var _this = this;
  69964. var engine = this._scene.getEngine();
  69965. var targetSize = this._mapSize / this.blurScale;
  69966. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  69967. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  69968. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69969. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69970. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69971. }
  69972. if (this.useKernelBlur) {
  69973. 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);
  69974. this._kernelBlurXPostprocess.width = targetSize;
  69975. this._kernelBlurXPostprocess.height = targetSize;
  69976. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  69977. effect.setTexture("textureSampler", _this._shadowMap);
  69978. });
  69979. 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);
  69980. this._kernelBlurXPostprocess.autoClear = false;
  69981. this._kernelBlurYPostprocess.autoClear = false;
  69982. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69983. this._kernelBlurXPostprocess.packedFloat = true;
  69984. this._kernelBlurYPostprocess.packedFloat = true;
  69985. }
  69986. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  69987. }
  69988. else {
  69989. 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);
  69990. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  69991. effect.setFloat2("screenSize", targetSize, targetSize);
  69992. effect.setTexture("textureSampler", _this._shadowMap);
  69993. });
  69994. this._boxBlurPostprocess.autoClear = false;
  69995. this._blurPostProcesses = [this._boxBlurPostprocess];
  69996. }
  69997. };
  69998. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69999. var index;
  70000. var engine = this._scene.getEngine();
  70001. if (depthOnlySubMeshes.length) {
  70002. engine.setColorWrite(false);
  70003. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70004. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  70005. }
  70006. engine.setColorWrite(true);
  70007. }
  70008. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70009. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  70010. }
  70011. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70012. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  70013. }
  70014. if (this._transparencyShadow) {
  70015. for (index = 0; index < transparentSubMeshes.length; index++) {
  70016. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  70017. }
  70018. }
  70019. };
  70020. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  70021. var _this = this;
  70022. var mesh = subMesh.getRenderingMesh();
  70023. var scene = this._scene;
  70024. var engine = scene.getEngine();
  70025. var material = subMesh.getMaterial();
  70026. if (!material) {
  70027. return;
  70028. }
  70029. // Culling
  70030. engine.setState(material.backFaceCulling);
  70031. // Managing instances
  70032. var batch = mesh._getInstancesRenderList(subMesh._id);
  70033. if (batch.mustReturn) {
  70034. return;
  70035. }
  70036. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  70037. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  70038. engine.enableEffect(this._effect);
  70039. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  70040. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  70041. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  70042. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70043. this._effect.setVector3("lightData", this._cachedDirection);
  70044. }
  70045. else {
  70046. this._effect.setVector3("lightData", this._cachedPosition);
  70047. }
  70048. if (scene.activeCamera) {
  70049. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  70050. }
  70051. // Alpha test
  70052. if (material && material.needAlphaTesting()) {
  70053. var alphaTexture = material.getAlphaTestTexture();
  70054. if (alphaTexture) {
  70055. this._effect.setTexture("diffuseSampler", alphaTexture);
  70056. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  70057. }
  70058. }
  70059. // Bones
  70060. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70061. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  70062. }
  70063. // Morph targets
  70064. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  70065. if (this.forceBackFacesOnly) {
  70066. engine.setState(true, 0, false, true);
  70067. }
  70068. // Draw
  70069. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70070. if (this.forceBackFacesOnly) {
  70071. engine.setState(true, 0, false, false);
  70072. }
  70073. }
  70074. else {
  70075. // Need to reset refresh rate of the shadowMap
  70076. if (this._shadowMap) {
  70077. this._shadowMap.resetRefreshCounter();
  70078. }
  70079. }
  70080. };
  70081. ShadowGenerator.prototype._applyFilterValues = function () {
  70082. if (!this._shadowMap) {
  70083. return;
  70084. }
  70085. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  70086. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  70087. }
  70088. else {
  70089. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70090. }
  70091. };
  70092. /**
  70093. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70094. * @param onCompiled Callback triggered at the and of the effects compilation
  70095. * @param options Sets of optional options forcing the compilation with different modes
  70096. */
  70097. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  70098. var _this = this;
  70099. var localOptions = __assign({ useInstances: false }, options);
  70100. var shadowMap = this.getShadowMap();
  70101. if (!shadowMap) {
  70102. if (onCompiled) {
  70103. onCompiled(this);
  70104. }
  70105. return;
  70106. }
  70107. var renderList = shadowMap.renderList;
  70108. if (!renderList) {
  70109. if (onCompiled) {
  70110. onCompiled(this);
  70111. }
  70112. return;
  70113. }
  70114. var subMeshes = new Array();
  70115. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  70116. var mesh = renderList_1[_i];
  70117. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  70118. }
  70119. if (subMeshes.length === 0) {
  70120. if (onCompiled) {
  70121. onCompiled(this);
  70122. }
  70123. return;
  70124. }
  70125. var currentIndex = 0;
  70126. var checkReady = function () {
  70127. if (!_this._scene || !_this._scene.getEngine()) {
  70128. return;
  70129. }
  70130. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  70131. currentIndex++;
  70132. if (currentIndex >= subMeshes.length) {
  70133. if (onCompiled) {
  70134. onCompiled(_this);
  70135. }
  70136. return;
  70137. }
  70138. }
  70139. setTimeout(checkReady, 16);
  70140. };
  70141. checkReady();
  70142. };
  70143. /**
  70144. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70145. * @param options Sets of optional options forcing the compilation with different modes
  70146. * @returns A promise that resolves when the compilation completes
  70147. */
  70148. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  70149. var _this = this;
  70150. return new Promise(function (resolve) {
  70151. _this.forceCompilation(function () {
  70152. resolve();
  70153. }, options);
  70154. });
  70155. };
  70156. /**
  70157. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  70158. * @param subMesh The submesh we want to render in the shadow map
  70159. * @param useInstances Defines wether will draw in the map using instances
  70160. * @returns true if ready otherwise, false
  70161. */
  70162. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  70163. var defines = [];
  70164. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70165. defines.push("#define FLOAT");
  70166. }
  70167. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  70168. defines.push("#define ESM");
  70169. }
  70170. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  70171. defines.push("#define DEPTHTEXTURE");
  70172. }
  70173. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70174. var mesh = subMesh.getMesh();
  70175. var material = subMesh.getMaterial();
  70176. // Normal bias.
  70177. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  70178. attribs.push(BABYLON.VertexBuffer.NormalKind);
  70179. defines.push("#define NORMAL");
  70180. if (mesh.nonUniformScaling) {
  70181. defines.push("#define NONUNIFORMSCALING");
  70182. }
  70183. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70184. defines.push("#define DIRECTIONINLIGHTDATA");
  70185. }
  70186. }
  70187. // Alpha test
  70188. if (material && material.needAlphaTesting()) {
  70189. var alphaTexture = material.getAlphaTestTexture();
  70190. if (alphaTexture) {
  70191. defines.push("#define ALPHATEST");
  70192. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70193. attribs.push(BABYLON.VertexBuffer.UVKind);
  70194. defines.push("#define UV1");
  70195. }
  70196. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70197. if (alphaTexture.coordinatesIndex === 1) {
  70198. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70199. defines.push("#define UV2");
  70200. }
  70201. }
  70202. }
  70203. }
  70204. // Bones
  70205. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70206. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70207. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70208. if (mesh.numBoneInfluencers > 4) {
  70209. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70210. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70211. }
  70212. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70213. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  70214. }
  70215. else {
  70216. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70217. }
  70218. // Morph targets
  70219. var manager = mesh.morphTargetManager;
  70220. var morphInfluencers = 0;
  70221. if (manager) {
  70222. if (manager.numInfluencers > 0) {
  70223. defines.push("#define MORPHTARGETS");
  70224. morphInfluencers = manager.numInfluencers;
  70225. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  70226. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  70227. }
  70228. }
  70229. // Instances
  70230. if (useInstances) {
  70231. defines.push("#define INSTANCES");
  70232. attribs.push("world0");
  70233. attribs.push("world1");
  70234. attribs.push("world2");
  70235. attribs.push("world3");
  70236. }
  70237. // Get correct effect
  70238. var join = defines.join("\n");
  70239. if (this._cachedDefines !== join) {
  70240. this._cachedDefines = join;
  70241. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  70242. }
  70243. if (!this._effect.isReady()) {
  70244. return false;
  70245. }
  70246. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  70247. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  70248. this._initializeBlurRTTAndPostProcesses();
  70249. }
  70250. }
  70251. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  70252. return false;
  70253. }
  70254. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  70255. return false;
  70256. }
  70257. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  70258. return false;
  70259. }
  70260. return true;
  70261. };
  70262. /**
  70263. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  70264. * @param defines Defines of the material we want to update
  70265. * @param lightIndex Index of the light in the enabled light list of the material
  70266. */
  70267. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  70268. var scene = this._scene;
  70269. var light = this._light;
  70270. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  70271. return;
  70272. }
  70273. defines["SHADOW" + lightIndex] = true;
  70274. if (this.useContactHardeningShadow) {
  70275. defines["SHADOWPCSS" + lightIndex] = true;
  70276. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  70277. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  70278. }
  70279. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  70280. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  70281. }
  70282. // else default to high.
  70283. }
  70284. if (this.usePercentageCloserFiltering) {
  70285. defines["SHADOWPCF" + lightIndex] = true;
  70286. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  70287. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  70288. }
  70289. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  70290. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  70291. }
  70292. // else default to high.
  70293. }
  70294. else if (this.usePoissonSampling) {
  70295. defines["SHADOWPOISSON" + lightIndex] = true;
  70296. }
  70297. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  70298. defines["SHADOWESM" + lightIndex] = true;
  70299. }
  70300. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  70301. defines["SHADOWCLOSEESM" + lightIndex] = true;
  70302. }
  70303. if (light.needCube()) {
  70304. defines["SHADOWCUBE" + lightIndex] = true;
  70305. }
  70306. };
  70307. /**
  70308. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  70309. * defined in the generator but impacting the effect).
  70310. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  70311. * @param effect The effect we are binfing the information for
  70312. */
  70313. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  70314. var light = this._light;
  70315. var scene = this._scene;
  70316. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  70317. return;
  70318. }
  70319. var camera = scene.activeCamera;
  70320. if (!camera) {
  70321. return;
  70322. }
  70323. var shadowMap = this.getShadowMap();
  70324. if (!shadowMap) {
  70325. return;
  70326. }
  70327. if (!light.needCube()) {
  70328. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  70329. }
  70330. // Only PCF uses depth stencil texture.
  70331. if (this._filter === ShadowGenerator.FILTER_PCF) {
  70332. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70333. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  70334. }
  70335. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  70336. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70337. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  70338. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  70339. }
  70340. else {
  70341. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70342. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  70343. }
  70344. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  70345. };
  70346. /**
  70347. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  70348. * (eq to shadow prjection matrix * light transform matrix)
  70349. * @returns The transform matrix used to create the shadow map
  70350. */
  70351. ShadowGenerator.prototype.getTransformMatrix = function () {
  70352. var scene = this._scene;
  70353. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  70354. return this._transformMatrix;
  70355. }
  70356. this._currentRenderID = scene.getRenderId();
  70357. this._currentFaceIndexCache = this._currentFaceIndex;
  70358. var lightPosition = this._light.position;
  70359. if (this._light.computeTransformedInformation()) {
  70360. lightPosition = this._light.transformedPosition;
  70361. }
  70362. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  70363. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  70364. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  70365. }
  70366. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  70367. this._cachedPosition.copyFrom(lightPosition);
  70368. this._cachedDirection.copyFrom(this._lightDirection);
  70369. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  70370. var shadowMap = this.getShadowMap();
  70371. if (shadowMap) {
  70372. var renderList = shadowMap.renderList;
  70373. if (renderList) {
  70374. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  70375. }
  70376. }
  70377. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  70378. }
  70379. return this._transformMatrix;
  70380. };
  70381. /**
  70382. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  70383. * Cube and 2D textures for instance.
  70384. */
  70385. ShadowGenerator.prototype.recreateShadowMap = function () {
  70386. var shadowMap = this._shadowMap;
  70387. if (!shadowMap) {
  70388. return;
  70389. }
  70390. // Track render list.
  70391. var renderList = shadowMap.renderList;
  70392. // Clean up existing data.
  70393. this._disposeRTTandPostProcesses();
  70394. // Reinitializes.
  70395. this._initializeGenerator();
  70396. // Reaffect the filter to ensure a correct fallback if necessary.
  70397. this.filter = this.filter;
  70398. // Reaffect the filter.
  70399. this._applyFilterValues();
  70400. // Reaffect Render List.
  70401. this._shadowMap.renderList = renderList;
  70402. };
  70403. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  70404. if (this._shadowMap2) {
  70405. this._shadowMap2.dispose();
  70406. this._shadowMap2 = null;
  70407. }
  70408. if (this._boxBlurPostprocess) {
  70409. this._boxBlurPostprocess.dispose();
  70410. this._boxBlurPostprocess = null;
  70411. }
  70412. if (this._kernelBlurXPostprocess) {
  70413. this._kernelBlurXPostprocess.dispose();
  70414. this._kernelBlurXPostprocess = null;
  70415. }
  70416. if (this._kernelBlurYPostprocess) {
  70417. this._kernelBlurYPostprocess.dispose();
  70418. this._kernelBlurYPostprocess = null;
  70419. }
  70420. this._blurPostProcesses = [];
  70421. };
  70422. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  70423. if (this._shadowMap) {
  70424. this._shadowMap.dispose();
  70425. this._shadowMap = null;
  70426. }
  70427. this._disposeBlurPostProcesses();
  70428. };
  70429. /**
  70430. * Disposes the ShadowGenerator.
  70431. * Returns nothing.
  70432. */
  70433. ShadowGenerator.prototype.dispose = function () {
  70434. this._disposeRTTandPostProcesses();
  70435. if (this._light) {
  70436. this._light._shadowGenerator = null;
  70437. this._light._markMeshesAsLightDirty();
  70438. }
  70439. };
  70440. /**
  70441. * Serializes the shadow generator setup to a json object.
  70442. * @returns The serialized JSON object
  70443. */
  70444. ShadowGenerator.prototype.serialize = function () {
  70445. var serializationObject = {};
  70446. var shadowMap = this.getShadowMap();
  70447. if (!shadowMap) {
  70448. return serializationObject;
  70449. }
  70450. serializationObject.lightId = this._light.id;
  70451. serializationObject.mapSize = shadowMap.getRenderSize();
  70452. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  70453. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  70454. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70455. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70456. serializationObject.usePoissonSampling = this.usePoissonSampling;
  70457. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  70458. serializationObject.depthScale = this.depthScale;
  70459. serializationObject.darkness = this.getDarkness();
  70460. serializationObject.blurBoxOffset = this.blurBoxOffset;
  70461. serializationObject.blurKernel = this.blurKernel;
  70462. serializationObject.blurScale = this.blurScale;
  70463. serializationObject.useKernelBlur = this.useKernelBlur;
  70464. serializationObject.transparencyShadow = this._transparencyShadow;
  70465. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  70466. serializationObject.bias = this.bias;
  70467. serializationObject.normalBias = this.normalBias;
  70468. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  70469. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  70470. serializationObject.filteringQuality = this.filteringQuality;
  70471. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  70472. serializationObject.renderList = [];
  70473. if (shadowMap.renderList) {
  70474. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  70475. var mesh = shadowMap.renderList[meshIndex];
  70476. serializationObject.renderList.push(mesh.id);
  70477. }
  70478. }
  70479. return serializationObject;
  70480. };
  70481. /**
  70482. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  70483. * @param parsedShadowGenerator The JSON object to parse
  70484. * @param scene The scene to create the shadow map for
  70485. * @returns The parsed shadow generator
  70486. */
  70487. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  70488. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  70489. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  70490. var shadowMap = shadowGenerator.getShadowMap();
  70491. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  70492. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  70493. meshes.forEach(function (mesh) {
  70494. if (!shadowMap) {
  70495. return;
  70496. }
  70497. if (!shadowMap.renderList) {
  70498. shadowMap.renderList = [];
  70499. }
  70500. shadowMap.renderList.push(mesh);
  70501. });
  70502. }
  70503. if (parsedShadowGenerator.usePoissonSampling) {
  70504. shadowGenerator.usePoissonSampling = true;
  70505. }
  70506. else if (parsedShadowGenerator.useExponentialShadowMap) {
  70507. shadowGenerator.useExponentialShadowMap = true;
  70508. }
  70509. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  70510. shadowGenerator.useBlurExponentialShadowMap = true;
  70511. }
  70512. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  70513. shadowGenerator.useCloseExponentialShadowMap = true;
  70514. }
  70515. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  70516. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  70517. }
  70518. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  70519. shadowGenerator.usePercentageCloserFiltering = true;
  70520. }
  70521. else if (parsedShadowGenerator.useContactHardeningShadow) {
  70522. shadowGenerator.useContactHardeningShadow = true;
  70523. }
  70524. if (parsedShadowGenerator.filteringQuality) {
  70525. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  70526. }
  70527. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  70528. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  70529. }
  70530. // Backward compat
  70531. else if (parsedShadowGenerator.useVarianceShadowMap) {
  70532. shadowGenerator.useExponentialShadowMap = true;
  70533. }
  70534. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  70535. shadowGenerator.useBlurExponentialShadowMap = true;
  70536. }
  70537. if (parsedShadowGenerator.depthScale) {
  70538. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  70539. }
  70540. if (parsedShadowGenerator.blurScale) {
  70541. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  70542. }
  70543. if (parsedShadowGenerator.blurBoxOffset) {
  70544. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  70545. }
  70546. if (parsedShadowGenerator.useKernelBlur) {
  70547. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  70548. }
  70549. if (parsedShadowGenerator.blurKernel) {
  70550. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  70551. }
  70552. if (parsedShadowGenerator.bias !== undefined) {
  70553. shadowGenerator.bias = parsedShadowGenerator.bias;
  70554. }
  70555. if (parsedShadowGenerator.normalBias !== undefined) {
  70556. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  70557. }
  70558. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  70559. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  70560. }
  70561. if (parsedShadowGenerator.darkness) {
  70562. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  70563. }
  70564. if (parsedShadowGenerator.transparencyShadow) {
  70565. shadowGenerator.setTransparencyShadow(true);
  70566. }
  70567. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  70568. return shadowGenerator;
  70569. };
  70570. /**
  70571. * Shadow generator mode None: no filtering applied.
  70572. */
  70573. ShadowGenerator.FILTER_NONE = 0;
  70574. /**
  70575. * Shadow generator mode ESM: Exponential Shadow Mapping.
  70576. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70577. */
  70578. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  70579. /**
  70580. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  70581. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  70582. */
  70583. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  70584. /**
  70585. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  70586. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70587. */
  70588. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  70589. /**
  70590. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  70591. * edge artifacts on steep falloff.
  70592. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70593. */
  70594. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  70595. /**
  70596. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  70597. * edge artifacts on steep falloff.
  70598. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70599. */
  70600. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  70601. /**
  70602. * Shadow generator mode PCF: Percentage Closer Filtering
  70603. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  70604. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  70605. */
  70606. ShadowGenerator.FILTER_PCF = 6;
  70607. /**
  70608. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  70609. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  70610. * Contact Hardening
  70611. */
  70612. ShadowGenerator.FILTER_PCSS = 7;
  70613. /**
  70614. * Reserved for PCF and PCSS
  70615. * Highest Quality.
  70616. *
  70617. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  70618. *
  70619. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  70620. */
  70621. ShadowGenerator.QUALITY_HIGH = 0;
  70622. /**
  70623. * Reserved for PCF and PCSS
  70624. * Good tradeoff for quality/perf cross devices
  70625. *
  70626. * Execute PCF on a 3*3 kernel.
  70627. *
  70628. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  70629. */
  70630. ShadowGenerator.QUALITY_MEDIUM = 1;
  70631. /**
  70632. * Reserved for PCF and PCSS
  70633. * The lowest quality but the fastest.
  70634. *
  70635. * Execute PCF on a 1*1 kernel.
  70636. *
  70637. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  70638. */
  70639. ShadowGenerator.QUALITY_LOW = 2;
  70640. return ShadowGenerator;
  70641. }());
  70642. BABYLON.ShadowGenerator = ShadowGenerator;
  70643. })(BABYLON || (BABYLON = {}));
  70644. //# sourceMappingURL=babylon.shadowGenerator.js.map
  70645. var BABYLON;
  70646. (function (BABYLON) {
  70647. // Adds the parser to the scene parsers.
  70648. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  70649. // Shadows
  70650. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  70651. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  70652. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  70653. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  70654. // SG would be available on their associated lights
  70655. }
  70656. }
  70657. });
  70658. /**
  70659. * Defines the shadow generator component responsible to manage any shadow generators
  70660. * in a given scene.
  70661. */
  70662. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  70663. /**
  70664. * Creates a new instance of the component for the given scene
  70665. * @param scene Defines the scene to register the component in
  70666. */
  70667. function ShadowGeneratorSceneComponent(scene) {
  70668. /**
  70669. * The component name helpfull to identify the component in the list of scene components.
  70670. */
  70671. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  70672. this.scene = scene;
  70673. }
  70674. /**
  70675. * Registers the component in a given scene
  70676. */
  70677. ShadowGeneratorSceneComponent.prototype.register = function () {
  70678. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  70679. };
  70680. /**
  70681. * Rebuilds the elements related to this component in case of
  70682. * context lost for instance.
  70683. */
  70684. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  70685. // Nothing To Do Here.
  70686. };
  70687. /**
  70688. * Serializes the component data to the specified json object
  70689. * @param serializationObject The object to serialize to
  70690. */
  70691. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  70692. // Shadows
  70693. serializationObject.shadowGenerators = [];
  70694. var lights = this.scene.lights;
  70695. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  70696. var light = lights_1[_i];
  70697. var shadowGenerator = light.getShadowGenerator();
  70698. if (shadowGenerator) {
  70699. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  70700. }
  70701. }
  70702. };
  70703. /**
  70704. * Adds all the element from the container to the scene
  70705. * @param container the container holding the elements
  70706. */
  70707. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  70708. // Nothing To Do Here. (directly attached to a light)
  70709. };
  70710. /**
  70711. * Removes all the elements in the container from the scene
  70712. * @param container contains the elements to remove
  70713. */
  70714. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  70715. // Nothing To Do Here. (directly attached to a light)
  70716. };
  70717. /**
  70718. * Rebuilds the elements related to this component in case of
  70719. * context lost for instance.
  70720. */
  70721. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  70722. // Nothing To Do Here.
  70723. };
  70724. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  70725. // Shadows
  70726. var scene = this.scene;
  70727. if (this.scene.shadowsEnabled) {
  70728. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  70729. var light = scene.lights[lightIndex];
  70730. var shadowGenerator = light.getShadowGenerator();
  70731. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  70732. var shadowMap = (shadowGenerator.getShadowMap());
  70733. if (scene.textures.indexOf(shadowMap) !== -1) {
  70734. renderTargets.push(shadowMap);
  70735. }
  70736. }
  70737. }
  70738. }
  70739. };
  70740. return ShadowGeneratorSceneComponent;
  70741. }());
  70742. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  70743. })(BABYLON || (BABYLON = {}));
  70744. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  70745. var BABYLON;
  70746. (function (BABYLON) {
  70747. var DefaultLoadingScreen = /** @class */ (function () {
  70748. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  70749. if (_loadingText === void 0) { _loadingText = ""; }
  70750. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  70751. var _this = this;
  70752. this._renderingCanvas = _renderingCanvas;
  70753. this._loadingText = _loadingText;
  70754. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  70755. // Resize
  70756. this._resizeLoadingUI = function () {
  70757. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  70758. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  70759. if (!_this._loadingDiv) {
  70760. return;
  70761. }
  70762. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  70763. _this._loadingDiv.style.left = canvasRect.left + "px";
  70764. _this._loadingDiv.style.top = canvasRect.top + "px";
  70765. _this._loadingDiv.style.width = canvasRect.width + "px";
  70766. _this._loadingDiv.style.height = canvasRect.height + "px";
  70767. };
  70768. }
  70769. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  70770. if (this._loadingDiv) {
  70771. // Do not add a loading screen if there is already one
  70772. return;
  70773. }
  70774. this._loadingDiv = document.createElement("div");
  70775. this._loadingDiv.id = "babylonjsLoadingDiv";
  70776. this._loadingDiv.style.opacity = "0";
  70777. this._loadingDiv.style.transition = "opacity 1.5s ease";
  70778. this._loadingDiv.style.pointerEvents = "none";
  70779. // Loading text
  70780. this._loadingTextDiv = document.createElement("div");
  70781. this._loadingTextDiv.style.position = "absolute";
  70782. this._loadingTextDiv.style.left = "0";
  70783. this._loadingTextDiv.style.top = "50%";
  70784. this._loadingTextDiv.style.marginTop = "80px";
  70785. this._loadingTextDiv.style.width = "100%";
  70786. this._loadingTextDiv.style.height = "20px";
  70787. this._loadingTextDiv.style.fontFamily = "Arial";
  70788. this._loadingTextDiv.style.fontSize = "14px";
  70789. this._loadingTextDiv.style.color = "white";
  70790. this._loadingTextDiv.style.textAlign = "center";
  70791. this._loadingTextDiv.innerHTML = "Loading";
  70792. this._loadingDiv.appendChild(this._loadingTextDiv);
  70793. //set the predefined text
  70794. this._loadingTextDiv.innerHTML = this._loadingText;
  70795. // Generating keyframes
  70796. var style = document.createElement('style');
  70797. style.type = 'text/css';
  70798. 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 }";
  70799. style.innerHTML = keyFrames;
  70800. document.getElementsByTagName('head')[0].appendChild(style);
  70801. // Loading img
  70802. var imgBack = new Image();
  70803. 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";
  70804. imgBack.style.position = "absolute";
  70805. imgBack.style.left = "50%";
  70806. imgBack.style.top = "50%";
  70807. imgBack.style.marginLeft = "-60px";
  70808. imgBack.style.marginTop = "-60px";
  70809. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  70810. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  70811. imgBack.style.transformOrigin = "50% 50%";
  70812. imgBack.style.webkitTransformOrigin = "50% 50%";
  70813. this._loadingDiv.appendChild(imgBack);
  70814. this._resizeLoadingUI();
  70815. window.addEventListener("resize", this._resizeLoadingUI);
  70816. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70817. document.body.appendChild(this._loadingDiv);
  70818. this._loadingDiv.style.opacity = "1";
  70819. };
  70820. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  70821. var _this = this;
  70822. if (!this._loadingDiv) {
  70823. return;
  70824. }
  70825. var onTransitionEnd = function () {
  70826. if (!_this._loadingDiv) {
  70827. return;
  70828. }
  70829. document.body.removeChild(_this._loadingDiv);
  70830. window.removeEventListener("resize", _this._resizeLoadingUI);
  70831. _this._loadingDiv = null;
  70832. };
  70833. this._loadingDiv.style.opacity = "0";
  70834. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  70835. };
  70836. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  70837. set: function (text) {
  70838. this._loadingText = text;
  70839. if (this._loadingTextDiv) {
  70840. this._loadingTextDiv.innerHTML = this._loadingText;
  70841. }
  70842. },
  70843. enumerable: true,
  70844. configurable: true
  70845. });
  70846. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  70847. get: function () {
  70848. return this._loadingDivBackgroundColor;
  70849. },
  70850. set: function (color) {
  70851. this._loadingDivBackgroundColor = color;
  70852. if (!this._loadingDiv) {
  70853. return;
  70854. }
  70855. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70856. },
  70857. enumerable: true,
  70858. configurable: true
  70859. });
  70860. return DefaultLoadingScreen;
  70861. }());
  70862. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  70863. })(BABYLON || (BABYLON = {}));
  70864. //# sourceMappingURL=babylon.loadingScreen.js.map
  70865. var BABYLON;
  70866. (function (BABYLON) {
  70867. var SceneLoaderProgressEvent = /** @class */ (function () {
  70868. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  70869. this.lengthComputable = lengthComputable;
  70870. this.loaded = loaded;
  70871. this.total = total;
  70872. }
  70873. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  70874. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  70875. };
  70876. return SceneLoaderProgressEvent;
  70877. }());
  70878. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  70879. var SceneLoader = /** @class */ (function () {
  70880. function SceneLoader() {
  70881. }
  70882. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  70883. get: function () {
  70884. return 0;
  70885. },
  70886. enumerable: true,
  70887. configurable: true
  70888. });
  70889. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  70890. get: function () {
  70891. return 1;
  70892. },
  70893. enumerable: true,
  70894. configurable: true
  70895. });
  70896. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  70897. get: function () {
  70898. return 2;
  70899. },
  70900. enumerable: true,
  70901. configurable: true
  70902. });
  70903. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  70904. get: function () {
  70905. return 3;
  70906. },
  70907. enumerable: true,
  70908. configurable: true
  70909. });
  70910. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  70911. get: function () {
  70912. return SceneLoader._ForceFullSceneLoadingForIncremental;
  70913. },
  70914. set: function (value) {
  70915. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  70916. },
  70917. enumerable: true,
  70918. configurable: true
  70919. });
  70920. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  70921. get: function () {
  70922. return SceneLoader._ShowLoadingScreen;
  70923. },
  70924. set: function (value) {
  70925. SceneLoader._ShowLoadingScreen = value;
  70926. },
  70927. enumerable: true,
  70928. configurable: true
  70929. });
  70930. Object.defineProperty(SceneLoader, "loggingLevel", {
  70931. get: function () {
  70932. return SceneLoader._loggingLevel;
  70933. },
  70934. set: function (value) {
  70935. SceneLoader._loggingLevel = value;
  70936. },
  70937. enumerable: true,
  70938. configurable: true
  70939. });
  70940. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  70941. get: function () {
  70942. return SceneLoader._CleanBoneMatrixWeights;
  70943. },
  70944. set: function (value) {
  70945. SceneLoader._CleanBoneMatrixWeights = value;
  70946. },
  70947. enumerable: true,
  70948. configurable: true
  70949. });
  70950. SceneLoader._getDefaultPlugin = function () {
  70951. return SceneLoader._registeredPlugins[".babylon"];
  70952. };
  70953. SceneLoader._getPluginForExtension = function (extension) {
  70954. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  70955. if (registeredPlugin) {
  70956. return registeredPlugin;
  70957. }
  70958. 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");
  70959. return SceneLoader._getDefaultPlugin();
  70960. };
  70961. SceneLoader._getPluginForDirectLoad = function (data) {
  70962. for (var extension in SceneLoader._registeredPlugins) {
  70963. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  70964. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  70965. return SceneLoader._registeredPlugins[extension];
  70966. }
  70967. }
  70968. return SceneLoader._getDefaultPlugin();
  70969. };
  70970. SceneLoader._getPluginForFilename = function (sceneFilename) {
  70971. if (sceneFilename.name) {
  70972. sceneFilename = sceneFilename.name;
  70973. }
  70974. var queryStringPosition = sceneFilename.indexOf("?");
  70975. if (queryStringPosition !== -1) {
  70976. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  70977. }
  70978. var dotPosition = sceneFilename.lastIndexOf(".");
  70979. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  70980. return SceneLoader._getPluginForExtension(extension);
  70981. };
  70982. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  70983. SceneLoader._getDirectLoad = function (sceneFilename) {
  70984. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  70985. return sceneFilename.substr(5);
  70986. }
  70987. return null;
  70988. };
  70989. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  70990. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  70991. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  70992. var plugin;
  70993. if (registeredPlugin.plugin.createPlugin) {
  70994. plugin = registeredPlugin.plugin.createPlugin();
  70995. }
  70996. else {
  70997. plugin = registeredPlugin.plugin;
  70998. }
  70999. var useArrayBuffer = registeredPlugin.isBinary;
  71000. var database;
  71001. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  71002. var dataCallback = function (data, responseURL) {
  71003. if (scene.isDisposed) {
  71004. onError("Scene has been disposed");
  71005. return;
  71006. }
  71007. scene.database = database;
  71008. onSuccess(plugin, data, responseURL);
  71009. };
  71010. var request = null;
  71011. var pluginDisposed = false;
  71012. var onDisposeObservable = plugin.onDisposeObservable;
  71013. if (onDisposeObservable) {
  71014. onDisposeObservable.add(function () {
  71015. pluginDisposed = true;
  71016. if (request) {
  71017. request.abort();
  71018. request = null;
  71019. }
  71020. onDispose();
  71021. });
  71022. }
  71023. var manifestChecked = function () {
  71024. if (pluginDisposed) {
  71025. return;
  71026. }
  71027. var url = rootUrl + sceneFilename;
  71028. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  71029. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  71030. } : undefined, database, useArrayBuffer, function (request, exception) {
  71031. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  71032. });
  71033. };
  71034. if (directLoad) {
  71035. dataCallback(directLoad);
  71036. return plugin;
  71037. }
  71038. if (rootUrl.indexOf("file:") === -1) {
  71039. var engine = scene.getEngine();
  71040. var canUseOfflineSupport = engine.enableOfflineSupport;
  71041. if (canUseOfflineSupport) {
  71042. // Also check for exceptions
  71043. var exceptionFound = false;
  71044. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  71045. var regex = _a[_i];
  71046. if (regex.test(rootUrl + sceneFilename)) {
  71047. exceptionFound = true;
  71048. break;
  71049. }
  71050. }
  71051. canUseOfflineSupport = !exceptionFound;
  71052. }
  71053. if (canUseOfflineSupport) {
  71054. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  71055. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  71056. }
  71057. else {
  71058. manifestChecked();
  71059. }
  71060. }
  71061. // Loading file from disk via input file or drag'n'drop
  71062. else {
  71063. var fileOrString = sceneFilename;
  71064. if (fileOrString.name) { // File
  71065. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  71066. }
  71067. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  71068. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  71069. }
  71070. else {
  71071. onError("Unable to find file named " + sceneFilename);
  71072. }
  71073. }
  71074. return plugin;
  71075. };
  71076. // Public functions
  71077. SceneLoader.GetPluginForExtension = function (extension) {
  71078. return SceneLoader._getPluginForExtension(extension).plugin;
  71079. };
  71080. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  71081. return !!SceneLoader._registeredPlugins[extension];
  71082. };
  71083. SceneLoader.RegisterPlugin = function (plugin) {
  71084. if (typeof plugin.extensions === "string") {
  71085. var extension = plugin.extensions;
  71086. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71087. plugin: plugin,
  71088. isBinary: false
  71089. };
  71090. }
  71091. else {
  71092. var extensions = plugin.extensions;
  71093. Object.keys(extensions).forEach(function (extension) {
  71094. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71095. plugin: plugin,
  71096. isBinary: extensions[extension].isBinary
  71097. };
  71098. });
  71099. }
  71100. };
  71101. /**
  71102. * Import meshes into a scene
  71103. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71104. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71105. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71106. * @param scene the instance of BABYLON.Scene to append to
  71107. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  71108. * @param onProgress a callback with a progress event for each file being loaded
  71109. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71110. * @param pluginExtension the extension used to determine the plugin
  71111. * @returns The loaded plugin
  71112. */
  71113. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71114. if (sceneFilename === void 0) { sceneFilename = ""; }
  71115. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71116. if (onSuccess === void 0) { onSuccess = null; }
  71117. if (onProgress === void 0) { onProgress = null; }
  71118. if (onError === void 0) { onError = null; }
  71119. if (pluginExtension === void 0) { pluginExtension = null; }
  71120. if (!scene) {
  71121. BABYLON.Tools.Error("No scene available to import mesh to");
  71122. return null;
  71123. }
  71124. if (!sceneFilename) {
  71125. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71126. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71127. }
  71128. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71129. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71130. return null;
  71131. }
  71132. var loadingToken = {};
  71133. scene._addPendingData(loadingToken);
  71134. var disposeHandler = function () {
  71135. scene._removePendingData(loadingToken);
  71136. };
  71137. var errorHandler = function (message, exception) {
  71138. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  71139. if (onError) {
  71140. onError(scene, errorMessage, exception);
  71141. }
  71142. else {
  71143. BABYLON.Tools.Error(errorMessage);
  71144. // should the exception be thrown?
  71145. }
  71146. disposeHandler();
  71147. };
  71148. var progressHandler = onProgress ? function (event) {
  71149. try {
  71150. onProgress(event);
  71151. }
  71152. catch (e) {
  71153. errorHandler("Error in onProgress callback", e);
  71154. }
  71155. } : undefined;
  71156. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  71157. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  71158. if (onSuccess) {
  71159. try {
  71160. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  71161. }
  71162. catch (e) {
  71163. errorHandler("Error in onSuccess callback", e);
  71164. }
  71165. }
  71166. scene._removePendingData(loadingToken);
  71167. };
  71168. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71169. if (plugin.rewriteRootURL) {
  71170. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  71171. }
  71172. if (sceneFilename === "") {
  71173. if (sceneFilename === "") {
  71174. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  71175. }
  71176. }
  71177. if (plugin.importMesh) {
  71178. var syncedPlugin = plugin;
  71179. var meshes = new Array();
  71180. var particleSystems = new Array();
  71181. var skeletons = new Array();
  71182. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  71183. return;
  71184. }
  71185. scene.loadingPluginName = plugin.name;
  71186. successHandler(meshes, particleSystems, skeletons, []);
  71187. }
  71188. else {
  71189. var asyncedPlugin = plugin;
  71190. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function (result) {
  71191. scene.loadingPluginName = plugin.name;
  71192. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  71193. }).catch(function (error) {
  71194. errorHandler(error.message, error);
  71195. });
  71196. }
  71197. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71198. };
  71199. /**
  71200. * Import meshes into a scene
  71201. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71202. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71203. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71204. * @param scene the instance of BABYLON.Scene to append to
  71205. * @param onProgress a callback with a progress event for each file being loaded
  71206. * @param pluginExtension the extension used to determine the plugin
  71207. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  71208. */
  71209. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71210. if (sceneFilename === void 0) { sceneFilename = ""; }
  71211. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71212. if (onProgress === void 0) { onProgress = null; }
  71213. if (pluginExtension === void 0) { pluginExtension = null; }
  71214. return new Promise(function (resolve, reject) {
  71215. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  71216. resolve({
  71217. meshes: meshes,
  71218. particleSystems: particleSystems,
  71219. skeletons: skeletons,
  71220. animationGroups: animationGroups
  71221. });
  71222. }, onProgress, function (scene, message, exception) {
  71223. reject(exception || new Error(message));
  71224. }, pluginExtension);
  71225. });
  71226. };
  71227. /**
  71228. * Load a scene
  71229. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71230. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71231. * @param engine is the instance of BABYLON.Engine to use to create the scene
  71232. * @param onSuccess a callback with the scene when import succeeds
  71233. * @param onProgress a callback with a progress event for each file being loaded
  71234. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71235. * @param pluginExtension the extension used to determine the plugin
  71236. * @returns The loaded plugin
  71237. */
  71238. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  71239. if (onSuccess === void 0) { onSuccess = null; }
  71240. if (onProgress === void 0) { onProgress = null; }
  71241. if (onError === void 0) { onError = null; }
  71242. if (pluginExtension === void 0) { pluginExtension = null; }
  71243. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  71244. };
  71245. /**
  71246. * Load a scene
  71247. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71248. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71249. * @param engine is the instance of BABYLON.Engine to use to create the scene
  71250. * @param onProgress a callback with a progress event for each file being loaded
  71251. * @param pluginExtension the extension used to determine the plugin
  71252. * @returns The loaded scene
  71253. */
  71254. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  71255. if (onProgress === void 0) { onProgress = null; }
  71256. if (pluginExtension === void 0) { pluginExtension = null; }
  71257. return new Promise(function (resolve, reject) {
  71258. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  71259. resolve(scene);
  71260. }, onProgress, function (scene, message, exception) {
  71261. reject(exception || new Error(message));
  71262. }, pluginExtension);
  71263. });
  71264. };
  71265. /**
  71266. * Append a scene
  71267. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71268. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71269. * @param scene is the instance of BABYLON.Scene to append to
  71270. * @param onSuccess a callback with the scene when import succeeds
  71271. * @param onProgress a callback with a progress event for each file being loaded
  71272. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71273. * @param pluginExtension the extension used to determine the plugin
  71274. * @returns The loaded plugin
  71275. */
  71276. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71277. if (sceneFilename === void 0) { sceneFilename = ""; }
  71278. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71279. if (onSuccess === void 0) { onSuccess = null; }
  71280. if (onProgress === void 0) { onProgress = null; }
  71281. if (onError === void 0) { onError = null; }
  71282. if (pluginExtension === void 0) { pluginExtension = null; }
  71283. if (!scene) {
  71284. BABYLON.Tools.Error("No scene available to append to");
  71285. return null;
  71286. }
  71287. if (!sceneFilename) {
  71288. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71289. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71290. }
  71291. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71292. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71293. return null;
  71294. }
  71295. if (SceneLoader.ShowLoadingScreen) {
  71296. scene.getEngine().displayLoadingUI();
  71297. }
  71298. var loadingToken = {};
  71299. scene._addPendingData(loadingToken);
  71300. var disposeHandler = function () {
  71301. scene._removePendingData(loadingToken);
  71302. scene.getEngine().hideLoadingUI();
  71303. };
  71304. var errorHandler = function (message, exception) {
  71305. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  71306. if (onError) {
  71307. onError(scene, errorMessage, exception);
  71308. }
  71309. else {
  71310. BABYLON.Tools.Error(errorMessage);
  71311. // should the exception be thrown?
  71312. }
  71313. disposeHandler();
  71314. };
  71315. var progressHandler = onProgress ? function (event) {
  71316. try {
  71317. onProgress(event);
  71318. }
  71319. catch (e) {
  71320. errorHandler("Error in onProgress callback", e);
  71321. }
  71322. } : undefined;
  71323. var successHandler = function () {
  71324. if (onSuccess) {
  71325. try {
  71326. onSuccess(scene);
  71327. }
  71328. catch (e) {
  71329. errorHandler("Error in onSuccess callback", e);
  71330. }
  71331. }
  71332. scene._removePendingData(loadingToken);
  71333. };
  71334. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71335. if (sceneFilename === "") {
  71336. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  71337. }
  71338. if (plugin.load) {
  71339. var syncedPlugin = plugin;
  71340. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  71341. return;
  71342. }
  71343. scene.loadingPluginName = plugin.name;
  71344. successHandler();
  71345. }
  71346. else {
  71347. var asyncedPlugin = plugin;
  71348. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function () {
  71349. scene.loadingPluginName = plugin.name;
  71350. successHandler();
  71351. }).catch(function (error) {
  71352. errorHandler(error.message, error);
  71353. });
  71354. }
  71355. if (SceneLoader.ShowLoadingScreen) {
  71356. scene.executeWhenReady(function () {
  71357. scene.getEngine().hideLoadingUI();
  71358. });
  71359. }
  71360. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71361. };
  71362. /**
  71363. * Append a scene
  71364. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71365. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71366. * @param scene is the instance of BABYLON.Scene to append to
  71367. * @param onProgress a callback with a progress event for each file being loaded
  71368. * @param pluginExtension the extension used to determine the plugin
  71369. * @returns The given scene
  71370. */
  71371. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71372. if (sceneFilename === void 0) { sceneFilename = ""; }
  71373. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71374. if (onProgress === void 0) { onProgress = null; }
  71375. if (pluginExtension === void 0) { pluginExtension = null; }
  71376. return new Promise(function (resolve, reject) {
  71377. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  71378. resolve(scene);
  71379. }, onProgress, function (scene, message, exception) {
  71380. reject(exception || new Error(message));
  71381. }, pluginExtension);
  71382. });
  71383. };
  71384. /**
  71385. * Load a scene into an asset container
  71386. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71387. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71388. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  71389. * @param onSuccess a callback with the scene when import succeeds
  71390. * @param onProgress a callback with a progress event for each file being loaded
  71391. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71392. * @param pluginExtension the extension used to determine the plugin
  71393. * @returns The loaded plugin
  71394. */
  71395. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71396. if (sceneFilename === void 0) { sceneFilename = ""; }
  71397. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71398. if (onSuccess === void 0) { onSuccess = null; }
  71399. if (onProgress === void 0) { onProgress = null; }
  71400. if (onError === void 0) { onError = null; }
  71401. if (pluginExtension === void 0) { pluginExtension = null; }
  71402. if (!scene) {
  71403. BABYLON.Tools.Error("No scene available to load asset container to");
  71404. return null;
  71405. }
  71406. if (!sceneFilename) {
  71407. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71408. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71409. }
  71410. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71411. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71412. return null;
  71413. }
  71414. var loadingToken = {};
  71415. scene._addPendingData(loadingToken);
  71416. var disposeHandler = function () {
  71417. scene._removePendingData(loadingToken);
  71418. };
  71419. var errorHandler = function (message, exception) {
  71420. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  71421. if (onError) {
  71422. onError(scene, errorMessage, exception);
  71423. }
  71424. else {
  71425. BABYLON.Tools.Error(errorMessage);
  71426. // should the exception be thrown?
  71427. }
  71428. disposeHandler();
  71429. };
  71430. var progressHandler = onProgress ? function (event) {
  71431. try {
  71432. onProgress(event);
  71433. }
  71434. catch (e) {
  71435. errorHandler("Error in onProgress callback", e);
  71436. }
  71437. } : undefined;
  71438. var successHandler = function (assets) {
  71439. if (onSuccess) {
  71440. try {
  71441. onSuccess(assets);
  71442. }
  71443. catch (e) {
  71444. errorHandler("Error in onSuccess callback", e);
  71445. }
  71446. }
  71447. scene._removePendingData(loadingToken);
  71448. };
  71449. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71450. if (plugin.loadAssetContainer) {
  71451. var syncedPlugin = plugin;
  71452. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  71453. if (!assetContainer) {
  71454. return;
  71455. }
  71456. scene.loadingPluginName = plugin.name;
  71457. successHandler(assetContainer);
  71458. }
  71459. else if (plugin.loadAssetContainerAsync) {
  71460. var asyncedPlugin = plugin;
  71461. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function (assetContainer) {
  71462. scene.loadingPluginName = plugin.name;
  71463. successHandler(assetContainer);
  71464. }).catch(function (error) {
  71465. errorHandler(error.message, error);
  71466. });
  71467. }
  71468. else {
  71469. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  71470. }
  71471. if (SceneLoader.ShowLoadingScreen) {
  71472. scene.executeWhenReady(function () {
  71473. scene.getEngine().hideLoadingUI();
  71474. });
  71475. }
  71476. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71477. };
  71478. /**
  71479. * Load a scene into an asset container
  71480. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71481. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71482. * @param scene is the instance of BABYLON.Scene to append to
  71483. * @param onProgress a callback with a progress event for each file being loaded
  71484. * @param pluginExtension the extension used to determine the plugin
  71485. * @returns The loaded asset container
  71486. */
  71487. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71488. if (sceneFilename === void 0) { sceneFilename = ""; }
  71489. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71490. if (onProgress === void 0) { onProgress = null; }
  71491. if (pluginExtension === void 0) { pluginExtension = null; }
  71492. return new Promise(function (resolve, reject) {
  71493. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  71494. resolve(assetContainer);
  71495. }, onProgress, function (scene, message, exception) {
  71496. reject(exception || new Error(message));
  71497. }, pluginExtension);
  71498. });
  71499. };
  71500. // Flags
  71501. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  71502. SceneLoader._ShowLoadingScreen = true;
  71503. SceneLoader._CleanBoneMatrixWeights = false;
  71504. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  71505. // Members
  71506. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  71507. SceneLoader._registeredPlugins = {};
  71508. return SceneLoader;
  71509. }());
  71510. BABYLON.SceneLoader = SceneLoader;
  71511. ;
  71512. })(BABYLON || (BABYLON = {}));
  71513. //# sourceMappingURL=babylon.sceneLoader.js.map
  71514. var BABYLON;
  71515. (function (BABYLON) {
  71516. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  71517. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  71518. var parsedMaterial = parsedData.materials[index];
  71519. if (parsedMaterial.id === id) {
  71520. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  71521. }
  71522. }
  71523. return null;
  71524. };
  71525. var isDescendantOf = function (mesh, names, hierarchyIds) {
  71526. for (var i in names) {
  71527. if (mesh.name === names[i]) {
  71528. hierarchyIds.push(mesh.id);
  71529. return true;
  71530. }
  71531. }
  71532. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  71533. hierarchyIds.push(mesh.id);
  71534. return true;
  71535. }
  71536. return false;
  71537. };
  71538. var logOperation = function (operation, producer) {
  71539. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  71540. };
  71541. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  71542. if (addToScene === void 0) { addToScene = false; }
  71543. var container = new BABYLON.AssetContainer(scene);
  71544. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71545. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71546. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71547. // and avoid problems with multiple concurrent .babylon loads.
  71548. var log = "importScene has failed JSON parse";
  71549. try {
  71550. var parsedData = JSON.parse(data);
  71551. log = "";
  71552. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  71553. var index;
  71554. var cache;
  71555. // Lights
  71556. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  71557. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  71558. var parsedLight = parsedData.lights[index];
  71559. var light = BABYLON.Light.Parse(parsedLight, scene);
  71560. if (light) {
  71561. container.lights.push(light);
  71562. log += (index === 0 ? "\n\tLights:" : "");
  71563. log += "\n\t\t" + light.toString(fullDetails);
  71564. }
  71565. }
  71566. }
  71567. // Animations
  71568. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  71569. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  71570. var parsedAnimation = parsedData.animations[index];
  71571. var animation = BABYLON.Animation.Parse(parsedAnimation);
  71572. scene.animations.push(animation);
  71573. container.animations.push(animation);
  71574. log += (index === 0 ? "\n\tAnimations:" : "");
  71575. log += "\n\t\t" + animation.toString(fullDetails);
  71576. }
  71577. }
  71578. // Materials
  71579. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  71580. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  71581. var parsedMaterial = parsedData.materials[index];
  71582. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  71583. container.materials.push(mat);
  71584. log += (index === 0 ? "\n\tMaterials:" : "");
  71585. log += "\n\t\t" + mat.toString(fullDetails);
  71586. }
  71587. }
  71588. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  71589. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  71590. var parsedMultiMaterial = parsedData.multiMaterials[index];
  71591. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  71592. container.multiMaterials.push(mmat);
  71593. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  71594. log += "\n\t\t" + mmat.toString(fullDetails);
  71595. }
  71596. }
  71597. // Morph targets
  71598. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  71599. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  71600. var managerData = _a[_i];
  71601. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  71602. }
  71603. }
  71604. // Skeletons
  71605. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  71606. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  71607. var parsedSkeleton = parsedData.skeletons[index];
  71608. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  71609. container.skeletons.push(skeleton);
  71610. log += (index === 0 ? "\n\tSkeletons:" : "");
  71611. log += "\n\t\t" + skeleton.toString(fullDetails);
  71612. }
  71613. }
  71614. // Geometries
  71615. var geometries = parsedData.geometries;
  71616. if (geometries !== undefined && geometries !== null) {
  71617. var addedGeometry = new Array();
  71618. // Boxes
  71619. var boxes = geometries.boxes;
  71620. if (boxes !== undefined && boxes !== null) {
  71621. for (index = 0, cache = boxes.length; index < cache; index++) {
  71622. var parsedBox = boxes[index];
  71623. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  71624. }
  71625. }
  71626. // Spheres
  71627. var spheres = geometries.spheres;
  71628. if (spheres !== undefined && spheres !== null) {
  71629. for (index = 0, cache = spheres.length; index < cache; index++) {
  71630. var parsedSphere = spheres[index];
  71631. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  71632. }
  71633. }
  71634. // Cylinders
  71635. var cylinders = geometries.cylinders;
  71636. if (cylinders !== undefined && cylinders !== null) {
  71637. for (index = 0, cache = cylinders.length; index < cache; index++) {
  71638. var parsedCylinder = cylinders[index];
  71639. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  71640. }
  71641. }
  71642. // Toruses
  71643. var toruses = geometries.toruses;
  71644. if (toruses !== undefined && toruses !== null) {
  71645. for (index = 0, cache = toruses.length; index < cache; index++) {
  71646. var parsedTorus = toruses[index];
  71647. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  71648. }
  71649. }
  71650. // Grounds
  71651. var grounds = geometries.grounds;
  71652. if (grounds !== undefined && grounds !== null) {
  71653. for (index = 0, cache = grounds.length; index < cache; index++) {
  71654. var parsedGround = grounds[index];
  71655. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  71656. }
  71657. }
  71658. // Planes
  71659. var planes = geometries.planes;
  71660. if (planes !== undefined && planes !== null) {
  71661. for (index = 0, cache = planes.length; index < cache; index++) {
  71662. var parsedPlane = planes[index];
  71663. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  71664. }
  71665. }
  71666. // TorusKnots
  71667. var torusKnots = geometries.torusKnots;
  71668. if (torusKnots !== undefined && torusKnots !== null) {
  71669. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  71670. var parsedTorusKnot = torusKnots[index];
  71671. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  71672. }
  71673. }
  71674. // VertexData
  71675. var vertexData = geometries.vertexData;
  71676. if (vertexData !== undefined && vertexData !== null) {
  71677. for (index = 0, cache = vertexData.length; index < cache; index++) {
  71678. var parsedVertexData = vertexData[index];
  71679. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  71680. }
  71681. }
  71682. addedGeometry.forEach(function (g) {
  71683. if (g) {
  71684. container.geometries.push(g);
  71685. }
  71686. });
  71687. }
  71688. // Transform nodes
  71689. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  71690. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  71691. var parsedTransformNode = parsedData.transformNodes[index];
  71692. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  71693. container.transformNodes.push(node);
  71694. }
  71695. }
  71696. // Meshes
  71697. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  71698. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  71699. var parsedMesh = parsedData.meshes[index];
  71700. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  71701. container.meshes.push(mesh);
  71702. log += (index === 0 ? "\n\tMeshes:" : "");
  71703. log += "\n\t\t" + mesh.toString(fullDetails);
  71704. }
  71705. }
  71706. // Cameras
  71707. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  71708. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  71709. var parsedCamera = parsedData.cameras[index];
  71710. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  71711. container.cameras.push(camera);
  71712. log += (index === 0 ? "\n\tCameras:" : "");
  71713. log += "\n\t\t" + camera.toString(fullDetails);
  71714. }
  71715. }
  71716. // Browsing all the graph to connect the dots
  71717. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  71718. var camera = scene.cameras[index];
  71719. if (camera._waitingParentId) {
  71720. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  71721. camera._waitingParentId = null;
  71722. }
  71723. }
  71724. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  71725. var light_1 = scene.lights[index];
  71726. if (light_1 && light_1._waitingParentId) {
  71727. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  71728. light_1._waitingParentId = null;
  71729. }
  71730. }
  71731. // Sounds
  71732. // TODO: add sound
  71733. var loadedSounds = [];
  71734. var loadedSound;
  71735. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  71736. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  71737. var parsedSound = parsedData.sounds[index];
  71738. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71739. if (!parsedSound.url)
  71740. parsedSound.url = parsedSound.name;
  71741. if (!loadedSounds[parsedSound.url]) {
  71742. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  71743. loadedSounds[parsedSound.url] = loadedSound;
  71744. container.sounds.push(loadedSound);
  71745. }
  71746. else {
  71747. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  71748. }
  71749. }
  71750. else {
  71751. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  71752. }
  71753. }
  71754. }
  71755. loadedSounds = [];
  71756. // Connect parents & children and parse actions
  71757. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  71758. var transformNode = scene.transformNodes[index];
  71759. if (transformNode._waitingParentId) {
  71760. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  71761. transformNode._waitingParentId = null;
  71762. }
  71763. }
  71764. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71765. var mesh = scene.meshes[index];
  71766. if (mesh._waitingParentId) {
  71767. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  71768. mesh._waitingParentId = null;
  71769. }
  71770. if (mesh._waitingActions) {
  71771. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  71772. mesh._waitingActions = null;
  71773. }
  71774. }
  71775. // freeze world matrix application
  71776. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71777. var currentMesh = scene.meshes[index];
  71778. if (currentMesh._waitingFreezeWorldMatrix) {
  71779. currentMesh.freezeWorldMatrix();
  71780. currentMesh._waitingFreezeWorldMatrix = null;
  71781. }
  71782. else {
  71783. currentMesh.computeWorldMatrix(true);
  71784. }
  71785. }
  71786. // Lights exclusions / inclusions
  71787. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  71788. var light_2 = scene.lights[index];
  71789. // Excluded check
  71790. if (light_2._excludedMeshesIds.length > 0) {
  71791. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  71792. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  71793. if (excludedMesh) {
  71794. light_2.excludedMeshes.push(excludedMesh);
  71795. }
  71796. }
  71797. light_2._excludedMeshesIds = [];
  71798. }
  71799. // Included check
  71800. if (light_2._includedOnlyMeshesIds.length > 0) {
  71801. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  71802. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  71803. if (includedOnlyMesh) {
  71804. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  71805. }
  71806. }
  71807. light_2._includedOnlyMeshesIds = [];
  71808. }
  71809. }
  71810. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  71811. // Actions (scene)
  71812. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  71813. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  71814. }
  71815. if (!addToScene) {
  71816. container.removeAllFromScene();
  71817. }
  71818. }
  71819. catch (err) {
  71820. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  71821. if (onError) {
  71822. onError(msg, err);
  71823. }
  71824. else {
  71825. BABYLON.Tools.Log(msg);
  71826. throw err;
  71827. }
  71828. }
  71829. finally {
  71830. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71831. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71832. }
  71833. }
  71834. return container;
  71835. };
  71836. BABYLON.SceneLoader.RegisterPlugin({
  71837. name: "babylon.js",
  71838. extensions: ".babylon",
  71839. canDirectLoad: function (data) {
  71840. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  71841. return true;
  71842. }
  71843. return false;
  71844. },
  71845. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  71846. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71847. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71848. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71849. // and avoid problems with multiple concurrent .babylon loads.
  71850. var log = "importMesh has failed JSON parse";
  71851. try {
  71852. var parsedData = JSON.parse(data);
  71853. log = "";
  71854. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  71855. if (!meshesNames) {
  71856. meshesNames = null;
  71857. }
  71858. else if (!Array.isArray(meshesNames)) {
  71859. meshesNames = [meshesNames];
  71860. }
  71861. var hierarchyIds = new Array();
  71862. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  71863. var loadedSkeletonsIds = [];
  71864. var loadedMaterialsIds = [];
  71865. var index;
  71866. var cache;
  71867. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  71868. var parsedMesh = parsedData.meshes[index];
  71869. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  71870. if (meshesNames !== null) {
  71871. // Remove found mesh name from list.
  71872. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  71873. }
  71874. //Geometry?
  71875. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  71876. //does the file contain geometries?
  71877. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  71878. //find the correct geometry and add it to the scene
  71879. var found = false;
  71880. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  71881. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  71882. return;
  71883. }
  71884. else {
  71885. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  71886. if (parsedGeometryData.id === parsedMesh.geometryId) {
  71887. switch (geometryType) {
  71888. case "boxes":
  71889. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  71890. break;
  71891. case "spheres":
  71892. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  71893. break;
  71894. case "cylinders":
  71895. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  71896. break;
  71897. case "toruses":
  71898. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  71899. break;
  71900. case "grounds":
  71901. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  71902. break;
  71903. case "planes":
  71904. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  71905. break;
  71906. case "torusKnots":
  71907. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  71908. break;
  71909. case "vertexData":
  71910. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  71911. break;
  71912. }
  71913. found = true;
  71914. }
  71915. });
  71916. }
  71917. });
  71918. if (found === false) {
  71919. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  71920. }
  71921. }
  71922. }
  71923. // Material ?
  71924. if (parsedMesh.materialId) {
  71925. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  71926. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  71927. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  71928. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  71929. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  71930. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  71931. var subMatId = parsedMultiMaterial.materials[matIndex];
  71932. loadedMaterialsIds.push(subMatId);
  71933. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  71934. if (mat) {
  71935. log += "\n\tMaterial " + mat.toString(fullDetails);
  71936. }
  71937. }
  71938. loadedMaterialsIds.push(parsedMultiMaterial.id);
  71939. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  71940. if (mmat) {
  71941. materialFound = true;
  71942. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  71943. }
  71944. break;
  71945. }
  71946. }
  71947. }
  71948. if (materialFound === false) {
  71949. loadedMaterialsIds.push(parsedMesh.materialId);
  71950. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  71951. if (!mat) {
  71952. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  71953. }
  71954. else {
  71955. log += "\n\tMaterial " + mat.toString(fullDetails);
  71956. }
  71957. }
  71958. }
  71959. // Skeleton ?
  71960. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  71961. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  71962. if (skeletonAlreadyLoaded === false) {
  71963. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  71964. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  71965. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  71966. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  71967. skeletons.push(skeleton);
  71968. loadedSkeletonsIds.push(parsedSkeleton.id);
  71969. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  71970. }
  71971. }
  71972. }
  71973. }
  71974. // Morph targets ?
  71975. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  71976. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  71977. var managerData = _a[_i];
  71978. BABYLON.MorphTargetManager.Parse(managerData, scene);
  71979. }
  71980. }
  71981. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  71982. meshes.push(mesh);
  71983. log += "\n\tMesh " + mesh.toString(fullDetails);
  71984. }
  71985. }
  71986. // Connecting parents
  71987. var currentMesh;
  71988. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71989. currentMesh = scene.meshes[index];
  71990. if (currentMesh._waitingParentId) {
  71991. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  71992. currentMesh._waitingParentId = null;
  71993. }
  71994. }
  71995. // freeze and compute world matrix application
  71996. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71997. currentMesh = scene.meshes[index];
  71998. if (currentMesh._waitingFreezeWorldMatrix) {
  71999. currentMesh.freezeWorldMatrix();
  72000. currentMesh._waitingFreezeWorldMatrix = null;
  72001. }
  72002. else {
  72003. currentMesh.computeWorldMatrix(true);
  72004. }
  72005. }
  72006. }
  72007. // Particles
  72008. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  72009. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  72010. if (parser) {
  72011. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  72012. var parsedParticleSystem = parsedData.particleSystems[index];
  72013. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  72014. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  72015. }
  72016. }
  72017. }
  72018. }
  72019. return true;
  72020. }
  72021. catch (err) {
  72022. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  72023. if (onError) {
  72024. onError(msg, err);
  72025. }
  72026. else {
  72027. BABYLON.Tools.Log(msg);
  72028. throw err;
  72029. }
  72030. }
  72031. finally {
  72032. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72033. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72034. }
  72035. }
  72036. return false;
  72037. },
  72038. load: function (scene, data, rootUrl, onError) {
  72039. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72040. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72041. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72042. // and avoid problems with multiple concurrent .babylon loads.
  72043. var log = "importScene has failed JSON parse";
  72044. try {
  72045. var parsedData = JSON.parse(data);
  72046. log = "";
  72047. // Scene
  72048. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  72049. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  72050. }
  72051. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  72052. scene.autoClear = parsedData.autoClear;
  72053. }
  72054. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  72055. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  72056. }
  72057. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  72058. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  72059. }
  72060. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  72061. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  72062. }
  72063. // Fog
  72064. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  72065. scene.fogMode = parsedData.fogMode;
  72066. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  72067. scene.fogStart = parsedData.fogStart;
  72068. scene.fogEnd = parsedData.fogEnd;
  72069. scene.fogDensity = parsedData.fogDensity;
  72070. log += "\tFog mode for scene: ";
  72071. switch (scene.fogMode) {
  72072. // getters not compiling, so using hardcoded
  72073. case 1:
  72074. log += "exp\n";
  72075. break;
  72076. case 2:
  72077. log += "exp2\n";
  72078. break;
  72079. case 3:
  72080. log += "linear\n";
  72081. break;
  72082. }
  72083. }
  72084. //Physics
  72085. if (parsedData.physicsEnabled) {
  72086. var physicsPlugin;
  72087. if (parsedData.physicsEngine === "cannon") {
  72088. physicsPlugin = new BABYLON.CannonJSPlugin();
  72089. }
  72090. else if (parsedData.physicsEngine === "oimo") {
  72091. physicsPlugin = new BABYLON.OimoJSPlugin();
  72092. }
  72093. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  72094. //else - default engine, which is currently oimo
  72095. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  72096. scene.enablePhysics(physicsGravity, physicsPlugin);
  72097. }
  72098. // Metadata
  72099. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  72100. scene.metadata = parsedData.metadata;
  72101. }
  72102. //collisions, if defined. otherwise, default is true
  72103. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  72104. scene.collisionsEnabled = parsedData.collisionsEnabled;
  72105. }
  72106. scene.workerCollisions = !!parsedData.workerCollisions;
  72107. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  72108. if (!container) {
  72109. return false;
  72110. }
  72111. if (parsedData.autoAnimate) {
  72112. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  72113. }
  72114. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  72115. scene.setActiveCameraByID(parsedData.activeCameraID);
  72116. }
  72117. // Environment texture
  72118. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  72119. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  72120. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  72121. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  72122. if (parsedData.environmentTextureRotationY) {
  72123. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  72124. }
  72125. scene.environmentTexture = hdrTexture;
  72126. }
  72127. else {
  72128. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  72129. if (parsedData.environmentTextureRotationY) {
  72130. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  72131. }
  72132. scene.environmentTexture = cubeTexture;
  72133. }
  72134. if (parsedData.createDefaultSkybox === true) {
  72135. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  72136. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  72137. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  72138. }
  72139. }
  72140. // Finish
  72141. return true;
  72142. }
  72143. catch (err) {
  72144. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  72145. if (onError) {
  72146. onError(msg, err);
  72147. }
  72148. else {
  72149. BABYLON.Tools.Log(msg);
  72150. throw err;
  72151. }
  72152. }
  72153. finally {
  72154. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72155. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72156. }
  72157. }
  72158. return false;
  72159. },
  72160. loadAssetContainer: function (scene, data, rootUrl, onError) {
  72161. var container = loadAssetContainer(scene, data, rootUrl, onError);
  72162. return container;
  72163. }
  72164. });
  72165. })(BABYLON || (BABYLON = {}));
  72166. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  72167. var BABYLON;
  72168. (function (BABYLON) {
  72169. var FilesInput = /** @class */ (function () {
  72170. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  72171. this.onProcessFileCallback = function () { return true; };
  72172. this._engine = engine;
  72173. this._currentScene = scene;
  72174. this._sceneLoadedCallback = sceneLoadedCallback;
  72175. this._progressCallback = progressCallback;
  72176. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  72177. this._textureLoadingCallback = textureLoadingCallback;
  72178. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  72179. this._onReloadCallback = onReloadCallback;
  72180. this._errorCallback = errorCallback;
  72181. }
  72182. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  72183. var _this = this;
  72184. if (elementToMonitor) {
  72185. this._elementToMonitor = elementToMonitor;
  72186. this._dragEnterHandler = function (e) { _this.drag(e); };
  72187. this._dragOverHandler = function (e) { _this.drag(e); };
  72188. this._dropHandler = function (e) { _this.drop(e); };
  72189. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  72190. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  72191. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  72192. }
  72193. };
  72194. FilesInput.prototype.dispose = function () {
  72195. if (!this._elementToMonitor) {
  72196. return;
  72197. }
  72198. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  72199. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  72200. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  72201. };
  72202. FilesInput.prototype.renderFunction = function () {
  72203. if (this._additionalRenderLoopLogicCallback) {
  72204. this._additionalRenderLoopLogicCallback();
  72205. }
  72206. if (this._currentScene) {
  72207. if (this._textureLoadingCallback) {
  72208. var remaining = this._currentScene.getWaitingItemsCount();
  72209. if (remaining > 0) {
  72210. this._textureLoadingCallback(remaining);
  72211. }
  72212. }
  72213. this._currentScene.render();
  72214. }
  72215. };
  72216. FilesInput.prototype.drag = function (e) {
  72217. e.stopPropagation();
  72218. e.preventDefault();
  72219. };
  72220. FilesInput.prototype.drop = function (eventDrop) {
  72221. eventDrop.stopPropagation();
  72222. eventDrop.preventDefault();
  72223. this.loadFiles(eventDrop);
  72224. };
  72225. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  72226. var _this = this;
  72227. var reader = folder.createReader();
  72228. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  72229. reader.readEntries(function (entries) {
  72230. remaining.count += entries.length;
  72231. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  72232. var entry = entries_1[_i];
  72233. if (entry.isFile) {
  72234. entry.file(function (file) {
  72235. file.correctName = relativePath + file.name;
  72236. files.push(file);
  72237. if (--remaining.count === 0) {
  72238. callback();
  72239. }
  72240. });
  72241. }
  72242. else if (entry.isDirectory) {
  72243. _this._traverseFolder(entry, files, remaining, callback);
  72244. }
  72245. }
  72246. if (--remaining.count) {
  72247. callback();
  72248. }
  72249. });
  72250. };
  72251. FilesInput.prototype._processFiles = function (files) {
  72252. for (var i = 0; i < files.length; i++) {
  72253. var name = files[i].correctName.toLowerCase();
  72254. var extension = name.split('.').pop();
  72255. if (!this.onProcessFileCallback(files[i], name, extension)) {
  72256. continue;
  72257. }
  72258. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  72259. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  72260. this._sceneFileToLoad = files[i];
  72261. }
  72262. else {
  72263. FilesInput.FilesToLoad[name] = files[i];
  72264. }
  72265. }
  72266. };
  72267. FilesInput.prototype.loadFiles = function (event) {
  72268. var _this = this;
  72269. // Handling data transfer via drag'n'drop
  72270. if (event && event.dataTransfer && event.dataTransfer.files) {
  72271. this._filesToLoad = event.dataTransfer.files;
  72272. }
  72273. // Handling files from input files
  72274. if (event && event.target && event.target.files) {
  72275. this._filesToLoad = event.target.files;
  72276. }
  72277. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  72278. return;
  72279. }
  72280. if (this._startingProcessingFilesCallback) {
  72281. this._startingProcessingFilesCallback(this._filesToLoad);
  72282. }
  72283. if (this._filesToLoad && this._filesToLoad.length > 0) {
  72284. var files_1 = new Array();
  72285. var folders = [];
  72286. var items = event.dataTransfer ? event.dataTransfer.items : null;
  72287. for (var i = 0; i < this._filesToLoad.length; i++) {
  72288. var fileToLoad = this._filesToLoad[i];
  72289. var name_1 = fileToLoad.name.toLowerCase();
  72290. var entry = void 0;
  72291. fileToLoad.correctName = name_1;
  72292. if (items) {
  72293. var item = items[i];
  72294. if (item.getAsEntry) {
  72295. entry = item.getAsEntry();
  72296. }
  72297. else if (item.webkitGetAsEntry) {
  72298. entry = item.webkitGetAsEntry();
  72299. }
  72300. }
  72301. if (!entry) {
  72302. files_1.push(fileToLoad);
  72303. }
  72304. else {
  72305. if (entry.isDirectory) {
  72306. folders.push(entry);
  72307. }
  72308. else {
  72309. files_1.push(fileToLoad);
  72310. }
  72311. }
  72312. }
  72313. if (folders.length === 0) {
  72314. this._processFiles(files_1);
  72315. this._processReload();
  72316. }
  72317. else {
  72318. var remaining = { count: folders.length };
  72319. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  72320. var folder = folders_1[_i];
  72321. this._traverseFolder(folder, files_1, remaining, function () {
  72322. _this._processFiles(files_1);
  72323. if (remaining.count === 0) {
  72324. _this._processReload();
  72325. }
  72326. });
  72327. }
  72328. }
  72329. }
  72330. };
  72331. FilesInput.prototype._processReload = function () {
  72332. if (this._onReloadCallback) {
  72333. this._onReloadCallback(this._sceneFileToLoad);
  72334. }
  72335. else {
  72336. this.reload();
  72337. }
  72338. };
  72339. FilesInput.prototype.reload = function () {
  72340. var _this = this;
  72341. // If a scene file has been provided
  72342. if (this._sceneFileToLoad) {
  72343. if (this._currentScene) {
  72344. if (BABYLON.Tools.errorsCount > 0) {
  72345. BABYLON.Tools.ClearLogCache();
  72346. }
  72347. this._engine.stopRenderLoop();
  72348. }
  72349. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  72350. if (_this._progressCallback) {
  72351. _this._progressCallback(progress);
  72352. }
  72353. }).then(function (scene) {
  72354. if (_this._currentScene) {
  72355. _this._currentScene.dispose();
  72356. }
  72357. _this._currentScene = scene;
  72358. if (_this._sceneLoadedCallback) {
  72359. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  72360. }
  72361. // Wait for textures and shaders to be ready
  72362. _this._currentScene.executeWhenReady(function () {
  72363. _this._engine.runRenderLoop(function () {
  72364. _this.renderFunction();
  72365. });
  72366. });
  72367. }).catch(function (error) {
  72368. if (_this._errorCallback) {
  72369. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  72370. }
  72371. });
  72372. }
  72373. else {
  72374. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  72375. }
  72376. };
  72377. FilesInput.FilesToLoad = {};
  72378. return FilesInput;
  72379. }());
  72380. BABYLON.FilesInput = FilesInput;
  72381. })(BABYLON || (BABYLON = {}));
  72382. //# sourceMappingURL=babylon.filesInput.js.map
  72383. var BABYLON;
  72384. (function (BABYLON) {
  72385. var Tags = /** @class */ (function () {
  72386. function Tags() {
  72387. }
  72388. Tags.EnableFor = function (obj) {
  72389. obj._tags = obj._tags || {};
  72390. obj.hasTags = function () {
  72391. return Tags.HasTags(obj);
  72392. };
  72393. obj.addTags = function (tagsString) {
  72394. return Tags.AddTagsTo(obj, tagsString);
  72395. };
  72396. obj.removeTags = function (tagsString) {
  72397. return Tags.RemoveTagsFrom(obj, tagsString);
  72398. };
  72399. obj.matchesTagsQuery = function (tagsQuery) {
  72400. return Tags.MatchesQuery(obj, tagsQuery);
  72401. };
  72402. };
  72403. Tags.DisableFor = function (obj) {
  72404. delete obj._tags;
  72405. delete obj.hasTags;
  72406. delete obj.addTags;
  72407. delete obj.removeTags;
  72408. delete obj.matchesTagsQuery;
  72409. };
  72410. Tags.HasTags = function (obj) {
  72411. if (!obj._tags) {
  72412. return false;
  72413. }
  72414. return !BABYLON.Tools.IsEmpty(obj._tags);
  72415. };
  72416. Tags.GetTags = function (obj, asString) {
  72417. if (asString === void 0) { asString = true; }
  72418. if (!obj._tags) {
  72419. return null;
  72420. }
  72421. if (asString) {
  72422. var tagsArray = [];
  72423. for (var tag in obj._tags) {
  72424. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  72425. tagsArray.push(tag);
  72426. }
  72427. }
  72428. return tagsArray.join(" ");
  72429. }
  72430. else {
  72431. return obj._tags;
  72432. }
  72433. };
  72434. // the tags 'true' and 'false' are reserved and cannot be used as tags
  72435. // a tag cannot start with '||', '&&', and '!'
  72436. // it cannot contain whitespaces
  72437. Tags.AddTagsTo = function (obj, tagsString) {
  72438. if (!tagsString) {
  72439. return;
  72440. }
  72441. if (typeof tagsString !== "string") {
  72442. return;
  72443. }
  72444. var tags = tagsString.split(" ");
  72445. tags.forEach(function (tag, index, array) {
  72446. Tags._AddTagTo(obj, tag);
  72447. });
  72448. };
  72449. Tags._AddTagTo = function (obj, tag) {
  72450. tag = tag.trim();
  72451. if (tag === "" || tag === "true" || tag === "false") {
  72452. return;
  72453. }
  72454. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  72455. return;
  72456. }
  72457. Tags.EnableFor(obj);
  72458. obj._tags[tag] = true;
  72459. };
  72460. Tags.RemoveTagsFrom = function (obj, tagsString) {
  72461. if (!Tags.HasTags(obj)) {
  72462. return;
  72463. }
  72464. var tags = tagsString.split(" ");
  72465. for (var t in tags) {
  72466. Tags._RemoveTagFrom(obj, tags[t]);
  72467. }
  72468. };
  72469. Tags._RemoveTagFrom = function (obj, tag) {
  72470. delete obj._tags[tag];
  72471. };
  72472. Tags.MatchesQuery = function (obj, tagsQuery) {
  72473. if (tagsQuery === undefined) {
  72474. return true;
  72475. }
  72476. if (tagsQuery === "") {
  72477. return Tags.HasTags(obj);
  72478. }
  72479. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  72480. };
  72481. return Tags;
  72482. }());
  72483. BABYLON.Tags = Tags;
  72484. })(BABYLON || (BABYLON = {}));
  72485. //# sourceMappingURL=babylon.tags.js.map
  72486. var BABYLON;
  72487. (function (BABYLON) {
  72488. /**
  72489. * Class used to evalaute queries containing `and` and `or` operators
  72490. */
  72491. var AndOrNotEvaluator = /** @class */ (function () {
  72492. function AndOrNotEvaluator() {
  72493. }
  72494. /**
  72495. * Evaluate a query
  72496. * @param query defines the query to evaluate
  72497. * @param evaluateCallback defines the callback used to filter result
  72498. * @returns true if the query matches
  72499. */
  72500. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  72501. if (!query.match(/\([^\(\)]*\)/g)) {
  72502. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  72503. }
  72504. else {
  72505. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  72506. // remove parenthesis
  72507. r = r.slice(1, r.length - 1);
  72508. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  72509. });
  72510. }
  72511. if (query === "true") {
  72512. return true;
  72513. }
  72514. if (query === "false") {
  72515. return false;
  72516. }
  72517. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  72518. };
  72519. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  72520. evaluateCallback = evaluateCallback || (function (r) {
  72521. return r === "true" ? true : false;
  72522. });
  72523. var result;
  72524. var or = parenthesisContent.split("||");
  72525. for (var i in or) {
  72526. if (or.hasOwnProperty(i)) {
  72527. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  72528. var and = ori.split("&&");
  72529. if (and.length > 1) {
  72530. for (var j = 0; j < and.length; ++j) {
  72531. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  72532. if (andj !== "true" && andj !== "false") {
  72533. if (andj[0] === "!") {
  72534. result = !evaluateCallback(andj.substring(1));
  72535. }
  72536. else {
  72537. result = evaluateCallback(andj);
  72538. }
  72539. }
  72540. else {
  72541. result = andj === "true" ? true : false;
  72542. }
  72543. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  72544. ori = "false";
  72545. break;
  72546. }
  72547. }
  72548. }
  72549. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  72550. result = true;
  72551. break;
  72552. }
  72553. // result equals false (or undefined)
  72554. if (ori !== "true" && ori !== "false") {
  72555. if (ori[0] === "!") {
  72556. result = !evaluateCallback(ori.substring(1));
  72557. }
  72558. else {
  72559. result = evaluateCallback(ori);
  72560. }
  72561. }
  72562. else {
  72563. result = ori === "true" ? true : false;
  72564. }
  72565. }
  72566. }
  72567. // the whole parenthesis scope is replaced by 'true' or 'false'
  72568. return result ? "true" : "false";
  72569. };
  72570. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  72571. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  72572. // remove whitespaces
  72573. r = r.replace(/[\s]/g, function () { return ""; });
  72574. return r.length % 2 ? "!" : "";
  72575. });
  72576. booleanString = booleanString.trim();
  72577. if (booleanString === "!true") {
  72578. booleanString = "false";
  72579. }
  72580. else if (booleanString === "!false") {
  72581. booleanString = "true";
  72582. }
  72583. return booleanString;
  72584. };
  72585. return AndOrNotEvaluator;
  72586. }());
  72587. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  72588. })(BABYLON || (BABYLON = {}));
  72589. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  72590. var BABYLON;
  72591. (function (BABYLON) {
  72592. /**
  72593. * Class used to enable access to IndexedDB
  72594. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  72595. */
  72596. var Database = /** @class */ (function () {
  72597. /**
  72598. * Creates a new Database
  72599. * @param urlToScene defines the url to load the scene
  72600. * @param callbackManifestChecked defines the callback to use when manifest is checked
  72601. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  72602. */
  72603. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  72604. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  72605. var _this = this;
  72606. // Handling various flavors of prefixed version of IndexedDB
  72607. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  72608. this.callbackManifestChecked = callbackManifestChecked;
  72609. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  72610. this.db = null;
  72611. this._enableSceneOffline = false;
  72612. this._enableTexturesOffline = false;
  72613. this.manifestVersionFound = 0;
  72614. this.mustUpdateRessources = false;
  72615. this.hasReachedQuota = false;
  72616. if (!Database.IDBStorageEnabled) {
  72617. this.callbackManifestChecked(true);
  72618. }
  72619. else {
  72620. if (disableManifestCheck) {
  72621. this._enableSceneOffline = true;
  72622. this._enableTexturesOffline = true;
  72623. this.manifestVersionFound = 1;
  72624. BABYLON.Tools.SetImmediate(function () {
  72625. _this.callbackManifestChecked(true);
  72626. });
  72627. }
  72628. else {
  72629. this._checkManifestFile();
  72630. }
  72631. }
  72632. }
  72633. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  72634. /**
  72635. * Gets a boolean indicating if scene must be saved in the database
  72636. */
  72637. get: function () {
  72638. return this._enableSceneOffline;
  72639. },
  72640. enumerable: true,
  72641. configurable: true
  72642. });
  72643. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  72644. /**
  72645. * Gets a boolean indicating if textures must be saved in the database
  72646. */
  72647. get: function () {
  72648. return this._enableTexturesOffline;
  72649. },
  72650. enumerable: true,
  72651. configurable: true
  72652. });
  72653. Database.prototype._checkManifestFile = function () {
  72654. var _this = this;
  72655. var noManifestFile = function () {
  72656. _this._enableSceneOffline = false;
  72657. _this._enableTexturesOffline = false;
  72658. _this.callbackManifestChecked(false);
  72659. };
  72660. var timeStampUsed = false;
  72661. var manifestURL = this.currentSceneUrl + ".manifest";
  72662. var xhr = new XMLHttpRequest();
  72663. if (navigator.onLine) {
  72664. // Adding a timestamp to by-pass browsers' cache
  72665. timeStampUsed = true;
  72666. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  72667. }
  72668. xhr.open("GET", manifestURL, true);
  72669. xhr.addEventListener("load", function () {
  72670. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  72671. try {
  72672. var manifestFile = JSON.parse(xhr.response);
  72673. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  72674. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  72675. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  72676. _this.manifestVersionFound = manifestFile.version;
  72677. }
  72678. if (_this.callbackManifestChecked) {
  72679. _this.callbackManifestChecked(true);
  72680. }
  72681. }
  72682. catch (ex) {
  72683. noManifestFile();
  72684. }
  72685. }
  72686. else {
  72687. noManifestFile();
  72688. }
  72689. }, false);
  72690. xhr.addEventListener("error", function (event) {
  72691. if (timeStampUsed) {
  72692. timeStampUsed = false;
  72693. // Let's retry without the timeStamp
  72694. // It could fail when coupled with HTML5 Offline API
  72695. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  72696. xhr.open("GET", retryManifestURL, true);
  72697. xhr.send();
  72698. }
  72699. else {
  72700. noManifestFile();
  72701. }
  72702. }, false);
  72703. try {
  72704. xhr.send();
  72705. }
  72706. catch (ex) {
  72707. BABYLON.Tools.Error("Error on XHR send request.");
  72708. this.callbackManifestChecked(false);
  72709. }
  72710. };
  72711. /**
  72712. * Open the database and make it available
  72713. * @param successCallback defines the callback to call on success
  72714. * @param errorCallback defines the callback to call on error
  72715. */
  72716. Database.prototype.openAsync = function (successCallback, errorCallback) {
  72717. var _this = this;
  72718. var handleError = function () {
  72719. _this.isSupported = false;
  72720. if (errorCallback)
  72721. errorCallback();
  72722. };
  72723. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  72724. // Your browser doesn't support IndexedDB
  72725. this.isSupported = false;
  72726. if (errorCallback)
  72727. errorCallback();
  72728. }
  72729. else {
  72730. // If the DB hasn't been opened or created yet
  72731. if (!this.db) {
  72732. this.hasReachedQuota = false;
  72733. this.isSupported = true;
  72734. var request = this.idbFactory.open("babylonjs", 1);
  72735. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  72736. request.onerror = function (event) {
  72737. handleError();
  72738. };
  72739. // executes when a version change transaction cannot complete due to other active transactions
  72740. request.onblocked = function (event) {
  72741. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  72742. handleError();
  72743. };
  72744. // DB has been opened successfully
  72745. request.onsuccess = function (event) {
  72746. _this.db = request.result;
  72747. successCallback();
  72748. };
  72749. // Initialization of the DB. Creating Scenes & Textures stores
  72750. request.onupgradeneeded = function (event) {
  72751. _this.db = (event.target).result;
  72752. if (_this.db) {
  72753. try {
  72754. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  72755. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  72756. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  72757. }
  72758. catch (ex) {
  72759. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  72760. handleError();
  72761. }
  72762. }
  72763. };
  72764. }
  72765. // DB has already been created and opened
  72766. else {
  72767. if (successCallback)
  72768. successCallback();
  72769. }
  72770. }
  72771. };
  72772. /**
  72773. * Loads an image from the database
  72774. * @param url defines the url to load from
  72775. * @param image defines the target DOM image
  72776. */
  72777. Database.prototype.loadImageFromDB = function (url, image) {
  72778. var _this = this;
  72779. var completeURL = Database._ReturnFullUrlLocation(url);
  72780. var saveAndLoadImage = function () {
  72781. if (!_this.hasReachedQuota && _this.db !== null) {
  72782. // the texture is not yet in the DB, let's try to save it
  72783. _this._saveImageIntoDBAsync(completeURL, image);
  72784. }
  72785. // If the texture is not in the DB and we've reached the DB quota limit
  72786. // let's load it directly from the web
  72787. else {
  72788. image.src = url;
  72789. }
  72790. };
  72791. if (!this.mustUpdateRessources) {
  72792. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  72793. }
  72794. // First time we're download the images or update requested in the manifest file by a version change
  72795. else {
  72796. saveAndLoadImage();
  72797. }
  72798. };
  72799. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  72800. if (this.isSupported && this.db !== null) {
  72801. var texture;
  72802. var transaction = this.db.transaction(["textures"]);
  72803. transaction.onabort = function (event) {
  72804. image.src = url;
  72805. };
  72806. transaction.oncomplete = function (event) {
  72807. var blobTextureURL;
  72808. if (texture) {
  72809. var URL = window.URL || window.webkitURL;
  72810. blobTextureURL = URL.createObjectURL(texture.data);
  72811. image.onerror = function () {
  72812. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  72813. image.src = url;
  72814. };
  72815. image.src = blobTextureURL;
  72816. }
  72817. else {
  72818. notInDBCallback();
  72819. }
  72820. };
  72821. var getRequest = transaction.objectStore("textures").get(url);
  72822. getRequest.onsuccess = function (event) {
  72823. texture = (event.target).result;
  72824. };
  72825. getRequest.onerror = function (event) {
  72826. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  72827. image.src = url;
  72828. };
  72829. }
  72830. else {
  72831. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72832. image.src = url;
  72833. }
  72834. };
  72835. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  72836. var _this = this;
  72837. if (this.isSupported) {
  72838. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  72839. var generateBlobUrl = function () {
  72840. var blobTextureURL;
  72841. if (blob) {
  72842. var URL = window.URL || window.webkitURL;
  72843. try {
  72844. blobTextureURL = URL.createObjectURL(blob);
  72845. }
  72846. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  72847. catch (ex) {
  72848. blobTextureURL = URL.createObjectURL(blob);
  72849. }
  72850. }
  72851. if (blobTextureURL) {
  72852. image.src = blobTextureURL;
  72853. }
  72854. };
  72855. if (Database.IsUASupportingBlobStorage) { // Create XHR
  72856. var xhr = new XMLHttpRequest(), blob;
  72857. xhr.open("GET", url, true);
  72858. xhr.responseType = "blob";
  72859. xhr.addEventListener("load", function () {
  72860. if (xhr.status === 200 && _this.db) {
  72861. // Blob as response (XHR2)
  72862. blob = xhr.response;
  72863. var transaction = _this.db.transaction(["textures"], "readwrite");
  72864. // the transaction could abort because of a QuotaExceededError error
  72865. transaction.onabort = function (event) {
  72866. try {
  72867. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72868. var srcElement = (event.srcElement || event.target);
  72869. var error = srcElement.error;
  72870. if (error && error.name === "QuotaExceededError") {
  72871. _this.hasReachedQuota = true;
  72872. }
  72873. }
  72874. catch (ex) { }
  72875. generateBlobUrl();
  72876. };
  72877. transaction.oncomplete = function (event) {
  72878. generateBlobUrl();
  72879. };
  72880. var newTexture = { textureUrl: url, data: blob };
  72881. try {
  72882. // Put the blob into the dabase
  72883. var addRequest = transaction.objectStore("textures").put(newTexture);
  72884. addRequest.onsuccess = function (event) {
  72885. };
  72886. addRequest.onerror = function (event) {
  72887. generateBlobUrl();
  72888. };
  72889. }
  72890. catch (ex) {
  72891. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  72892. if (ex.code === 25) {
  72893. Database.IsUASupportingBlobStorage = false;
  72894. }
  72895. image.src = url;
  72896. }
  72897. }
  72898. else {
  72899. image.src = url;
  72900. }
  72901. }, false);
  72902. xhr.addEventListener("error", function (event) {
  72903. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  72904. image.src = url;
  72905. }, false);
  72906. xhr.send();
  72907. }
  72908. else {
  72909. image.src = url;
  72910. }
  72911. }
  72912. else {
  72913. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72914. image.src = url;
  72915. }
  72916. };
  72917. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  72918. var _this = this;
  72919. var updateVersion = function () {
  72920. // the version is not yet in the DB or we need to update it
  72921. _this._saveVersionIntoDBAsync(url, versionLoaded);
  72922. };
  72923. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  72924. };
  72925. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  72926. var _this = this;
  72927. if (this.isSupported && this.db) {
  72928. var version;
  72929. try {
  72930. var transaction = this.db.transaction(["versions"]);
  72931. transaction.oncomplete = function (event) {
  72932. if (version) {
  72933. // If the version in the JSON file is different from the version in DB
  72934. if (_this.manifestVersionFound !== version.data) {
  72935. _this.mustUpdateRessources = true;
  72936. updateInDBCallback();
  72937. }
  72938. else {
  72939. callback(version.data);
  72940. }
  72941. }
  72942. // version was not found in DB
  72943. else {
  72944. _this.mustUpdateRessources = true;
  72945. updateInDBCallback();
  72946. }
  72947. };
  72948. transaction.onabort = function (event) {
  72949. callback(-1);
  72950. };
  72951. var getRequest = transaction.objectStore("versions").get(url);
  72952. getRequest.onsuccess = function (event) {
  72953. version = (event.target).result;
  72954. };
  72955. getRequest.onerror = function (event) {
  72956. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  72957. callback(-1);
  72958. };
  72959. }
  72960. catch (ex) {
  72961. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  72962. callback(-1);
  72963. }
  72964. }
  72965. else {
  72966. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72967. callback(-1);
  72968. }
  72969. };
  72970. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  72971. var _this = this;
  72972. if (this.isSupported && !this.hasReachedQuota && this.db) {
  72973. try {
  72974. // Open a transaction to the database
  72975. var transaction = this.db.transaction(["versions"], "readwrite");
  72976. // the transaction could abort because of a QuotaExceededError error
  72977. transaction.onabort = function (event) {
  72978. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72979. var error = event.srcElement['error'];
  72980. if (error && error.name === "QuotaExceededError") {
  72981. _this.hasReachedQuota = true;
  72982. }
  72983. }
  72984. catch (ex) { }
  72985. callback(-1);
  72986. };
  72987. transaction.oncomplete = function (event) {
  72988. callback(_this.manifestVersionFound);
  72989. };
  72990. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  72991. // Put the scene into the database
  72992. var addRequest = transaction.objectStore("versions").put(newVersion);
  72993. addRequest.onsuccess = function (event) {
  72994. };
  72995. addRequest.onerror = function (event) {
  72996. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  72997. };
  72998. }
  72999. catch (ex) {
  73000. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  73001. callback(-1);
  73002. }
  73003. }
  73004. else {
  73005. callback(-1);
  73006. }
  73007. };
  73008. /**
  73009. * Loads a file from database
  73010. * @param url defines the URL to load from
  73011. * @param sceneLoaded defines a callback to call on success
  73012. * @param progressCallBack defines a callback to call when progress changed
  73013. * @param errorCallback defines a callback to call on error
  73014. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  73015. */
  73016. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  73017. var _this = this;
  73018. var completeUrl = Database._ReturnFullUrlLocation(url);
  73019. var saveAndLoadFile = function () {
  73020. // the scene is not yet in the DB, let's try to save it
  73021. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73022. };
  73023. this._checkVersionFromDB(completeUrl, function (version) {
  73024. if (version !== -1) {
  73025. if (!_this.mustUpdateRessources) {
  73026. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  73027. }
  73028. else {
  73029. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73030. }
  73031. }
  73032. else {
  73033. if (errorCallback) {
  73034. errorCallback();
  73035. }
  73036. }
  73037. });
  73038. };
  73039. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  73040. if (this.isSupported && this.db) {
  73041. var targetStore;
  73042. if (url.indexOf(".babylon") !== -1) {
  73043. targetStore = "scenes";
  73044. }
  73045. else {
  73046. targetStore = "textures";
  73047. }
  73048. var file;
  73049. var transaction = this.db.transaction([targetStore]);
  73050. transaction.oncomplete = function (event) {
  73051. if (file) {
  73052. callback(file.data);
  73053. }
  73054. // file was not found in DB
  73055. else {
  73056. notInDBCallback();
  73057. }
  73058. };
  73059. transaction.onabort = function (event) {
  73060. notInDBCallback();
  73061. };
  73062. var getRequest = transaction.objectStore(targetStore).get(url);
  73063. getRequest.onsuccess = function (event) {
  73064. file = (event.target).result;
  73065. };
  73066. getRequest.onerror = function (event) {
  73067. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  73068. notInDBCallback();
  73069. };
  73070. }
  73071. else {
  73072. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73073. callback();
  73074. }
  73075. };
  73076. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  73077. var _this = this;
  73078. if (this.isSupported) {
  73079. var targetStore;
  73080. if (url.indexOf(".babylon") !== -1) {
  73081. targetStore = "scenes";
  73082. }
  73083. else {
  73084. targetStore = "textures";
  73085. }
  73086. // Create XHR
  73087. var xhr = new XMLHttpRequest();
  73088. var fileData;
  73089. xhr.open("GET", url + "?" + Date.now(), true);
  73090. if (useArrayBuffer) {
  73091. xhr.responseType = "arraybuffer";
  73092. }
  73093. if (progressCallback) {
  73094. xhr.onprogress = progressCallback;
  73095. }
  73096. xhr.addEventListener("load", function () {
  73097. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  73098. // Blob as response (XHR2)
  73099. //fileData = xhr.responseText;
  73100. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  73101. if (!_this.hasReachedQuota && _this.db) {
  73102. // Open a transaction to the database
  73103. var transaction = _this.db.transaction([targetStore], "readwrite");
  73104. // the transaction could abort because of a QuotaExceededError error
  73105. transaction.onabort = function (event) {
  73106. try {
  73107. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73108. var error = event.srcElement['error'];
  73109. if (error && error.name === "QuotaExceededError") {
  73110. _this.hasReachedQuota = true;
  73111. }
  73112. }
  73113. catch (ex) { }
  73114. callback(fileData);
  73115. };
  73116. transaction.oncomplete = function (event) {
  73117. callback(fileData);
  73118. };
  73119. var newFile;
  73120. if (targetStore === "scenes") {
  73121. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  73122. }
  73123. else {
  73124. newFile = { textureUrl: url, data: fileData };
  73125. }
  73126. try {
  73127. // Put the scene into the database
  73128. var addRequest = transaction.objectStore(targetStore).put(newFile);
  73129. addRequest.onsuccess = function (event) {
  73130. };
  73131. addRequest.onerror = function (event) {
  73132. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  73133. };
  73134. }
  73135. catch (ex) {
  73136. callback(fileData);
  73137. }
  73138. }
  73139. else {
  73140. callback(fileData);
  73141. }
  73142. }
  73143. else {
  73144. if (xhr.status >= 400 && errorCallback) {
  73145. errorCallback(xhr);
  73146. }
  73147. else {
  73148. callback();
  73149. }
  73150. }
  73151. }, false);
  73152. xhr.addEventListener("error", function (event) {
  73153. BABYLON.Tools.Error("error on XHR request.");
  73154. callback();
  73155. }, false);
  73156. xhr.send();
  73157. }
  73158. else {
  73159. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73160. callback();
  73161. }
  73162. };
  73163. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  73164. Database.IsUASupportingBlobStorage = true;
  73165. /** Gets a boolean indicating if Database storate is enabled */
  73166. Database.IDBStorageEnabled = true;
  73167. Database._ParseURL = function (url) {
  73168. var a = document.createElement('a');
  73169. a.href = url;
  73170. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  73171. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  73172. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  73173. return absLocation;
  73174. };
  73175. Database._ReturnFullUrlLocation = function (url) {
  73176. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  73177. return (Database._ParseURL(window.location.href) + url);
  73178. }
  73179. else {
  73180. return url;
  73181. }
  73182. };
  73183. return Database;
  73184. }());
  73185. BABYLON.Database = Database;
  73186. })(BABYLON || (BABYLON = {}));
  73187. //# sourceMappingURL=babylon.database.js.map
  73188. var BABYLON;
  73189. (function (BABYLON) {
  73190. var FresnelParameters = /** @class */ (function () {
  73191. function FresnelParameters() {
  73192. this._isEnabled = true;
  73193. this.leftColor = BABYLON.Color3.White();
  73194. this.rightColor = BABYLON.Color3.Black();
  73195. this.bias = 0;
  73196. this.power = 1;
  73197. }
  73198. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  73199. get: function () {
  73200. return this._isEnabled;
  73201. },
  73202. set: function (value) {
  73203. if (this._isEnabled === value) {
  73204. return;
  73205. }
  73206. this._isEnabled = value;
  73207. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  73208. },
  73209. enumerable: true,
  73210. configurable: true
  73211. });
  73212. FresnelParameters.prototype.clone = function () {
  73213. var newFresnelParameters = new FresnelParameters();
  73214. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  73215. return newFresnelParameters;
  73216. };
  73217. FresnelParameters.prototype.serialize = function () {
  73218. var serializationObject = {};
  73219. serializationObject.isEnabled = this.isEnabled;
  73220. serializationObject.leftColor = this.leftColor.asArray();
  73221. serializationObject.rightColor = this.rightColor.asArray();
  73222. serializationObject.bias = this.bias;
  73223. serializationObject.power = this.power;
  73224. return serializationObject;
  73225. };
  73226. FresnelParameters.Parse = function (parsedFresnelParameters) {
  73227. var fresnelParameters = new FresnelParameters();
  73228. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  73229. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  73230. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  73231. fresnelParameters.bias = parsedFresnelParameters.bias;
  73232. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  73233. return fresnelParameters;
  73234. };
  73235. return FresnelParameters;
  73236. }());
  73237. BABYLON.FresnelParameters = FresnelParameters;
  73238. })(BABYLON || (BABYLON = {}));
  73239. //# sourceMappingURL=babylon.fresnelParameters.js.map
  73240. var BABYLON;
  73241. (function (BABYLON) {
  73242. var MultiMaterial = /** @class */ (function (_super) {
  73243. __extends(MultiMaterial, _super);
  73244. function MultiMaterial(name, scene) {
  73245. var _this = _super.call(this, name, scene, true) || this;
  73246. scene.multiMaterials.push(_this);
  73247. _this.subMaterials = new Array();
  73248. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  73249. return _this;
  73250. }
  73251. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  73252. get: function () {
  73253. return this._subMaterials;
  73254. },
  73255. set: function (value) {
  73256. this._subMaterials = value;
  73257. this._hookArray(value);
  73258. },
  73259. enumerable: true,
  73260. configurable: true
  73261. });
  73262. MultiMaterial.prototype._hookArray = function (array) {
  73263. var _this = this;
  73264. var oldPush = array.push;
  73265. array.push = function () {
  73266. var items = [];
  73267. for (var _i = 0; _i < arguments.length; _i++) {
  73268. items[_i] = arguments[_i];
  73269. }
  73270. var result = oldPush.apply(array, items);
  73271. _this._markAllSubMeshesAsTexturesDirty();
  73272. return result;
  73273. };
  73274. var oldSplice = array.splice;
  73275. array.splice = function (index, deleteCount) {
  73276. var deleted = oldSplice.apply(array, [index, deleteCount]);
  73277. _this._markAllSubMeshesAsTexturesDirty();
  73278. return deleted;
  73279. };
  73280. };
  73281. // Properties
  73282. MultiMaterial.prototype.getSubMaterial = function (index) {
  73283. if (index < 0 || index >= this.subMaterials.length) {
  73284. return this.getScene().defaultMaterial;
  73285. }
  73286. return this.subMaterials[index];
  73287. };
  73288. MultiMaterial.prototype.getActiveTextures = function () {
  73289. var _a;
  73290. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  73291. if (subMaterial) {
  73292. return subMaterial.getActiveTextures();
  73293. }
  73294. else {
  73295. return [];
  73296. }
  73297. }));
  73298. };
  73299. // Methods
  73300. MultiMaterial.prototype.getClassName = function () {
  73301. return "MultiMaterial";
  73302. };
  73303. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  73304. for (var index = 0; index < this.subMaterials.length; index++) {
  73305. var subMaterial = this.subMaterials[index];
  73306. if (subMaterial) {
  73307. if (subMaterial.storeEffectOnSubMeshes) {
  73308. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  73309. return false;
  73310. }
  73311. continue;
  73312. }
  73313. if (!subMaterial.isReady(mesh)) {
  73314. return false;
  73315. }
  73316. }
  73317. }
  73318. return true;
  73319. };
  73320. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  73321. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  73322. for (var index = 0; index < this.subMaterials.length; index++) {
  73323. var subMaterial = null;
  73324. var current = this.subMaterials[index];
  73325. if (cloneChildren && current) {
  73326. subMaterial = current.clone(name + "-" + current.name);
  73327. }
  73328. else {
  73329. subMaterial = this.subMaterials[index];
  73330. }
  73331. newMultiMaterial.subMaterials.push(subMaterial);
  73332. }
  73333. return newMultiMaterial;
  73334. };
  73335. MultiMaterial.prototype.serialize = function () {
  73336. var serializationObject = {};
  73337. serializationObject.name = this.name;
  73338. serializationObject.id = this.id;
  73339. if (BABYLON.Tags) {
  73340. serializationObject.tags = BABYLON.Tags.GetTags(this);
  73341. }
  73342. serializationObject.materials = [];
  73343. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  73344. var subMat = this.subMaterials[matIndex];
  73345. if (subMat) {
  73346. serializationObject.materials.push(subMat.id);
  73347. }
  73348. else {
  73349. serializationObject.materials.push(null);
  73350. }
  73351. }
  73352. return serializationObject;
  73353. };
  73354. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  73355. var scene = this.getScene();
  73356. if (!scene) {
  73357. return;
  73358. }
  73359. var index = scene.multiMaterials.indexOf(this);
  73360. if (index >= 0) {
  73361. scene.multiMaterials.splice(index, 1);
  73362. }
  73363. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  73364. };
  73365. return MultiMaterial;
  73366. }(BABYLON.Material));
  73367. BABYLON.MultiMaterial = MultiMaterial;
  73368. })(BABYLON || (BABYLON = {}));
  73369. //# sourceMappingURL=babylon.multiMaterial.js.map
  73370. var BABYLON;
  73371. (function (BABYLON) {
  73372. var FreeCameraTouchInput = /** @class */ (function () {
  73373. function FreeCameraTouchInput() {
  73374. this._offsetX = null;
  73375. this._offsetY = null;
  73376. this._pointerPressed = new Array();
  73377. this.touchAngularSensibility = 200000.0;
  73378. this.touchMoveSensibility = 250.0;
  73379. }
  73380. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  73381. var _this = this;
  73382. var previousPosition = null;
  73383. if (this._pointerInput === undefined) {
  73384. this._onLostFocus = function (evt) {
  73385. _this._offsetX = null;
  73386. _this._offsetY = null;
  73387. };
  73388. this._pointerInput = function (p, s) {
  73389. var evt = p.event;
  73390. if (evt.pointerType === "mouse") {
  73391. return;
  73392. }
  73393. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73394. if (!noPreventDefault) {
  73395. evt.preventDefault();
  73396. }
  73397. _this._pointerPressed.push(evt.pointerId);
  73398. if (_this._pointerPressed.length !== 1) {
  73399. return;
  73400. }
  73401. previousPosition = {
  73402. x: evt.clientX,
  73403. y: evt.clientY
  73404. };
  73405. }
  73406. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  73407. if (!noPreventDefault) {
  73408. evt.preventDefault();
  73409. }
  73410. var index = _this._pointerPressed.indexOf(evt.pointerId);
  73411. if (index === -1) {
  73412. return;
  73413. }
  73414. _this._pointerPressed.splice(index, 1);
  73415. if (index != 0) {
  73416. return;
  73417. }
  73418. previousPosition = null;
  73419. _this._offsetX = null;
  73420. _this._offsetY = null;
  73421. }
  73422. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  73423. if (!noPreventDefault) {
  73424. evt.preventDefault();
  73425. }
  73426. if (!previousPosition) {
  73427. return;
  73428. }
  73429. var index = _this._pointerPressed.indexOf(evt.pointerId);
  73430. if (index != 0) {
  73431. return;
  73432. }
  73433. _this._offsetX = evt.clientX - previousPosition.x;
  73434. _this._offsetY = -(evt.clientY - previousPosition.y);
  73435. }
  73436. };
  73437. }
  73438. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  73439. if (this._onLostFocus) {
  73440. element.addEventListener("blur", this._onLostFocus);
  73441. }
  73442. };
  73443. FreeCameraTouchInput.prototype.detachControl = function (element) {
  73444. if (this._pointerInput && element) {
  73445. if (this._observer) {
  73446. this.camera.getScene().onPointerObservable.remove(this._observer);
  73447. this._observer = null;
  73448. }
  73449. if (this._onLostFocus) {
  73450. element.removeEventListener("blur", this._onLostFocus);
  73451. this._onLostFocus = null;
  73452. }
  73453. this._pointerPressed = [];
  73454. this._offsetX = null;
  73455. this._offsetY = null;
  73456. }
  73457. };
  73458. FreeCameraTouchInput.prototype.checkInputs = function () {
  73459. if (this._offsetX && this._offsetY) {
  73460. var camera = this.camera;
  73461. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  73462. if (this._pointerPressed.length > 1) {
  73463. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  73464. }
  73465. else {
  73466. var speed = camera._computeLocalCameraSpeed();
  73467. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  73468. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  73469. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  73470. }
  73471. }
  73472. };
  73473. FreeCameraTouchInput.prototype.getClassName = function () {
  73474. return "FreeCameraTouchInput";
  73475. };
  73476. FreeCameraTouchInput.prototype.getSimpleName = function () {
  73477. return "touch";
  73478. };
  73479. __decorate([
  73480. BABYLON.serialize()
  73481. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  73482. __decorate([
  73483. BABYLON.serialize()
  73484. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  73485. return FreeCameraTouchInput;
  73486. }());
  73487. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  73488. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  73489. })(BABYLON || (BABYLON = {}));
  73490. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  73491. var BABYLON;
  73492. (function (BABYLON) {
  73493. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  73494. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  73495. });
  73496. // We're mainly based on the logic defined into the FreeCamera code
  73497. var TouchCamera = /** @class */ (function (_super) {
  73498. __extends(TouchCamera, _super);
  73499. //-- end properties for backward compatibility for inputs
  73500. function TouchCamera(name, position, scene) {
  73501. var _this = _super.call(this, name, position, scene) || this;
  73502. _this.inputs.addTouch();
  73503. _this._setupInputs();
  73504. return _this;
  73505. }
  73506. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  73507. //-- Begin properties for backward compatibility for inputs
  73508. get: function () {
  73509. var touch = this.inputs.attached["touch"];
  73510. if (touch)
  73511. return touch.touchAngularSensibility;
  73512. return 0;
  73513. },
  73514. set: function (value) {
  73515. var touch = this.inputs.attached["touch"];
  73516. if (touch)
  73517. touch.touchAngularSensibility = value;
  73518. },
  73519. enumerable: true,
  73520. configurable: true
  73521. });
  73522. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  73523. get: function () {
  73524. var touch = this.inputs.attached["touch"];
  73525. if (touch)
  73526. return touch.touchMoveSensibility;
  73527. return 0;
  73528. },
  73529. set: function (value) {
  73530. var touch = this.inputs.attached["touch"];
  73531. if (touch)
  73532. touch.touchMoveSensibility = value;
  73533. },
  73534. enumerable: true,
  73535. configurable: true
  73536. });
  73537. TouchCamera.prototype.getClassName = function () {
  73538. return "TouchCamera";
  73539. };
  73540. /** @hidden */
  73541. TouchCamera.prototype._setupInputs = function () {
  73542. var mouse = this.inputs.attached["mouse"];
  73543. if (mouse) {
  73544. mouse.touchEnabled = false;
  73545. }
  73546. };
  73547. return TouchCamera;
  73548. }(BABYLON.FreeCamera));
  73549. BABYLON.TouchCamera = TouchCamera;
  73550. })(BABYLON || (BABYLON = {}));
  73551. //# sourceMappingURL=babylon.touchCamera.js.map
  73552. var BABYLON;
  73553. (function (BABYLON) {
  73554. var ProceduralTexture = /** @class */ (function (_super) {
  73555. __extends(ProceduralTexture, _super);
  73556. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  73557. if (fallbackTexture === void 0) { fallbackTexture = null; }
  73558. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73559. if (isCube === void 0) { isCube = false; }
  73560. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  73561. _this.isCube = isCube;
  73562. _this.isEnabled = true;
  73563. _this._currentRefreshId = -1;
  73564. _this._refreshRate = 1;
  73565. _this._vertexBuffers = {};
  73566. _this._uniforms = new Array();
  73567. _this._samplers = new Array();
  73568. /** @hidden */
  73569. _this._textures = {};
  73570. _this._floats = {};
  73571. _this._ints = {};
  73572. _this._floatsArrays = {};
  73573. _this._colors3 = {};
  73574. _this._colors4 = {};
  73575. _this._vectors2 = {};
  73576. _this._vectors3 = {};
  73577. _this._matrices = {};
  73578. _this._fallbackTextureUsed = false;
  73579. _this._cachedDefines = "";
  73580. scene = _this.getScene();
  73581. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  73582. if (!component) {
  73583. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  73584. scene._addComponent(component);
  73585. }
  73586. scene.proceduralTextures.push(_this);
  73587. _this._engine = scene.getEngine();
  73588. _this.name = name;
  73589. _this.isRenderTarget = true;
  73590. _this._size = size;
  73591. _this._generateMipMaps = generateMipMaps;
  73592. _this.setFragment(fragment);
  73593. _this._fallbackTexture = fallbackTexture;
  73594. if (isCube) {
  73595. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  73596. _this.setFloat("face", 0);
  73597. }
  73598. else {
  73599. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  73600. }
  73601. // VBO
  73602. var vertices = [];
  73603. vertices.push(1, 1);
  73604. vertices.push(-1, 1);
  73605. vertices.push(-1, -1);
  73606. vertices.push(1, -1);
  73607. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73608. _this._createIndexBuffer();
  73609. return _this;
  73610. }
  73611. ProceduralTexture.prototype._createIndexBuffer = function () {
  73612. var engine = this._engine;
  73613. // Indices
  73614. var indices = [];
  73615. indices.push(0);
  73616. indices.push(1);
  73617. indices.push(2);
  73618. indices.push(0);
  73619. indices.push(2);
  73620. indices.push(3);
  73621. this._indexBuffer = engine.createIndexBuffer(indices);
  73622. };
  73623. /** @hidden */
  73624. ProceduralTexture.prototype._rebuild = function () {
  73625. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73626. if (vb) {
  73627. vb._rebuild();
  73628. }
  73629. this._createIndexBuffer();
  73630. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  73631. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  73632. }
  73633. };
  73634. ProceduralTexture.prototype.reset = function () {
  73635. if (this._effect === undefined) {
  73636. return;
  73637. }
  73638. var engine = this._engine;
  73639. engine._releaseEffect(this._effect);
  73640. };
  73641. ProceduralTexture.prototype._getDefines = function () {
  73642. return "";
  73643. };
  73644. ProceduralTexture.prototype.isReady = function () {
  73645. var _this = this;
  73646. var engine = this._engine;
  73647. var shaders;
  73648. if (!this._fragment) {
  73649. return false;
  73650. }
  73651. if (this._fallbackTextureUsed) {
  73652. return true;
  73653. }
  73654. var defines = this._getDefines();
  73655. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  73656. return true;
  73657. }
  73658. if (this._fragment.fragmentElement !== undefined) {
  73659. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  73660. }
  73661. else {
  73662. shaders = { vertex: "procedural", fragment: this._fragment };
  73663. }
  73664. this._cachedDefines = defines;
  73665. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  73666. _this.releaseInternalTexture();
  73667. if (_this._fallbackTexture) {
  73668. _this._texture = _this._fallbackTexture._texture;
  73669. if (_this._texture) {
  73670. _this._texture.incrementReferences();
  73671. }
  73672. }
  73673. _this._fallbackTextureUsed = true;
  73674. });
  73675. return this._effect.isReady();
  73676. };
  73677. ProceduralTexture.prototype.resetRefreshCounter = function () {
  73678. this._currentRefreshId = -1;
  73679. };
  73680. ProceduralTexture.prototype.setFragment = function (fragment) {
  73681. this._fragment = fragment;
  73682. };
  73683. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  73684. get: function () {
  73685. return this._refreshRate;
  73686. },
  73687. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  73688. set: function (value) {
  73689. this._refreshRate = value;
  73690. this.resetRefreshCounter();
  73691. },
  73692. enumerable: true,
  73693. configurable: true
  73694. });
  73695. /** @hidden */
  73696. ProceduralTexture.prototype._shouldRender = function () {
  73697. if (!this.isEnabled || !this.isReady() || !this._texture) {
  73698. return false;
  73699. }
  73700. if (this._fallbackTextureUsed) {
  73701. return false;
  73702. }
  73703. if (this._currentRefreshId === -1) { // At least render once
  73704. this._currentRefreshId = 1;
  73705. return true;
  73706. }
  73707. if (this.refreshRate === this._currentRefreshId) {
  73708. this._currentRefreshId = 1;
  73709. return true;
  73710. }
  73711. this._currentRefreshId++;
  73712. return false;
  73713. };
  73714. ProceduralTexture.prototype.getRenderSize = function () {
  73715. return this._size;
  73716. };
  73717. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  73718. if (this._fallbackTextureUsed) {
  73719. return;
  73720. }
  73721. this.releaseInternalTexture();
  73722. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  73723. // Update properties
  73724. this._size = size;
  73725. this._generateMipMaps = generateMipMaps;
  73726. };
  73727. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  73728. if (this._uniforms.indexOf(uniformName) === -1) {
  73729. this._uniforms.push(uniformName);
  73730. }
  73731. };
  73732. ProceduralTexture.prototype.setTexture = function (name, texture) {
  73733. if (this._samplers.indexOf(name) === -1) {
  73734. this._samplers.push(name);
  73735. }
  73736. this._textures[name] = texture;
  73737. return this;
  73738. };
  73739. ProceduralTexture.prototype.setFloat = function (name, value) {
  73740. this._checkUniform(name);
  73741. this._floats[name] = value;
  73742. return this;
  73743. };
  73744. /**
  73745. * Set the value of an uniform to an integer value
  73746. * @param name defines the name of the uniform
  73747. * @param value defines the value to set
  73748. * @returns the current procedural texture
  73749. */
  73750. ProceduralTexture.prototype.setInt = function (name, value) {
  73751. this._checkUniform(name);
  73752. this._ints[name] = value;
  73753. return this;
  73754. };
  73755. ProceduralTexture.prototype.setFloats = function (name, value) {
  73756. this._checkUniform(name);
  73757. this._floatsArrays[name] = value;
  73758. return this;
  73759. };
  73760. ProceduralTexture.prototype.setColor3 = function (name, value) {
  73761. this._checkUniform(name);
  73762. this._colors3[name] = value;
  73763. return this;
  73764. };
  73765. ProceduralTexture.prototype.setColor4 = function (name, value) {
  73766. this._checkUniform(name);
  73767. this._colors4[name] = value;
  73768. return this;
  73769. };
  73770. ProceduralTexture.prototype.setVector2 = function (name, value) {
  73771. this._checkUniform(name);
  73772. this._vectors2[name] = value;
  73773. return this;
  73774. };
  73775. ProceduralTexture.prototype.setVector3 = function (name, value) {
  73776. this._checkUniform(name);
  73777. this._vectors3[name] = value;
  73778. return this;
  73779. };
  73780. ProceduralTexture.prototype.setMatrix = function (name, value) {
  73781. this._checkUniform(name);
  73782. this._matrices[name] = value;
  73783. return this;
  73784. };
  73785. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  73786. var scene = this.getScene();
  73787. if (!scene) {
  73788. return;
  73789. }
  73790. var engine = this._engine;
  73791. // Render
  73792. engine.enableEffect(this._effect);
  73793. engine.setState(false);
  73794. // Texture
  73795. for (var name in this._textures) {
  73796. this._effect.setTexture(name, this._textures[name]);
  73797. }
  73798. // Float
  73799. for (name in this._ints) {
  73800. this._effect.setInt(name, this._ints[name]);
  73801. }
  73802. // Float
  73803. for (name in this._floats) {
  73804. this._effect.setFloat(name, this._floats[name]);
  73805. }
  73806. // Floats
  73807. for (name in this._floatsArrays) {
  73808. this._effect.setArray(name, this._floatsArrays[name]);
  73809. }
  73810. // Color3
  73811. for (name in this._colors3) {
  73812. this._effect.setColor3(name, this._colors3[name]);
  73813. }
  73814. // Color4
  73815. for (name in this._colors4) {
  73816. var color = this._colors4[name];
  73817. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  73818. }
  73819. // Vector2
  73820. for (name in this._vectors2) {
  73821. this._effect.setVector2(name, this._vectors2[name]);
  73822. }
  73823. // Vector3
  73824. for (name in this._vectors3) {
  73825. this._effect.setVector3(name, this._vectors3[name]);
  73826. }
  73827. // Matrix
  73828. for (name in this._matrices) {
  73829. this._effect.setMatrix(name, this._matrices[name]);
  73830. }
  73831. if (!this._texture) {
  73832. return;
  73833. }
  73834. if (this.isCube) {
  73835. for (var face = 0; face < 6; face++) {
  73836. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  73837. // VBOs
  73838. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73839. this._effect.setFloat("face", face);
  73840. // Clear
  73841. engine.clear(scene.clearColor, true, true, true);
  73842. // Draw order
  73843. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73844. // Mipmaps
  73845. if (face === 5) {
  73846. engine.generateMipMapsForCubemap(this._texture);
  73847. }
  73848. }
  73849. }
  73850. else {
  73851. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  73852. // VBOs
  73853. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73854. // Clear
  73855. engine.clear(scene.clearColor, true, true, true);
  73856. // Draw order
  73857. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73858. }
  73859. // Unbind
  73860. engine.unBindFramebuffer(this._texture, this.isCube);
  73861. if (this.onGenerated) {
  73862. this.onGenerated();
  73863. }
  73864. };
  73865. ProceduralTexture.prototype.clone = function () {
  73866. var textureSize = this.getSize();
  73867. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  73868. // Base texture
  73869. newTexture.hasAlpha = this.hasAlpha;
  73870. newTexture.level = this.level;
  73871. // RenderTarget Texture
  73872. newTexture.coordinatesMode = this.coordinatesMode;
  73873. return newTexture;
  73874. };
  73875. ProceduralTexture.prototype.dispose = function () {
  73876. var scene = this.getScene();
  73877. if (!scene) {
  73878. return;
  73879. }
  73880. var index = scene.proceduralTextures.indexOf(this);
  73881. if (index >= 0) {
  73882. scene.proceduralTextures.splice(index, 1);
  73883. }
  73884. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73885. if (vertexBuffer) {
  73886. vertexBuffer.dispose();
  73887. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73888. }
  73889. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  73890. this._indexBuffer = null;
  73891. }
  73892. _super.prototype.dispose.call(this);
  73893. };
  73894. __decorate([
  73895. BABYLON.serialize()
  73896. ], ProceduralTexture.prototype, "_size", void 0);
  73897. __decorate([
  73898. BABYLON.serialize()
  73899. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  73900. __decorate([
  73901. BABYLON.serialize()
  73902. ], ProceduralTexture.prototype, "isEnabled", void 0);
  73903. __decorate([
  73904. BABYLON.serialize()
  73905. ], ProceduralTexture.prototype, "refreshRate", null);
  73906. return ProceduralTexture;
  73907. }(BABYLON.Texture));
  73908. BABYLON.ProceduralTexture = ProceduralTexture;
  73909. })(BABYLON || (BABYLON = {}));
  73910. //# sourceMappingURL=babylon.proceduralTexture.js.map
  73911. var BABYLON;
  73912. (function (BABYLON) {
  73913. /**
  73914. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  73915. * in a given scene.
  73916. */
  73917. var ProceduralTextureSceneComponent = /** @class */ (function () {
  73918. /**
  73919. * Creates a new instance of the component for the given scene
  73920. * @param scene Defines the scene to register the component in
  73921. */
  73922. function ProceduralTextureSceneComponent(scene) {
  73923. /**
  73924. * The component name helpfull to identify the component in the list of scene components.
  73925. */
  73926. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  73927. this.scene = scene;
  73928. this.scene.proceduralTextures = new Array();
  73929. scene.layers = new Array();
  73930. }
  73931. /**
  73932. * Registers the component in a given scene
  73933. */
  73934. ProceduralTextureSceneComponent.prototype.register = function () {
  73935. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  73936. };
  73937. /**
  73938. * Rebuilds the elements related to this component in case of
  73939. * context lost for instance.
  73940. */
  73941. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  73942. // Nothing to do here.
  73943. };
  73944. /**
  73945. * Disposes the component and the associated ressources.
  73946. */
  73947. ProceduralTextureSceneComponent.prototype.dispose = function () {
  73948. // Nothing to do here.
  73949. };
  73950. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  73951. if (this.scene.proceduralTexturesEnabled) {
  73952. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  73953. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  73954. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  73955. if (proceduralTexture._shouldRender()) {
  73956. proceduralTexture.render();
  73957. }
  73958. }
  73959. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  73960. }
  73961. };
  73962. return ProceduralTextureSceneComponent;
  73963. }());
  73964. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  73965. })(BABYLON || (BABYLON = {}));
  73966. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  73967. var BABYLON;
  73968. (function (BABYLON) {
  73969. var CustomProceduralTexture = /** @class */ (function (_super) {
  73970. __extends(CustomProceduralTexture, _super);
  73971. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  73972. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  73973. _this._animate = true;
  73974. _this._time = 0;
  73975. _this._texturePath = texturePath;
  73976. //Try to load json
  73977. _this.loadJson(texturePath);
  73978. _this.refreshRate = 1;
  73979. return _this;
  73980. }
  73981. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  73982. var _this = this;
  73983. var noConfigFile = function () {
  73984. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  73985. try {
  73986. _this.setFragment(_this._texturePath);
  73987. }
  73988. catch (ex) {
  73989. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  73990. }
  73991. };
  73992. var configFileUrl = jsonUrl + "/config.json";
  73993. var xhr = new XMLHttpRequest();
  73994. xhr.open("GET", configFileUrl, true);
  73995. xhr.addEventListener("load", function () {
  73996. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73997. try {
  73998. _this._config = JSON.parse(xhr.response);
  73999. _this.updateShaderUniforms();
  74000. _this.updateTextures();
  74001. _this.setFragment(_this._texturePath + "/custom");
  74002. _this._animate = _this._config.animate;
  74003. _this.refreshRate = _this._config.refreshrate;
  74004. }
  74005. catch (ex) {
  74006. noConfigFile();
  74007. }
  74008. }
  74009. else {
  74010. noConfigFile();
  74011. }
  74012. }, false);
  74013. xhr.addEventListener("error", function () {
  74014. noConfigFile();
  74015. }, false);
  74016. try {
  74017. xhr.send();
  74018. }
  74019. catch (ex) {
  74020. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  74021. }
  74022. };
  74023. CustomProceduralTexture.prototype.isReady = function () {
  74024. if (!_super.prototype.isReady.call(this)) {
  74025. return false;
  74026. }
  74027. for (var name in this._textures) {
  74028. var texture = this._textures[name];
  74029. if (!texture.isReady()) {
  74030. return false;
  74031. }
  74032. }
  74033. return true;
  74034. };
  74035. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74036. var scene = this.getScene();
  74037. if (this._animate && scene) {
  74038. this._time += scene.getAnimationRatio() * 0.03;
  74039. this.updateShaderUniforms();
  74040. }
  74041. _super.prototype.render.call(this, useCameraPostProcess);
  74042. };
  74043. CustomProceduralTexture.prototype.updateTextures = function () {
  74044. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  74045. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  74046. }
  74047. };
  74048. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  74049. if (this._config) {
  74050. for (var j = 0; j < this._config.uniforms.length; j++) {
  74051. var uniform = this._config.uniforms[j];
  74052. switch (uniform.type) {
  74053. case "float":
  74054. this.setFloat(uniform.name, uniform.value);
  74055. break;
  74056. case "color3":
  74057. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  74058. break;
  74059. case "color4":
  74060. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  74061. break;
  74062. case "vector2":
  74063. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  74064. break;
  74065. case "vector3":
  74066. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  74067. break;
  74068. }
  74069. }
  74070. }
  74071. this.setFloat("time", this._time);
  74072. };
  74073. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  74074. get: function () {
  74075. return this._animate;
  74076. },
  74077. set: function (value) {
  74078. this._animate = value;
  74079. },
  74080. enumerable: true,
  74081. configurable: true
  74082. });
  74083. return CustomProceduralTexture;
  74084. }(BABYLON.ProceduralTexture));
  74085. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  74086. })(BABYLON || (BABYLON = {}));
  74087. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  74088. var BABYLON;
  74089. (function (BABYLON) {
  74090. var FreeCameraGamepadInput = /** @class */ (function () {
  74091. function FreeCameraGamepadInput() {
  74092. this.gamepadAngularSensibility = 200;
  74093. this.gamepadMoveSensibility = 40;
  74094. // private members
  74095. this._cameraTransform = BABYLON.Matrix.Identity();
  74096. this._deltaTransform = BABYLON.Vector3.Zero();
  74097. this._vector3 = BABYLON.Vector3.Zero();
  74098. this._vector2 = BABYLON.Vector2.Zero();
  74099. }
  74100. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74101. var _this = this;
  74102. var manager = this.camera.getScene().gamepadManager;
  74103. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74104. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74105. // prioritize XBOX gamepads.
  74106. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74107. _this.gamepad = gamepad;
  74108. }
  74109. }
  74110. });
  74111. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74112. if (_this.gamepad === gamepad) {
  74113. _this.gamepad = null;
  74114. }
  74115. });
  74116. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74117. };
  74118. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  74119. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74120. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74121. this.gamepad = null;
  74122. };
  74123. FreeCameraGamepadInput.prototype.checkInputs = function () {
  74124. if (this.gamepad && this.gamepad.leftStick) {
  74125. var camera = this.camera;
  74126. var LSValues = this.gamepad.leftStick;
  74127. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  74128. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  74129. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  74130. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  74131. var RSValues = this.gamepad.rightStick;
  74132. if (RSValues) {
  74133. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  74134. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  74135. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  74136. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  74137. }
  74138. else {
  74139. RSValues = { x: 0, y: 0 };
  74140. }
  74141. if (!camera.rotationQuaternion) {
  74142. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  74143. }
  74144. else {
  74145. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  74146. }
  74147. var speed = camera._computeLocalCameraSpeed() * 50.0;
  74148. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  74149. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  74150. camera.cameraDirection.addInPlace(this._deltaTransform);
  74151. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  74152. camera.cameraRotation.addInPlace(this._vector2);
  74153. }
  74154. };
  74155. FreeCameraGamepadInput.prototype.getClassName = function () {
  74156. return "FreeCameraGamepadInput";
  74157. };
  74158. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  74159. return "gamepad";
  74160. };
  74161. __decorate([
  74162. BABYLON.serialize()
  74163. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  74164. __decorate([
  74165. BABYLON.serialize()
  74166. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  74167. return FreeCameraGamepadInput;
  74168. }());
  74169. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  74170. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  74171. })(BABYLON || (BABYLON = {}));
  74172. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  74173. var BABYLON;
  74174. (function (BABYLON) {
  74175. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  74176. function ArcRotateCameraGamepadInput() {
  74177. this.gamepadRotationSensibility = 80;
  74178. this.gamepadMoveSensibility = 40;
  74179. }
  74180. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74181. var _this = this;
  74182. var manager = this.camera.getScene().gamepadManager;
  74183. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74184. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74185. // prioritize XBOX gamepads.
  74186. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74187. _this.gamepad = gamepad;
  74188. }
  74189. }
  74190. });
  74191. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74192. if (_this.gamepad === gamepad) {
  74193. _this.gamepad = null;
  74194. }
  74195. });
  74196. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74197. };
  74198. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  74199. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74200. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74201. this.gamepad = null;
  74202. };
  74203. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  74204. if (this.gamepad) {
  74205. var camera = this.camera;
  74206. var RSValues = this.gamepad.rightStick;
  74207. if (RSValues) {
  74208. if (RSValues.x != 0) {
  74209. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  74210. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  74211. camera.inertialAlphaOffset += normalizedRX;
  74212. }
  74213. }
  74214. if (RSValues.y != 0) {
  74215. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  74216. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  74217. camera.inertialBetaOffset += normalizedRY;
  74218. }
  74219. }
  74220. }
  74221. var LSValues = this.gamepad.leftStick;
  74222. if (LSValues && LSValues.y != 0) {
  74223. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  74224. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  74225. this.camera.inertialRadiusOffset -= normalizedLY;
  74226. }
  74227. }
  74228. }
  74229. };
  74230. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  74231. return "ArcRotateCameraGamepadInput";
  74232. };
  74233. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  74234. return "gamepad";
  74235. };
  74236. __decorate([
  74237. BABYLON.serialize()
  74238. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  74239. __decorate([
  74240. BABYLON.serialize()
  74241. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  74242. return ArcRotateCameraGamepadInput;
  74243. }());
  74244. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  74245. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  74246. })(BABYLON || (BABYLON = {}));
  74247. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  74248. var BABYLON;
  74249. (function (BABYLON) {
  74250. var GamepadManager = /** @class */ (function () {
  74251. function GamepadManager(_scene) {
  74252. var _this = this;
  74253. this._scene = _scene;
  74254. this._babylonGamepads = [];
  74255. this._oneGamepadConnected = false;
  74256. /** @hidden */
  74257. this._isMonitoring = false;
  74258. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  74259. if (!BABYLON.Tools.IsWindowObjectExist()) {
  74260. this._gamepadEventSupported = false;
  74261. }
  74262. else {
  74263. this._gamepadEventSupported = 'GamepadEvent' in window;
  74264. this._gamepadSupport = (navigator.getGamepads ||
  74265. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  74266. }
  74267. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  74268. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  74269. for (var i in _this._babylonGamepads) {
  74270. var gamepad = _this._babylonGamepads[i];
  74271. if (gamepad && gamepad._isConnected) {
  74272. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  74273. }
  74274. }
  74275. });
  74276. this._onGamepadConnectedEvent = function (evt) {
  74277. var gamepad = evt.gamepad;
  74278. if (gamepad.index in _this._babylonGamepads) {
  74279. if (_this._babylonGamepads[gamepad.index].isConnected) {
  74280. return;
  74281. }
  74282. }
  74283. var newGamepad;
  74284. if (_this._babylonGamepads[gamepad.index]) {
  74285. newGamepad = _this._babylonGamepads[gamepad.index];
  74286. newGamepad.browserGamepad = gamepad;
  74287. newGamepad._isConnected = true;
  74288. }
  74289. else {
  74290. newGamepad = _this._addNewGamepad(gamepad);
  74291. }
  74292. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  74293. _this._startMonitoringGamepads();
  74294. };
  74295. this._onGamepadDisconnectedEvent = function (evt) {
  74296. var gamepad = evt.gamepad;
  74297. // Remove the gamepad from the list of gamepads to monitor.
  74298. for (var i in _this._babylonGamepads) {
  74299. if (_this._babylonGamepads[i].index === gamepad.index) {
  74300. var disconnectedGamepad = _this._babylonGamepads[i];
  74301. disconnectedGamepad._isConnected = false;
  74302. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  74303. break;
  74304. }
  74305. }
  74306. };
  74307. if (this._gamepadSupport) {
  74308. //first add already-connected gamepads
  74309. this._updateGamepadObjects();
  74310. if (this._babylonGamepads.length) {
  74311. this._startMonitoringGamepads();
  74312. }
  74313. // Checking if the gamepad connected event is supported (like in Firefox)
  74314. if (this._gamepadEventSupported) {
  74315. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  74316. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  74317. }
  74318. else {
  74319. this._startMonitoringGamepads();
  74320. }
  74321. }
  74322. }
  74323. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  74324. get: function () {
  74325. return this._babylonGamepads;
  74326. },
  74327. enumerable: true,
  74328. configurable: true
  74329. });
  74330. GamepadManager.prototype.getGamepadByType = function (type) {
  74331. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  74332. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  74333. var gamepad = _a[_i];
  74334. if (gamepad && gamepad.type === type) {
  74335. return gamepad;
  74336. }
  74337. }
  74338. return null;
  74339. };
  74340. GamepadManager.prototype.dispose = function () {
  74341. if (this._gamepadEventSupported) {
  74342. if (this._onGamepadConnectedEvent) {
  74343. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  74344. }
  74345. if (this._onGamepadDisconnectedEvent) {
  74346. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  74347. }
  74348. this._onGamepadConnectedEvent = null;
  74349. this._onGamepadDisconnectedEvent = null;
  74350. }
  74351. this._babylonGamepads.forEach(function (gamepad) {
  74352. gamepad.dispose();
  74353. });
  74354. this.onGamepadConnectedObservable.clear();
  74355. this.onGamepadDisconnectedObservable.clear();
  74356. this._oneGamepadConnected = false;
  74357. this._stopMonitoringGamepads();
  74358. this._babylonGamepads = [];
  74359. };
  74360. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  74361. if (!this._oneGamepadConnected) {
  74362. this._oneGamepadConnected = true;
  74363. }
  74364. var newGamepad;
  74365. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  74366. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  74367. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  74368. }
  74369. // if pose is supported, use the (WebVR) pose enabled controller
  74370. else if (gamepad.pose) {
  74371. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  74372. }
  74373. else {
  74374. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  74375. }
  74376. this._babylonGamepads[newGamepad.index] = newGamepad;
  74377. return newGamepad;
  74378. };
  74379. GamepadManager.prototype._startMonitoringGamepads = function () {
  74380. if (!this._isMonitoring) {
  74381. this._isMonitoring = true;
  74382. //back-comp
  74383. if (!this._scene) {
  74384. this._checkGamepadsStatus();
  74385. }
  74386. }
  74387. };
  74388. GamepadManager.prototype._stopMonitoringGamepads = function () {
  74389. this._isMonitoring = false;
  74390. };
  74391. /** @hidden */
  74392. GamepadManager.prototype._checkGamepadsStatus = function () {
  74393. var _this = this;
  74394. // Hack to be compatible Chrome
  74395. this._updateGamepadObjects();
  74396. for (var i in this._babylonGamepads) {
  74397. var gamepad = this._babylonGamepads[i];
  74398. if (!gamepad || !gamepad.isConnected) {
  74399. continue;
  74400. }
  74401. gamepad.update();
  74402. }
  74403. if (this._isMonitoring && !this._scene) {
  74404. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  74405. }
  74406. };
  74407. // This function is called only on Chrome, which does not properly support
  74408. // connection/disconnection events and forces you to recopy again the gamepad object
  74409. GamepadManager.prototype._updateGamepadObjects = function () {
  74410. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  74411. for (var i = 0; i < gamepads.length; i++) {
  74412. var gamepad = gamepads[i];
  74413. if (gamepad) {
  74414. if (!this._babylonGamepads[gamepad.index]) {
  74415. var newGamepad = this._addNewGamepad(gamepad);
  74416. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  74417. }
  74418. else {
  74419. // Forced to copy again this object for Chrome for unknown reason
  74420. this._babylonGamepads[i].browserGamepad = gamepad;
  74421. if (!this._babylonGamepads[i].isConnected) {
  74422. this._babylonGamepads[i]._isConnected = true;
  74423. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  74424. }
  74425. }
  74426. }
  74427. }
  74428. };
  74429. return GamepadManager;
  74430. }());
  74431. BABYLON.GamepadManager = GamepadManager;
  74432. })(BABYLON || (BABYLON = {}));
  74433. //# sourceMappingURL=babylon.gamepadManager.js.map
  74434. var BABYLON;
  74435. (function (BABYLON) {
  74436. var StickValues = /** @class */ (function () {
  74437. function StickValues(x, y) {
  74438. this.x = x;
  74439. this.y = y;
  74440. }
  74441. return StickValues;
  74442. }());
  74443. BABYLON.StickValues = StickValues;
  74444. var Gamepad = /** @class */ (function () {
  74445. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  74446. if (leftStickX === void 0) { leftStickX = 0; }
  74447. if (leftStickY === void 0) { leftStickY = 1; }
  74448. if (rightStickX === void 0) { rightStickX = 2; }
  74449. if (rightStickY === void 0) { rightStickY = 3; }
  74450. this.id = id;
  74451. this.index = index;
  74452. this.browserGamepad = browserGamepad;
  74453. this._leftStick = { x: 0, y: 0 };
  74454. this._rightStick = { x: 0, y: 0 };
  74455. /** @hidden */
  74456. this._isConnected = true;
  74457. this._invertLeftStickY = false;
  74458. this.type = Gamepad.GAMEPAD;
  74459. this._leftStickAxisX = leftStickX;
  74460. this._leftStickAxisY = leftStickY;
  74461. this._rightStickAxisX = rightStickX;
  74462. this._rightStickAxisY = rightStickY;
  74463. if (this.browserGamepad.axes.length >= 2) {
  74464. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  74465. }
  74466. if (this.browserGamepad.axes.length >= 4) {
  74467. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  74468. }
  74469. }
  74470. Object.defineProperty(Gamepad.prototype, "isConnected", {
  74471. get: function () {
  74472. return this._isConnected;
  74473. },
  74474. enumerable: true,
  74475. configurable: true
  74476. });
  74477. Gamepad.prototype.onleftstickchanged = function (callback) {
  74478. this._onleftstickchanged = callback;
  74479. };
  74480. Gamepad.prototype.onrightstickchanged = function (callback) {
  74481. this._onrightstickchanged = callback;
  74482. };
  74483. Object.defineProperty(Gamepad.prototype, "leftStick", {
  74484. get: function () {
  74485. return this._leftStick;
  74486. },
  74487. set: function (newValues) {
  74488. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  74489. this._onleftstickchanged(newValues);
  74490. }
  74491. this._leftStick = newValues;
  74492. },
  74493. enumerable: true,
  74494. configurable: true
  74495. });
  74496. Object.defineProperty(Gamepad.prototype, "rightStick", {
  74497. get: function () {
  74498. return this._rightStick;
  74499. },
  74500. set: function (newValues) {
  74501. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  74502. this._onrightstickchanged(newValues);
  74503. }
  74504. this._rightStick = newValues;
  74505. },
  74506. enumerable: true,
  74507. configurable: true
  74508. });
  74509. Gamepad.prototype.update = function () {
  74510. if (this._leftStick) {
  74511. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  74512. if (this._invertLeftStickY) {
  74513. this.leftStick.y *= -1;
  74514. }
  74515. }
  74516. if (this._rightStick) {
  74517. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  74518. }
  74519. };
  74520. Gamepad.prototype.dispose = function () {
  74521. };
  74522. Gamepad.GAMEPAD = 0;
  74523. Gamepad.GENERIC = 1;
  74524. Gamepad.XBOX = 2;
  74525. Gamepad.POSE_ENABLED = 3;
  74526. return Gamepad;
  74527. }());
  74528. BABYLON.Gamepad = Gamepad;
  74529. var GenericPad = /** @class */ (function (_super) {
  74530. __extends(GenericPad, _super);
  74531. function GenericPad(id, index, browserGamepad) {
  74532. var _this = _super.call(this, id, index, browserGamepad) || this;
  74533. _this.onButtonDownObservable = new BABYLON.Observable();
  74534. _this.onButtonUpObservable = new BABYLON.Observable();
  74535. _this.type = Gamepad.GENERIC;
  74536. _this._buttons = new Array(browserGamepad.buttons.length);
  74537. return _this;
  74538. }
  74539. GenericPad.prototype.onbuttondown = function (callback) {
  74540. this._onbuttondown = callback;
  74541. };
  74542. GenericPad.prototype.onbuttonup = function (callback) {
  74543. this._onbuttonup = callback;
  74544. };
  74545. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  74546. if (newValue !== currentValue) {
  74547. if (newValue === 1) {
  74548. if (this._onbuttondown) {
  74549. this._onbuttondown(buttonIndex);
  74550. }
  74551. this.onButtonDownObservable.notifyObservers(buttonIndex);
  74552. }
  74553. if (newValue === 0) {
  74554. if (this._onbuttonup) {
  74555. this._onbuttonup(buttonIndex);
  74556. }
  74557. this.onButtonUpObservable.notifyObservers(buttonIndex);
  74558. }
  74559. }
  74560. return newValue;
  74561. };
  74562. GenericPad.prototype.update = function () {
  74563. _super.prototype.update.call(this);
  74564. for (var index = 0; index < this._buttons.length; index++) {
  74565. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  74566. }
  74567. };
  74568. GenericPad.prototype.dispose = function () {
  74569. _super.prototype.dispose.call(this);
  74570. this.onButtonDownObservable.clear();
  74571. this.onButtonUpObservable.clear();
  74572. };
  74573. return GenericPad;
  74574. }(Gamepad));
  74575. BABYLON.GenericPad = GenericPad;
  74576. })(BABYLON || (BABYLON = {}));
  74577. //# sourceMappingURL=babylon.gamepad.js.map
  74578. var BABYLON;
  74579. (function (BABYLON) {
  74580. /**
  74581. * Defines supported buttons for XBox360 compatible gamepads
  74582. */
  74583. var Xbox360Button;
  74584. (function (Xbox360Button) {
  74585. /** A */
  74586. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  74587. /** B */
  74588. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  74589. /** X */
  74590. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  74591. /** Y */
  74592. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  74593. /** Start */
  74594. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  74595. /** Back */
  74596. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  74597. /** Left button */
  74598. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  74599. /** Right button */
  74600. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  74601. /** Left stick */
  74602. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  74603. /** Right stick */
  74604. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  74605. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  74606. /** Defines values for XBox360 DPad */
  74607. var Xbox360Dpad;
  74608. (function (Xbox360Dpad) {
  74609. /** Up */
  74610. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  74611. /** Down */
  74612. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  74613. /** Left */
  74614. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  74615. /** Right */
  74616. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  74617. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  74618. /**
  74619. * Defines a XBox360 gamepad
  74620. */
  74621. var Xbox360Pad = /** @class */ (function (_super) {
  74622. __extends(Xbox360Pad, _super);
  74623. /**
  74624. * Creates a new XBox360 gamepad object
  74625. * @param id defines the id of this gamepad
  74626. * @param index defines its index
  74627. * @param gamepad defines the internal HTML gamepad object
  74628. * @param xboxOne defines if it is a XBox One gamepad
  74629. */
  74630. function Xbox360Pad(id, index, gamepad, xboxOne) {
  74631. if (xboxOne === void 0) { xboxOne = false; }
  74632. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  74633. _this._leftTrigger = 0;
  74634. _this._rightTrigger = 0;
  74635. /** Observable raised when a button is pressed */
  74636. _this.onButtonDownObservable = new BABYLON.Observable();
  74637. /** Observable raised when a button is released */
  74638. _this.onButtonUpObservable = new BABYLON.Observable();
  74639. /** Observable raised when a pad is pressed */
  74640. _this.onPadDownObservable = new BABYLON.Observable();
  74641. /** Observable raised when a pad is released */
  74642. _this.onPadUpObservable = new BABYLON.Observable();
  74643. _this._buttonA = 0;
  74644. _this._buttonB = 0;
  74645. _this._buttonX = 0;
  74646. _this._buttonY = 0;
  74647. _this._buttonBack = 0;
  74648. _this._buttonStart = 0;
  74649. _this._buttonLB = 0;
  74650. _this._buttonRB = 0;
  74651. _this._buttonLeftStick = 0;
  74652. _this._buttonRightStick = 0;
  74653. _this._dPadUp = 0;
  74654. _this._dPadDown = 0;
  74655. _this._dPadLeft = 0;
  74656. _this._dPadRight = 0;
  74657. _this._isXboxOnePad = false;
  74658. _this.type = BABYLON.Gamepad.XBOX;
  74659. _this._isXboxOnePad = xboxOne;
  74660. return _this;
  74661. }
  74662. /**
  74663. * Defines the callback to call when left trigger is pressed
  74664. * @param callback defines the callback to use
  74665. */
  74666. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  74667. this._onlefttriggerchanged = callback;
  74668. };
  74669. /**
  74670. * Defines the callback to call when right trigger is pressed
  74671. * @param callback defines the callback to use
  74672. */
  74673. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  74674. this._onrighttriggerchanged = callback;
  74675. };
  74676. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  74677. /**
  74678. * Gets or sets left trigger value
  74679. */
  74680. get: function () {
  74681. return this._leftTrigger;
  74682. },
  74683. set: function (newValue) {
  74684. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  74685. this._onlefttriggerchanged(newValue);
  74686. }
  74687. this._leftTrigger = newValue;
  74688. },
  74689. enumerable: true,
  74690. configurable: true
  74691. });
  74692. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  74693. /**
  74694. * Gets or sets right trigger value
  74695. */
  74696. get: function () {
  74697. return this._rightTrigger;
  74698. },
  74699. set: function (newValue) {
  74700. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  74701. this._onrighttriggerchanged(newValue);
  74702. }
  74703. this._rightTrigger = newValue;
  74704. },
  74705. enumerable: true,
  74706. configurable: true
  74707. });
  74708. /**
  74709. * Defines the callback to call when a button is pressed
  74710. * @param callback defines the callback to use
  74711. */
  74712. Xbox360Pad.prototype.onbuttondown = function (callback) {
  74713. this._onbuttondown = callback;
  74714. };
  74715. /**
  74716. * Defines the callback to call when a button is released
  74717. * @param callback defines the callback to use
  74718. */
  74719. Xbox360Pad.prototype.onbuttonup = function (callback) {
  74720. this._onbuttonup = callback;
  74721. };
  74722. /**
  74723. * Defines the callback to call when a pad is pressed
  74724. * @param callback defines the callback to use
  74725. */
  74726. Xbox360Pad.prototype.ondpaddown = function (callback) {
  74727. this._ondpaddown = callback;
  74728. };
  74729. /**
  74730. * Defines the callback to call when a pad is released
  74731. * @param callback defines the callback to use
  74732. */
  74733. Xbox360Pad.prototype.ondpadup = function (callback) {
  74734. this._ondpadup = callback;
  74735. };
  74736. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  74737. if (newValue !== currentValue) {
  74738. if (newValue === 1) {
  74739. if (this._onbuttondown) {
  74740. this._onbuttondown(buttonType);
  74741. }
  74742. this.onButtonDownObservable.notifyObservers(buttonType);
  74743. }
  74744. if (newValue === 0) {
  74745. if (this._onbuttonup) {
  74746. this._onbuttonup(buttonType);
  74747. }
  74748. this.onButtonUpObservable.notifyObservers(buttonType);
  74749. }
  74750. }
  74751. return newValue;
  74752. };
  74753. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  74754. if (newValue !== currentValue) {
  74755. if (newValue === 1) {
  74756. if (this._ondpaddown) {
  74757. this._ondpaddown(buttonType);
  74758. }
  74759. this.onPadDownObservable.notifyObservers(buttonType);
  74760. }
  74761. if (newValue === 0) {
  74762. if (this._ondpadup) {
  74763. this._ondpadup(buttonType);
  74764. }
  74765. this.onPadUpObservable.notifyObservers(buttonType);
  74766. }
  74767. }
  74768. return newValue;
  74769. };
  74770. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  74771. /** Gets or sets value of A button */
  74772. get: function () {
  74773. return this._buttonA;
  74774. },
  74775. set: function (value) {
  74776. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  74777. },
  74778. enumerable: true,
  74779. configurable: true
  74780. });
  74781. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  74782. /** Gets or sets value of B button */
  74783. get: function () {
  74784. return this._buttonB;
  74785. },
  74786. set: function (value) {
  74787. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  74788. },
  74789. enumerable: true,
  74790. configurable: true
  74791. });
  74792. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  74793. /** Gets or sets value of X button */
  74794. get: function () {
  74795. return this._buttonX;
  74796. },
  74797. set: function (value) {
  74798. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  74799. },
  74800. enumerable: true,
  74801. configurable: true
  74802. });
  74803. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  74804. /** Gets or sets value of Y button */
  74805. get: function () {
  74806. return this._buttonY;
  74807. },
  74808. set: function (value) {
  74809. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  74810. },
  74811. enumerable: true,
  74812. configurable: true
  74813. });
  74814. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  74815. /** Gets or sets value of Start button */
  74816. get: function () {
  74817. return this._buttonStart;
  74818. },
  74819. set: function (value) {
  74820. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  74821. },
  74822. enumerable: true,
  74823. configurable: true
  74824. });
  74825. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  74826. /** Gets or sets value of Back button */
  74827. get: function () {
  74828. return this._buttonBack;
  74829. },
  74830. set: function (value) {
  74831. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  74832. },
  74833. enumerable: true,
  74834. configurable: true
  74835. });
  74836. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  74837. /** Gets or sets value of Left button */
  74838. get: function () {
  74839. return this._buttonLB;
  74840. },
  74841. set: function (value) {
  74842. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  74843. },
  74844. enumerable: true,
  74845. configurable: true
  74846. });
  74847. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  74848. /** Gets or sets value of Right button */
  74849. get: function () {
  74850. return this._buttonRB;
  74851. },
  74852. set: function (value) {
  74853. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  74854. },
  74855. enumerable: true,
  74856. configurable: true
  74857. });
  74858. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  74859. /** Gets or sets value of left stick */
  74860. get: function () {
  74861. return this._buttonLeftStick;
  74862. },
  74863. set: function (value) {
  74864. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  74865. },
  74866. enumerable: true,
  74867. configurable: true
  74868. });
  74869. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  74870. /** Gets or sets value of right stick */
  74871. get: function () {
  74872. return this._buttonRightStick;
  74873. },
  74874. set: function (value) {
  74875. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  74876. },
  74877. enumerable: true,
  74878. configurable: true
  74879. });
  74880. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  74881. /** Gets or sets value of DPad up */
  74882. get: function () {
  74883. return this._dPadUp;
  74884. },
  74885. set: function (value) {
  74886. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  74887. },
  74888. enumerable: true,
  74889. configurable: true
  74890. });
  74891. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  74892. /** Gets or sets value of DPad down */
  74893. get: function () {
  74894. return this._dPadDown;
  74895. },
  74896. set: function (value) {
  74897. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  74898. },
  74899. enumerable: true,
  74900. configurable: true
  74901. });
  74902. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  74903. /** Gets or sets value of DPad left */
  74904. get: function () {
  74905. return this._dPadLeft;
  74906. },
  74907. set: function (value) {
  74908. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  74909. },
  74910. enumerable: true,
  74911. configurable: true
  74912. });
  74913. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  74914. /** Gets or sets value of DPad right */
  74915. get: function () {
  74916. return this._dPadRight;
  74917. },
  74918. set: function (value) {
  74919. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  74920. },
  74921. enumerable: true,
  74922. configurable: true
  74923. });
  74924. /**
  74925. * Force the gamepad to synchronize with device values
  74926. */
  74927. Xbox360Pad.prototype.update = function () {
  74928. _super.prototype.update.call(this);
  74929. if (this._isXboxOnePad) {
  74930. this.buttonA = this.browserGamepad.buttons[0].value;
  74931. this.buttonB = this.browserGamepad.buttons[1].value;
  74932. this.buttonX = this.browserGamepad.buttons[2].value;
  74933. this.buttonY = this.browserGamepad.buttons[3].value;
  74934. this.buttonLB = this.browserGamepad.buttons[4].value;
  74935. this.buttonRB = this.browserGamepad.buttons[5].value;
  74936. this.leftTrigger = this.browserGamepad.axes[2];
  74937. this.rightTrigger = this.browserGamepad.axes[5];
  74938. this.buttonBack = this.browserGamepad.buttons[9].value;
  74939. this.buttonStart = this.browserGamepad.buttons[8].value;
  74940. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  74941. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  74942. this.dPadUp = this.browserGamepad.buttons[11].value;
  74943. this.dPadDown = this.browserGamepad.buttons[12].value;
  74944. this.dPadLeft = this.browserGamepad.buttons[13].value;
  74945. this.dPadRight = this.browserGamepad.buttons[14].value;
  74946. }
  74947. else {
  74948. this.buttonA = this.browserGamepad.buttons[0].value;
  74949. this.buttonB = this.browserGamepad.buttons[1].value;
  74950. this.buttonX = this.browserGamepad.buttons[2].value;
  74951. this.buttonY = this.browserGamepad.buttons[3].value;
  74952. this.buttonLB = this.browserGamepad.buttons[4].value;
  74953. this.buttonRB = this.browserGamepad.buttons[5].value;
  74954. this.leftTrigger = this.browserGamepad.buttons[6].value;
  74955. this.rightTrigger = this.browserGamepad.buttons[7].value;
  74956. this.buttonBack = this.browserGamepad.buttons[8].value;
  74957. this.buttonStart = this.browserGamepad.buttons[9].value;
  74958. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  74959. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  74960. this.dPadUp = this.browserGamepad.buttons[12].value;
  74961. this.dPadDown = this.browserGamepad.buttons[13].value;
  74962. this.dPadLeft = this.browserGamepad.buttons[14].value;
  74963. this.dPadRight = this.browserGamepad.buttons[15].value;
  74964. }
  74965. };
  74966. Xbox360Pad.prototype.dispose = function () {
  74967. _super.prototype.dispose.call(this);
  74968. this.onButtonDownObservable.clear();
  74969. this.onButtonUpObservable.clear();
  74970. this.onPadDownObservable.clear();
  74971. this.onPadUpObservable.clear();
  74972. };
  74973. return Xbox360Pad;
  74974. }(BABYLON.Gamepad));
  74975. BABYLON.Xbox360Pad = Xbox360Pad;
  74976. })(BABYLON || (BABYLON = {}));
  74977. //# sourceMappingURL=babylon.xboxGamepad.js.map
  74978. var BABYLON;
  74979. (function (BABYLON) {
  74980. /**
  74981. * Defines the types of pose enabled controllers that are supported
  74982. */
  74983. var PoseEnabledControllerType;
  74984. (function (PoseEnabledControllerType) {
  74985. /**
  74986. * HTC Vive
  74987. */
  74988. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  74989. /**
  74990. * Oculus Rift
  74991. */
  74992. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  74993. /**
  74994. * Windows mixed reality
  74995. */
  74996. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  74997. /**
  74998. * Samsung gear VR
  74999. */
  75000. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  75001. /**
  75002. * Google Daydream
  75003. */
  75004. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  75005. /**
  75006. * Generic
  75007. */
  75008. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  75009. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  75010. /**
  75011. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75012. */
  75013. var PoseEnabledControllerHelper = /** @class */ (function () {
  75014. function PoseEnabledControllerHelper() {
  75015. }
  75016. /**
  75017. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75018. * @param vrGamepad the gamepad to initialized
  75019. * @returns a vr controller of the type the gamepad identified as
  75020. */
  75021. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  75022. // Oculus Touch
  75023. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  75024. return new BABYLON.OculusTouchController(vrGamepad);
  75025. }
  75026. // Windows Mixed Reality controllers
  75027. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  75028. return new BABYLON.WindowsMotionController(vrGamepad);
  75029. }
  75030. // HTC Vive
  75031. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  75032. return new BABYLON.ViveController(vrGamepad);
  75033. }
  75034. // Samsung/Oculus Gear VR or Oculus Go
  75035. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  75036. return new BABYLON.GearVRController(vrGamepad);
  75037. }
  75038. // Google Daydream
  75039. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  75040. return new BABYLON.DaydreamController(vrGamepad);
  75041. }
  75042. // Generic
  75043. else {
  75044. return new BABYLON.GenericController(vrGamepad);
  75045. }
  75046. };
  75047. return PoseEnabledControllerHelper;
  75048. }());
  75049. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  75050. /**
  75051. * Defines the PoseEnabledController object that contains state of a vr capable controller
  75052. */
  75053. var PoseEnabledController = /** @class */ (function (_super) {
  75054. __extends(PoseEnabledController, _super);
  75055. /**
  75056. * Creates a new PoseEnabledController from a gamepad
  75057. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  75058. */
  75059. function PoseEnabledController(browserGamepad) {
  75060. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  75061. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  75062. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  75063. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  75064. /**
  75065. * The device position in babylon space
  75066. */
  75067. _this.devicePosition = BABYLON.Vector3.Zero();
  75068. /**
  75069. * The device rotation in babylon space
  75070. */
  75071. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  75072. /**
  75073. * The scale factor of the device in babylon space
  75074. */
  75075. _this.deviceScaleFactor = 1;
  75076. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  75077. /**
  75078. * Internal, matrix used to convert room space to babylon space
  75079. * @hidden
  75080. */
  75081. _this._deviceToWorld = BABYLON.Matrix.Identity();
  75082. /**
  75083. * Node to be used when casting a ray from the controller
  75084. * @hidden
  75085. */
  75086. _this._pointingPoseNode = null;
  75087. _this._workingMatrix = BABYLON.Matrix.Identity();
  75088. /**
  75089. * @hidden
  75090. */
  75091. _this._meshAttachedObservable = new BABYLON.Observable();
  75092. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  75093. _this.controllerType = PoseEnabledControllerType.GENERIC;
  75094. _this.position = BABYLON.Vector3.Zero();
  75095. _this.rotationQuaternion = new BABYLON.Quaternion();
  75096. _this._calculatedPosition = BABYLON.Vector3.Zero();
  75097. _this._calculatedRotation = new BABYLON.Quaternion();
  75098. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  75099. return _this;
  75100. }
  75101. /**
  75102. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  75103. */
  75104. PoseEnabledController.prototype.update = function () {
  75105. _super.prototype.update.call(this);
  75106. this._updatePoseAndMesh();
  75107. };
  75108. /**
  75109. * Updates only the pose device and mesh without doing any button event checking
  75110. */
  75111. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  75112. var pose = this.browserGamepad.pose;
  75113. this.updateFromDevice(pose);
  75114. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  75115. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  75116. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  75117. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  75118. if (this._mesh) {
  75119. this._mesh.position.copyFrom(this.devicePosition);
  75120. if (this._mesh.rotationQuaternion) {
  75121. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  75122. }
  75123. }
  75124. };
  75125. /**
  75126. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75127. * @param poseData raw pose fromthe device
  75128. */
  75129. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  75130. if (poseData) {
  75131. this.rawPose = poseData;
  75132. if (poseData.position) {
  75133. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  75134. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  75135. this._deviceRoomPosition.z *= -1;
  75136. }
  75137. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  75138. this._calculatedPosition.addInPlace(this.position);
  75139. }
  75140. var pose = this.rawPose;
  75141. if (poseData.orientation && pose.orientation) {
  75142. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  75143. if (this._mesh) {
  75144. if (this._mesh.getScene().useRightHandedSystem) {
  75145. this._deviceRoomRotationQuaternion.z *= -1;
  75146. this._deviceRoomRotationQuaternion.w *= -1;
  75147. }
  75148. else {
  75149. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  75150. }
  75151. }
  75152. // if the camera is set, rotate to the camera's rotation
  75153. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  75154. }
  75155. }
  75156. };
  75157. /**
  75158. * Attaches a mesh to the controller
  75159. * @param mesh the mesh to be attached
  75160. */
  75161. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  75162. if (this._mesh) {
  75163. this._mesh.parent = null;
  75164. }
  75165. this._mesh = mesh;
  75166. if (this._poseControlledCamera) {
  75167. this._mesh.parent = this._poseControlledCamera;
  75168. }
  75169. if (!this._mesh.rotationQuaternion) {
  75170. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  75171. }
  75172. // 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
  75173. this._updatePoseAndMesh();
  75174. if (this._pointingPoseNode) {
  75175. var parents = [];
  75176. var obj = this._pointingPoseNode;
  75177. while (obj.parent) {
  75178. parents.push(obj.parent);
  75179. obj = obj.parent;
  75180. }
  75181. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  75182. }
  75183. this._meshAttachedObservable.notifyObservers(mesh);
  75184. };
  75185. /**
  75186. * Attaches the controllers mesh to a camera
  75187. * @param camera the camera the mesh should be attached to
  75188. */
  75189. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  75190. this._poseControlledCamera = camera;
  75191. if (this._mesh) {
  75192. this._mesh.parent = this._poseControlledCamera;
  75193. }
  75194. };
  75195. /**
  75196. * Disposes of the controller
  75197. */
  75198. PoseEnabledController.prototype.dispose = function () {
  75199. if (this._mesh) {
  75200. this._mesh.dispose();
  75201. }
  75202. this._mesh = null;
  75203. _super.prototype.dispose.call(this);
  75204. };
  75205. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  75206. /**
  75207. * The mesh that is attached to the controller
  75208. */
  75209. get: function () {
  75210. return this._mesh;
  75211. },
  75212. enumerable: true,
  75213. configurable: true
  75214. });
  75215. /**
  75216. * Gets the ray of the controller in the direction the controller is pointing
  75217. * @param length the length the resulting ray should be
  75218. * @returns a ray in the direction the controller is pointing
  75219. */
  75220. PoseEnabledController.prototype.getForwardRay = function (length) {
  75221. if (length === void 0) { length = 100; }
  75222. if (!this.mesh) {
  75223. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  75224. }
  75225. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  75226. var origin = m.getTranslation();
  75227. var forward = new BABYLON.Vector3(0, 0, -1);
  75228. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  75229. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  75230. return new BABYLON.Ray(origin, direction, length);
  75231. };
  75232. /**
  75233. * Name of the child mesh that can be used to cast a ray from the controller
  75234. */
  75235. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  75236. return PoseEnabledController;
  75237. }(BABYLON.Gamepad));
  75238. BABYLON.PoseEnabledController = PoseEnabledController;
  75239. })(BABYLON || (BABYLON = {}));
  75240. //# sourceMappingURL=babylon.poseEnabledController.js.map
  75241. var BABYLON;
  75242. (function (BABYLON) {
  75243. /**
  75244. * Defines the WebVRController object that represents controllers tracked in 3D space
  75245. */
  75246. var WebVRController = /** @class */ (function (_super) {
  75247. __extends(WebVRController, _super);
  75248. /**
  75249. * Creates a new WebVRController from a gamepad
  75250. * @param vrGamepad the gamepad that the WebVRController should be created from
  75251. */
  75252. function WebVRController(vrGamepad) {
  75253. var _this = _super.call(this, vrGamepad) || this;
  75254. // Observables
  75255. /**
  75256. * Fired when the trigger state has changed
  75257. */
  75258. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  75259. /**
  75260. * Fired when the main button state has changed
  75261. */
  75262. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  75263. /**
  75264. * Fired when the secondary button state has changed
  75265. */
  75266. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  75267. /**
  75268. * Fired when the pad state has changed
  75269. */
  75270. _this.onPadStateChangedObservable = new BABYLON.Observable();
  75271. /**
  75272. * Fired when controllers stick values have changed
  75273. */
  75274. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  75275. /**
  75276. * X and Y axis corrisponding to the controllers joystick
  75277. */
  75278. _this.pad = { x: 0, y: 0 };
  75279. // avoid GC, store state in a tmp object
  75280. _this._changes = {
  75281. pressChanged: false,
  75282. touchChanged: false,
  75283. valueChanged: false,
  75284. changed: false
  75285. };
  75286. _this._buttons = new Array(vrGamepad.buttons.length);
  75287. _this.hand = vrGamepad.hand;
  75288. return _this;
  75289. }
  75290. /**
  75291. * Fired when a controller button's state has changed
  75292. * @param callback the callback containing the button that was modified
  75293. */
  75294. WebVRController.prototype.onButtonStateChange = function (callback) {
  75295. this._onButtonStateChange = callback;
  75296. };
  75297. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  75298. /**
  75299. * The default controller model for the controller
  75300. */
  75301. get: function () {
  75302. return this._defaultModel;
  75303. },
  75304. enumerable: true,
  75305. configurable: true
  75306. });
  75307. /**
  75308. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  75309. */
  75310. WebVRController.prototype.update = function () {
  75311. _super.prototype.update.call(this);
  75312. for (var index = 0; index < this._buttons.length; index++) {
  75313. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  75314. }
  75315. ;
  75316. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  75317. this.pad.x = this.leftStick.x;
  75318. this.pad.y = this.leftStick.y;
  75319. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  75320. }
  75321. };
  75322. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  75323. if (!newState) {
  75324. newState = {
  75325. pressed: false,
  75326. touched: false,
  75327. value: 0
  75328. };
  75329. }
  75330. if (!currentState) {
  75331. this._buttons[buttonIndex] = {
  75332. pressed: newState.pressed,
  75333. touched: newState.touched,
  75334. value: newState.value
  75335. };
  75336. return;
  75337. }
  75338. this._checkChanges(newState, currentState);
  75339. if (this._changes.changed) {
  75340. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  75341. this._handleButtonChange(buttonIndex, newState, this._changes);
  75342. }
  75343. this._buttons[buttonIndex].pressed = newState.pressed;
  75344. this._buttons[buttonIndex].touched = newState.touched;
  75345. // oculus triggers are never 0, thou not touched.
  75346. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  75347. };
  75348. WebVRController.prototype._checkChanges = function (newState, currentState) {
  75349. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  75350. this._changes.touchChanged = newState.touched !== currentState.touched;
  75351. this._changes.valueChanged = newState.value !== currentState.value;
  75352. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  75353. return this._changes;
  75354. };
  75355. /**
  75356. * Disposes of th webVRCOntroller
  75357. */
  75358. WebVRController.prototype.dispose = function () {
  75359. _super.prototype.dispose.call(this);
  75360. this.onTriggerStateChangedObservable.clear();
  75361. this.onMainButtonStateChangedObservable.clear();
  75362. this.onSecondaryButtonStateChangedObservable.clear();
  75363. this.onPadStateChangedObservable.clear();
  75364. this.onPadValuesChangedObservable.clear();
  75365. };
  75366. return WebVRController;
  75367. }(BABYLON.PoseEnabledController));
  75368. BABYLON.WebVRController = WebVRController;
  75369. })(BABYLON || (BABYLON = {}));
  75370. //# sourceMappingURL=babylon.webVRController.js.map
  75371. var BABYLON;
  75372. (function (BABYLON) {
  75373. /**
  75374. * Oculus Touch Controller
  75375. */
  75376. var OculusTouchController = /** @class */ (function (_super) {
  75377. __extends(OculusTouchController, _super);
  75378. /**
  75379. * Creates a new OculusTouchController from a gamepad
  75380. * @param vrGamepad the gamepad that the controller should be created from
  75381. */
  75382. function OculusTouchController(vrGamepad) {
  75383. var _this = _super.call(this, vrGamepad) || this;
  75384. /**
  75385. * Fired when the secondary trigger on this controller is modified
  75386. */
  75387. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  75388. /**
  75389. * Fired when the thumb rest on this controller is modified
  75390. */
  75391. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  75392. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  75393. return _this;
  75394. }
  75395. /**
  75396. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75397. * @param scene scene in which to add meshes
  75398. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75399. */
  75400. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75401. var _this = this;
  75402. var meshName;
  75403. // Hand
  75404. if (this.hand === 'left') {
  75405. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  75406. }
  75407. else { // Right is the default if no hand is specified
  75408. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  75409. }
  75410. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  75411. /*
  75412. Parent Mesh name: oculus_touch_left
  75413. - body
  75414. - trigger
  75415. - thumbstick
  75416. - grip
  75417. - button_y
  75418. - button_x
  75419. - button_enter
  75420. */
  75421. _this._defaultModel = newMeshes[1];
  75422. _this.attachToMesh(_this._defaultModel);
  75423. if (meshLoaded) {
  75424. meshLoaded(_this._defaultModel);
  75425. }
  75426. });
  75427. };
  75428. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  75429. /**
  75430. * Fired when the A button on this controller is modified
  75431. */
  75432. get: function () {
  75433. if (this.hand === 'right') {
  75434. return this.onMainButtonStateChangedObservable;
  75435. }
  75436. else {
  75437. throw new Error('No A button on left hand');
  75438. }
  75439. },
  75440. enumerable: true,
  75441. configurable: true
  75442. });
  75443. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  75444. /**
  75445. * Fired when the B button on this controller is modified
  75446. */
  75447. get: function () {
  75448. if (this.hand === 'right') {
  75449. return this.onSecondaryButtonStateChangedObservable;
  75450. }
  75451. else {
  75452. throw new Error('No B button on left hand');
  75453. }
  75454. },
  75455. enumerable: true,
  75456. configurable: true
  75457. });
  75458. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  75459. /**
  75460. * Fired when the X button on this controller is modified
  75461. */
  75462. get: function () {
  75463. if (this.hand === 'left') {
  75464. return this.onMainButtonStateChangedObservable;
  75465. }
  75466. else {
  75467. throw new Error('No X button on right hand');
  75468. }
  75469. },
  75470. enumerable: true,
  75471. configurable: true
  75472. });
  75473. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  75474. /**
  75475. * Fired when the Y button on this controller is modified
  75476. */
  75477. get: function () {
  75478. if (this.hand === 'left') {
  75479. return this.onSecondaryButtonStateChangedObservable;
  75480. }
  75481. else {
  75482. throw new Error('No Y button on right hand');
  75483. }
  75484. },
  75485. enumerable: true,
  75486. configurable: true
  75487. });
  75488. /**
  75489. * Called once for each button that changed state since the last frame
  75490. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  75491. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  75492. * 2) secondary trigger (same)
  75493. * 3) A (right) X (left), touch, pressed = value
  75494. * 4) B / Y
  75495. * 5) thumb rest
  75496. * @param buttonIdx Which button index changed
  75497. * @param state New state of the button
  75498. * @param changes Which properties on the state changed since last frame
  75499. */
  75500. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75501. var notifyObject = state; //{ state: state, changes: changes };
  75502. var triggerDirection = this.hand === 'right' ? -1 : 1;
  75503. switch (buttonIdx) {
  75504. case 0:
  75505. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  75506. return;
  75507. case 1: // index trigger
  75508. if (this._defaultModel) {
  75509. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  75510. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  75511. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  75512. }
  75513. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  75514. return;
  75515. case 2: // secondary trigger
  75516. if (this._defaultModel) {
  75517. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  75518. }
  75519. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  75520. return;
  75521. case 3:
  75522. if (this._defaultModel) {
  75523. if (notifyObject.pressed) {
  75524. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  75525. }
  75526. else {
  75527. (this._defaultModel.getChildren()[1]).position.y = 0;
  75528. }
  75529. }
  75530. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  75531. return;
  75532. case 4:
  75533. if (this._defaultModel) {
  75534. if (notifyObject.pressed) {
  75535. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  75536. }
  75537. else {
  75538. (this._defaultModel.getChildren()[2]).position.y = 0;
  75539. }
  75540. }
  75541. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  75542. return;
  75543. case 5:
  75544. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  75545. return;
  75546. }
  75547. };
  75548. /**
  75549. * Base Url for the controller model.
  75550. */
  75551. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  75552. /**
  75553. * File name for the left controller model.
  75554. */
  75555. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  75556. /**
  75557. * File name for the right controller model.
  75558. */
  75559. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  75560. return OculusTouchController;
  75561. }(BABYLON.WebVRController));
  75562. BABYLON.OculusTouchController = OculusTouchController;
  75563. })(BABYLON || (BABYLON = {}));
  75564. //# sourceMappingURL=babylon.oculusTouchController.js.map
  75565. var BABYLON;
  75566. (function (BABYLON) {
  75567. /**
  75568. * Vive Controller
  75569. */
  75570. var ViveController = /** @class */ (function (_super) {
  75571. __extends(ViveController, _super);
  75572. /**
  75573. * Creates a new ViveController from a gamepad
  75574. * @param vrGamepad the gamepad that the controller should be created from
  75575. */
  75576. function ViveController(vrGamepad) {
  75577. var _this = _super.call(this, vrGamepad) || this;
  75578. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  75579. _this._invertLeftStickY = true;
  75580. return _this;
  75581. }
  75582. /**
  75583. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75584. * @param scene scene in which to add meshes
  75585. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75586. */
  75587. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75588. var _this = this;
  75589. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  75590. /*
  75591. Parent Mesh name: ViveWand
  75592. - body
  75593. - r_gripper
  75594. - l_gripper
  75595. - menu_button
  75596. - system_button
  75597. - trackpad
  75598. - trigger
  75599. - LED
  75600. */
  75601. _this._defaultModel = newMeshes[1];
  75602. _this.attachToMesh(_this._defaultModel);
  75603. if (meshLoaded) {
  75604. meshLoaded(_this._defaultModel);
  75605. }
  75606. });
  75607. };
  75608. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  75609. /**
  75610. * Fired when the left button on this controller is modified
  75611. */
  75612. get: function () {
  75613. return this.onMainButtonStateChangedObservable;
  75614. },
  75615. enumerable: true,
  75616. configurable: true
  75617. });
  75618. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  75619. /**
  75620. * Fired when the right button on this controller is modified
  75621. */
  75622. get: function () {
  75623. return this.onMainButtonStateChangedObservable;
  75624. },
  75625. enumerable: true,
  75626. configurable: true
  75627. });
  75628. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  75629. /**
  75630. * Fired when the menu button on this controller is modified
  75631. */
  75632. get: function () {
  75633. return this.onSecondaryButtonStateChangedObservable;
  75634. },
  75635. enumerable: true,
  75636. configurable: true
  75637. });
  75638. /**
  75639. * Called once for each button that changed state since the last frame
  75640. * Vive mapping:
  75641. * 0: touchpad
  75642. * 1: trigger
  75643. * 2: left AND right buttons
  75644. * 3: menu button
  75645. * @param buttonIdx Which button index changed
  75646. * @param state New state of the button
  75647. * @param changes Which properties on the state changed since last frame
  75648. */
  75649. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75650. var notifyObject = state; //{ state: state, changes: changes };
  75651. switch (buttonIdx) {
  75652. case 0:
  75653. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  75654. return;
  75655. case 1: // index trigger
  75656. if (this._defaultModel) {
  75657. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  75658. }
  75659. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  75660. return;
  75661. case 2: // left AND right button
  75662. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  75663. return;
  75664. case 3:
  75665. if (this._defaultModel) {
  75666. if (notifyObject.pressed) {
  75667. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  75668. }
  75669. else {
  75670. (this._defaultModel.getChildren()[2]).position.y = 0;
  75671. }
  75672. }
  75673. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  75674. return;
  75675. }
  75676. };
  75677. /**
  75678. * Base Url for the controller model.
  75679. */
  75680. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  75681. /**
  75682. * File name for the controller model.
  75683. */
  75684. ViveController.MODEL_FILENAME = 'wand.babylon';
  75685. return ViveController;
  75686. }(BABYLON.WebVRController));
  75687. BABYLON.ViveController = ViveController;
  75688. })(BABYLON || (BABYLON = {}));
  75689. //# sourceMappingURL=babylon.viveController.js.map
  75690. var BABYLON;
  75691. (function (BABYLON) {
  75692. /**
  75693. * Generic Controller
  75694. */
  75695. var GenericController = /** @class */ (function (_super) {
  75696. __extends(GenericController, _super);
  75697. /**
  75698. * Creates a new GenericController from a gamepad
  75699. * @param vrGamepad the gamepad that the controller should be created from
  75700. */
  75701. function GenericController(vrGamepad) {
  75702. return _super.call(this, vrGamepad) || this;
  75703. }
  75704. /**
  75705. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75706. * @param scene scene in which to add meshes
  75707. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75708. */
  75709. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75710. var _this = this;
  75711. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  75712. _this._defaultModel = newMeshes[1];
  75713. _this.attachToMesh(_this._defaultModel);
  75714. if (meshLoaded) {
  75715. meshLoaded(_this._defaultModel);
  75716. }
  75717. });
  75718. };
  75719. /**
  75720. * Called once for each button that changed state since the last frame
  75721. * @param buttonIdx Which button index changed
  75722. * @param state New state of the button
  75723. * @param changes Which properties on the state changed since last frame
  75724. */
  75725. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75726. console.log("Button id: " + buttonIdx + "state: ");
  75727. console.dir(state);
  75728. };
  75729. /**
  75730. * Base Url for the controller model.
  75731. */
  75732. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75733. /**
  75734. * File name for the controller model.
  75735. */
  75736. GenericController.MODEL_FILENAME = 'generic.babylon';
  75737. return GenericController;
  75738. }(BABYLON.WebVRController));
  75739. BABYLON.GenericController = GenericController;
  75740. })(BABYLON || (BABYLON = {}));
  75741. //# sourceMappingURL=babylon.genericController.js.map
  75742. var BABYLON;
  75743. (function (BABYLON) {
  75744. /**
  75745. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  75746. */
  75747. var LoadedMeshInfo = /** @class */ (function () {
  75748. function LoadedMeshInfo() {
  75749. /**
  75750. * Map of the button meshes contained in the controller
  75751. */
  75752. this.buttonMeshes = {};
  75753. /**
  75754. * Map of the axis meshes contained in the controller
  75755. */
  75756. this.axisMeshes = {};
  75757. }
  75758. return LoadedMeshInfo;
  75759. }());
  75760. /**
  75761. * Defines the WindowsMotionController object that the state of the windows motion controller
  75762. */
  75763. var WindowsMotionController = /** @class */ (function (_super) {
  75764. __extends(WindowsMotionController, _super);
  75765. /**
  75766. * Creates a new WindowsMotionController from a gamepad
  75767. * @param vrGamepad the gamepad that the controller should be created from
  75768. */
  75769. function WindowsMotionController(vrGamepad) {
  75770. var _this = _super.call(this, vrGamepad) || this;
  75771. _this._mapping = {
  75772. // Semantic button names
  75773. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  75774. // A mapping of the button name to glTF model node name
  75775. // that should be transformed by button value.
  75776. buttonMeshNames: {
  75777. 'trigger': 'SELECT',
  75778. 'menu': 'MENU',
  75779. 'grip': 'GRASP',
  75780. 'thumbstick': 'THUMBSTICK_PRESS',
  75781. 'trackpad': 'TOUCHPAD_PRESS'
  75782. },
  75783. // This mapping is used to translate from the Motion Controller to Babylon semantics
  75784. buttonObservableNames: {
  75785. 'trigger': 'onTriggerStateChangedObservable',
  75786. 'menu': 'onSecondaryButtonStateChangedObservable',
  75787. 'grip': 'onMainButtonStateChangedObservable',
  75788. 'thumbstick': 'onPadStateChangedObservable',
  75789. 'trackpad': 'onTrackpadChangedObservable'
  75790. },
  75791. // A mapping of the axis name to glTF model node name
  75792. // that should be transformed by axis value.
  75793. // This array mirrors the browserGamepad.axes array, such that
  75794. // the mesh corresponding to axis 0 is in this array index 0.
  75795. axisMeshNames: [
  75796. 'THUMBSTICK_X',
  75797. 'THUMBSTICK_Y',
  75798. 'TOUCHPAD_TOUCH_X',
  75799. 'TOUCHPAD_TOUCH_Y'
  75800. ],
  75801. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  75802. };
  75803. /**
  75804. * Fired when the trackpad on this controller is clicked
  75805. */
  75806. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  75807. /**
  75808. * Fired when the trackpad on this controller is modified
  75809. */
  75810. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  75811. /**
  75812. * The current x and y values of this controller's trackpad
  75813. */
  75814. _this.trackpad = { x: 0, y: 0 };
  75815. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  75816. _this._loadedMeshInfo = null;
  75817. return _this;
  75818. }
  75819. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  75820. /**
  75821. * Fired when the trigger on this controller is modified
  75822. */
  75823. get: function () {
  75824. return this.onTriggerStateChangedObservable;
  75825. },
  75826. enumerable: true,
  75827. configurable: true
  75828. });
  75829. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  75830. /**
  75831. * Fired when the menu button on this controller is modified
  75832. */
  75833. get: function () {
  75834. return this.onSecondaryButtonStateChangedObservable;
  75835. },
  75836. enumerable: true,
  75837. configurable: true
  75838. });
  75839. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  75840. /**
  75841. * Fired when the grip button on this controller is modified
  75842. */
  75843. get: function () {
  75844. return this.onMainButtonStateChangedObservable;
  75845. },
  75846. enumerable: true,
  75847. configurable: true
  75848. });
  75849. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  75850. /**
  75851. * Fired when the thumbstick button on this controller is modified
  75852. */
  75853. get: function () {
  75854. return this.onPadStateChangedObservable;
  75855. },
  75856. enumerable: true,
  75857. configurable: true
  75858. });
  75859. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  75860. /**
  75861. * Fired when the touchpad button on this controller is modified
  75862. */
  75863. get: function () {
  75864. return this.onTrackpadChangedObservable;
  75865. },
  75866. enumerable: true,
  75867. configurable: true
  75868. });
  75869. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  75870. /**
  75871. * Fired when the touchpad values on this controller are modified
  75872. */
  75873. get: function () {
  75874. return this.onTrackpadValuesChangedObservable;
  75875. },
  75876. enumerable: true,
  75877. configurable: true
  75878. });
  75879. WindowsMotionController.prototype._updateTrackpad = function () {
  75880. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  75881. this.trackpad.x = this.browserGamepad["axes"][2];
  75882. this.trackpad.y = this.browserGamepad["axes"][3];
  75883. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  75884. }
  75885. };
  75886. /**
  75887. * Called once per frame by the engine.
  75888. */
  75889. WindowsMotionController.prototype.update = function () {
  75890. _super.prototype.update.call(this);
  75891. if (this.browserGamepad.axes) {
  75892. this._updateTrackpad();
  75893. // Only need to animate axes if there is a loaded mesh
  75894. if (this._loadedMeshInfo) {
  75895. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  75896. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  75897. }
  75898. }
  75899. }
  75900. };
  75901. /**
  75902. * Called once for each button that changed state since the last frame
  75903. * @param buttonIdx Which button index changed
  75904. * @param state New state of the button
  75905. * @param changes Which properties on the state changed since last frame
  75906. */
  75907. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75908. var buttonName = this._mapping.buttons[buttonIdx];
  75909. if (!buttonName) {
  75910. return;
  75911. }
  75912. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  75913. this._updateTrackpad();
  75914. // Only emit events for buttons that we know how to map from index to name
  75915. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  75916. if (observable) {
  75917. observable.notifyObservers(state);
  75918. }
  75919. this._lerpButtonTransform(buttonName, state.value);
  75920. };
  75921. /**
  75922. * Moves the buttons on the controller mesh based on their current state
  75923. * @param buttonName the name of the button to move
  75924. * @param buttonValue the value of the button which determines the buttons new position
  75925. */
  75926. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  75927. // If there is no loaded mesh, there is nothing to transform.
  75928. if (!this._loadedMeshInfo) {
  75929. return;
  75930. }
  75931. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  75932. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75933. return;
  75934. }
  75935. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  75936. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  75937. };
  75938. /**
  75939. * Moves the axis on the controller mesh based on its current state
  75940. * @param axis the index of the axis
  75941. * @param axisValue the value of the axis which determines the meshes new position
  75942. * @hidden
  75943. */
  75944. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  75945. if (!this._loadedMeshInfo) {
  75946. return;
  75947. }
  75948. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  75949. if (!meshInfo) {
  75950. return;
  75951. }
  75952. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75953. return;
  75954. }
  75955. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  75956. var lerpValue = axisValue * 0.5 + 0.5;
  75957. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  75958. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  75959. };
  75960. /**
  75961. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75962. * @param scene scene in which to add meshes
  75963. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75964. */
  75965. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  75966. var _this = this;
  75967. if (forceDefault === void 0) { forceDefault = false; }
  75968. var path;
  75969. var filename;
  75970. // Checking if GLB loader is present
  75971. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  75972. // Determine the device specific folder based on the ID suffix
  75973. var device = 'default';
  75974. if (this.id && !forceDefault) {
  75975. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  75976. device = ((match && match[0]) || device);
  75977. }
  75978. // Hand
  75979. if (this.hand === 'left') {
  75980. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  75981. }
  75982. else { // Right is the default if no hand is specified
  75983. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  75984. }
  75985. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  75986. }
  75987. else {
  75988. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  75989. path = BABYLON.GenericController.MODEL_BASE_URL;
  75990. filename = BABYLON.GenericController.MODEL_FILENAME;
  75991. }
  75992. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  75993. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  75994. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  75995. if (!_this._loadedMeshInfo) {
  75996. return;
  75997. }
  75998. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  75999. _this.attachToMesh(_this._defaultModel);
  76000. if (meshLoaded) {
  76001. meshLoaded(_this._defaultModel);
  76002. }
  76003. }, null, function (scene, message) {
  76004. BABYLON.Tools.Log(message);
  76005. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  76006. if (!forceDefault) {
  76007. _this.initControllerMesh(scene, meshLoaded, true);
  76008. }
  76009. });
  76010. };
  76011. /**
  76012. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  76013. * can be transformed by button presses and axes values, based on this._mapping.
  76014. *
  76015. * @param scene scene in which the meshes exist
  76016. * @param meshes list of meshes that make up the controller model to process
  76017. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  76018. */
  76019. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  76020. var loadedMeshInfo = null;
  76021. // Create a new mesh to contain the glTF hierarchy
  76022. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  76023. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  76024. var childMesh = null;
  76025. for (var i = 0; i < meshes.length; i++) {
  76026. var mesh = meshes[i];
  76027. if (!mesh.parent) {
  76028. // Exclude controller meshes from picking results
  76029. mesh.isPickable = false;
  76030. // Handle root node, attach to the new parentMesh
  76031. childMesh = mesh;
  76032. break;
  76033. }
  76034. }
  76035. if (childMesh) {
  76036. childMesh.setParent(parentMesh);
  76037. // Create our mesh info. Note that this method will always return non-null.
  76038. loadedMeshInfo = this.createMeshInfo(parentMesh);
  76039. }
  76040. else {
  76041. BABYLON.Tools.Warn('Could not find root node in model file.');
  76042. }
  76043. return loadedMeshInfo;
  76044. };
  76045. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  76046. var loadedMeshInfo = new LoadedMeshInfo();
  76047. var i;
  76048. loadedMeshInfo.rootNode = rootNode;
  76049. // Reset the caches
  76050. loadedMeshInfo.buttonMeshes = {};
  76051. loadedMeshInfo.axisMeshes = {};
  76052. // Button Meshes
  76053. for (i = 0; i < this._mapping.buttons.length; i++) {
  76054. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  76055. if (!buttonMeshName) {
  76056. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  76057. continue;
  76058. }
  76059. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  76060. if (!buttonMesh) {
  76061. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  76062. continue;
  76063. }
  76064. var buttonMeshInfo = {
  76065. index: i,
  76066. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  76067. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  76068. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  76069. };
  76070. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  76071. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  76072. }
  76073. else {
  76074. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  76075. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  76076. '(VALUE: ' + !!buttonMeshInfo.value +
  76077. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  76078. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  76079. ')');
  76080. }
  76081. }
  76082. // Axis Meshes
  76083. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  76084. var axisMeshName = this._mapping.axisMeshNames[i];
  76085. if (!axisMeshName) {
  76086. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  76087. continue;
  76088. }
  76089. var axisMesh = getChildByName(rootNode, axisMeshName);
  76090. if (!axisMesh) {
  76091. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  76092. continue;
  76093. }
  76094. var axisMeshInfo = {
  76095. index: i,
  76096. value: getImmediateChildByName(axisMesh, 'VALUE'),
  76097. min: getImmediateChildByName(axisMesh, 'MIN'),
  76098. max: getImmediateChildByName(axisMesh, 'MAX')
  76099. };
  76100. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  76101. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  76102. }
  76103. else {
  76104. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  76105. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  76106. '(VALUE: ' + !!axisMeshInfo.value +
  76107. ', MIN: ' + !!axisMeshInfo.min +
  76108. ', MAX:' + !!axisMeshInfo.max +
  76109. ')');
  76110. }
  76111. }
  76112. // Pointing Ray
  76113. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  76114. if (!loadedMeshInfo.pointingPoseNode) {
  76115. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  76116. }
  76117. else {
  76118. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  76119. }
  76120. return loadedMeshInfo;
  76121. // Look through all children recursively. This will return null if no mesh exists with the given name.
  76122. function getChildByName(node, name) {
  76123. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  76124. }
  76125. // Look through only immediate children. This will return null if no mesh exists with the given name.
  76126. function getImmediateChildByName(node, name) {
  76127. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  76128. }
  76129. };
  76130. /**
  76131. * Gets the ray of the controller in the direction the controller is pointing
  76132. * @param length the length the resulting ray should be
  76133. * @returns a ray in the direction the controller is pointing
  76134. */
  76135. WindowsMotionController.prototype.getForwardRay = function (length) {
  76136. if (length === void 0) { length = 100; }
  76137. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  76138. return _super.prototype.getForwardRay.call(this, length);
  76139. }
  76140. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  76141. var origin = m.getTranslation();
  76142. var forward = new BABYLON.Vector3(0, 0, -1);
  76143. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  76144. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  76145. return new BABYLON.Ray(origin, direction, length);
  76146. };
  76147. /**
  76148. * Disposes of the controller
  76149. */
  76150. WindowsMotionController.prototype.dispose = function () {
  76151. _super.prototype.dispose.call(this);
  76152. this.onTrackpadChangedObservable.clear();
  76153. };
  76154. /**
  76155. * The base url used to load the left and right controller models
  76156. */
  76157. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  76158. /**
  76159. * The name of the left controller model file
  76160. */
  76161. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  76162. /**
  76163. * The name of the right controller model file
  76164. */
  76165. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  76166. /**
  76167. * The controller name prefix for this controller type
  76168. */
  76169. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  76170. /**
  76171. * The controller id pattern for this controller type
  76172. */
  76173. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  76174. return WindowsMotionController;
  76175. }(BABYLON.WebVRController));
  76176. BABYLON.WindowsMotionController = WindowsMotionController;
  76177. })(BABYLON || (BABYLON = {}));
  76178. //# sourceMappingURL=babylon.windowsMotionController.js.map
  76179. var BABYLON;
  76180. (function (BABYLON) {
  76181. /**
  76182. * Gear VR Controller
  76183. */
  76184. var GearVRController = /** @class */ (function (_super) {
  76185. __extends(GearVRController, _super);
  76186. /**
  76187. * Creates a new GearVRController from a gamepad
  76188. * @param vrGamepad the gamepad that the controller should be created from
  76189. */
  76190. function GearVRController(vrGamepad) {
  76191. var _this = _super.call(this, vrGamepad) || this;
  76192. _this._maxRotationDistFromHeadset = Math.PI / 5;
  76193. _this._draggedRoomRotation = 0;
  76194. _this._tmpVector = new BABYLON.Vector3();
  76195. _this._buttonIndexToObservableNameMap = [
  76196. 'onTrackpadChangedObservable',
  76197. 'onTriggerStateChangedObservable' // Trigger
  76198. ];
  76199. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  76200. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  76201. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  76202. return _this;
  76203. }
  76204. /**
  76205. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  76206. * @param poseData raw pose fromthe device
  76207. */
  76208. GearVRController.prototype.updateFromDevice = function (poseData) {
  76209. _super.prototype.updateFromDevice.call(this, poseData);
  76210. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  76211. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  76212. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  76213. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  76214. // Find the radian distance away that the headset is from the controllers rotation
  76215. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  76216. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  76217. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  76218. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  76219. this._draggedRoomRotation += rotationAmount;
  76220. // Rotate controller around headset
  76221. var sin = Math.sin(-rotationAmount);
  76222. var cos = Math.cos(-rotationAmount);
  76223. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  76224. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  76225. }
  76226. }
  76227. }
  76228. };
  76229. /**
  76230. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76231. * @param scene scene in which to add meshes
  76232. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76233. */
  76234. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76235. var _this = this;
  76236. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  76237. // Offset the controller so it will rotate around the users wrist
  76238. var mesh = new BABYLON.Mesh("", scene);
  76239. newMeshes[1].parent = mesh;
  76240. newMeshes[1].position.z = -0.15;
  76241. _this._defaultModel = mesh;
  76242. _this.attachToMesh(_this._defaultModel);
  76243. if (meshLoaded) {
  76244. meshLoaded(_this._defaultModel);
  76245. }
  76246. });
  76247. };
  76248. /**
  76249. * Called once for each button that changed state since the last frame
  76250. * @param buttonIdx Which button index changed
  76251. * @param state New state of the button
  76252. * @param changes Which properties on the state changed since last frame
  76253. */
  76254. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76255. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  76256. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  76257. // Only emit events for buttons that we know how to map from index to observable
  76258. var observable = this[observableName];
  76259. if (observable) {
  76260. observable.notifyObservers(state);
  76261. }
  76262. }
  76263. };
  76264. /**
  76265. * Base Url for the controller model.
  76266. */
  76267. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76268. /**
  76269. * File name for the controller model.
  76270. */
  76271. GearVRController.MODEL_FILENAME = 'generic.babylon';
  76272. /**
  76273. * Gamepad Id prefix used to identify this controller.
  76274. */
  76275. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  76276. return GearVRController;
  76277. }(BABYLON.WebVRController));
  76278. BABYLON.GearVRController = GearVRController;
  76279. })(BABYLON || (BABYLON = {}));
  76280. //# sourceMappingURL=babylon.gearVRController.js.map
  76281. var BABYLON;
  76282. (function (BABYLON) {
  76283. /**
  76284. * Google Daydream controller
  76285. */
  76286. var DaydreamController = /** @class */ (function (_super) {
  76287. __extends(DaydreamController, _super);
  76288. /**
  76289. * Creates a new DaydreamController from a gamepad
  76290. * @param vrGamepad the gamepad that the controller should be created from
  76291. */
  76292. function DaydreamController(vrGamepad) {
  76293. var _this = _super.call(this, vrGamepad) || this;
  76294. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  76295. return _this;
  76296. }
  76297. /**
  76298. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76299. * @param scene scene in which to add meshes
  76300. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76301. */
  76302. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76303. var _this = this;
  76304. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  76305. _this._defaultModel = newMeshes[1];
  76306. _this.attachToMesh(_this._defaultModel);
  76307. if (meshLoaded) {
  76308. meshLoaded(_this._defaultModel);
  76309. }
  76310. });
  76311. };
  76312. /**
  76313. * Called once for each button that changed state since the last frame
  76314. * @param buttonIdx Which button index changed
  76315. * @param state New state of the button
  76316. * @param changes Which properties on the state changed since last frame
  76317. */
  76318. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76319. // Daydream controller only has 1 GamepadButton (on the trackpad).
  76320. if (buttonIdx === 0) {
  76321. var observable = this.onTriggerStateChangedObservable;
  76322. if (observable) {
  76323. observable.notifyObservers(state);
  76324. }
  76325. }
  76326. else {
  76327. // If the app or home buttons are ever made available
  76328. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  76329. }
  76330. };
  76331. /**
  76332. * Base Url for the controller model.
  76333. */
  76334. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76335. /**
  76336. * File name for the controller model.
  76337. */
  76338. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  76339. /**
  76340. * Gamepad Id prefix used to identify Daydream Controller.
  76341. */
  76342. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  76343. return DaydreamController;
  76344. }(BABYLON.WebVRController));
  76345. BABYLON.DaydreamController = DaydreamController;
  76346. })(BABYLON || (BABYLON = {}));
  76347. //# sourceMappingURL=babylon.daydreamController.js.map
  76348. var BABYLON;
  76349. (function (BABYLON) {
  76350. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  76351. get: function () {
  76352. if (!this._gamepadManager) {
  76353. this._gamepadManager = new BABYLON.GamepadManager(this);
  76354. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  76355. if (!component) {
  76356. component = new GamepadSystemSceneComponent(this);
  76357. this._addComponent(component);
  76358. }
  76359. }
  76360. return this._gamepadManager;
  76361. },
  76362. enumerable: true,
  76363. configurable: true
  76364. });
  76365. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  76366. this.add(new BABYLON.FreeCameraGamepadInput());
  76367. return this;
  76368. };
  76369. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  76370. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  76371. return this;
  76372. };
  76373. /**
  76374. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  76375. */
  76376. var GamepadSystemSceneComponent = /** @class */ (function () {
  76377. /**
  76378. * Creates a new instance of the component for the given scene
  76379. * @param scene Defines the scene to register the component in
  76380. */
  76381. function GamepadSystemSceneComponent(scene) {
  76382. /**
  76383. * The component name helpfull to identify the component in the list of scene components.
  76384. */
  76385. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  76386. this.scene = scene;
  76387. }
  76388. /**
  76389. * Registers the component in a given scene
  76390. */
  76391. GamepadSystemSceneComponent.prototype.register = function () {
  76392. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  76393. };
  76394. /**
  76395. * Rebuilds the elements related to this component in case of
  76396. * context lost for instance.
  76397. */
  76398. GamepadSystemSceneComponent.prototype.rebuild = function () {
  76399. // Nothing to do for gamepads
  76400. };
  76401. /**
  76402. * Disposes the component and the associated ressources
  76403. */
  76404. GamepadSystemSceneComponent.prototype.dispose = function () {
  76405. var gamepadManager = this.scene._gamepadManager;
  76406. if (gamepadManager) {
  76407. gamepadManager.dispose();
  76408. this.scene._gamepadManager = null;
  76409. }
  76410. };
  76411. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  76412. var gamepadManager = this.scene._gamepadManager;
  76413. if (gamepadManager && gamepadManager._isMonitoring) {
  76414. gamepadManager._checkGamepadsStatus();
  76415. }
  76416. };
  76417. return GamepadSystemSceneComponent;
  76418. }());
  76419. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  76420. })(BABYLON || (BABYLON = {}));
  76421. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  76422. var BABYLON;
  76423. (function (BABYLON) {
  76424. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  76425. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  76426. });
  76427. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  76428. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  76429. });
  76430. var FollowCamera = /** @class */ (function (_super) {
  76431. __extends(FollowCamera, _super);
  76432. function FollowCamera(name, position, scene, lockedTarget) {
  76433. if (lockedTarget === void 0) { lockedTarget = null; }
  76434. var _this = _super.call(this, name, position, scene) || this;
  76435. _this.radius = 12;
  76436. _this.rotationOffset = 0;
  76437. _this.heightOffset = 4;
  76438. _this.cameraAcceleration = 0.05;
  76439. _this.maxCameraSpeed = 20;
  76440. _this.lockedTarget = lockedTarget;
  76441. return _this;
  76442. }
  76443. FollowCamera.prototype.getRadians = function (degrees) {
  76444. return degrees * Math.PI / 180;
  76445. };
  76446. FollowCamera.prototype.follow = function (cameraTarget) {
  76447. if (!cameraTarget)
  76448. return;
  76449. var yRotation;
  76450. if (cameraTarget.rotationQuaternion) {
  76451. var rotMatrix = new BABYLON.Matrix();
  76452. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  76453. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  76454. }
  76455. else {
  76456. yRotation = cameraTarget.rotation.y;
  76457. }
  76458. var radians = this.getRadians(this.rotationOffset) + yRotation;
  76459. var targetPosition = cameraTarget.getAbsolutePosition();
  76460. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  76461. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  76462. var dx = targetX - this.position.x;
  76463. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  76464. var dz = (targetZ) - this.position.z;
  76465. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  76466. var vy = dy * this.cameraAcceleration;
  76467. var vz = dz * this.cameraAcceleration * 2;
  76468. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  76469. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76470. }
  76471. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  76472. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76473. }
  76474. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  76475. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76476. }
  76477. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  76478. this.setTarget(targetPosition);
  76479. };
  76480. /** @hidden */
  76481. FollowCamera.prototype._checkInputs = function () {
  76482. _super.prototype._checkInputs.call(this);
  76483. if (this.lockedTarget) {
  76484. this.follow(this.lockedTarget);
  76485. }
  76486. };
  76487. FollowCamera.prototype.getClassName = function () {
  76488. return "FollowCamera";
  76489. };
  76490. __decorate([
  76491. BABYLON.serialize()
  76492. ], FollowCamera.prototype, "radius", void 0);
  76493. __decorate([
  76494. BABYLON.serialize()
  76495. ], FollowCamera.prototype, "rotationOffset", void 0);
  76496. __decorate([
  76497. BABYLON.serialize()
  76498. ], FollowCamera.prototype, "heightOffset", void 0);
  76499. __decorate([
  76500. BABYLON.serialize()
  76501. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  76502. __decorate([
  76503. BABYLON.serialize()
  76504. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  76505. __decorate([
  76506. BABYLON.serializeAsMeshReference("lockedTargetId")
  76507. ], FollowCamera.prototype, "lockedTarget", void 0);
  76508. return FollowCamera;
  76509. }(BABYLON.TargetCamera));
  76510. BABYLON.FollowCamera = FollowCamera;
  76511. var ArcFollowCamera = /** @class */ (function (_super) {
  76512. __extends(ArcFollowCamera, _super);
  76513. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  76514. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  76515. _this.alpha = alpha;
  76516. _this.beta = beta;
  76517. _this.radius = radius;
  76518. _this.target = target;
  76519. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  76520. _this.follow();
  76521. return _this;
  76522. }
  76523. ArcFollowCamera.prototype.follow = function () {
  76524. if (!this.target) {
  76525. return;
  76526. }
  76527. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  76528. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  76529. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  76530. var targetPosition = this.target.getAbsolutePosition();
  76531. this.position = targetPosition.add(this._cartesianCoordinates);
  76532. this.setTarget(targetPosition);
  76533. };
  76534. /** @hidden */
  76535. ArcFollowCamera.prototype._checkInputs = function () {
  76536. _super.prototype._checkInputs.call(this);
  76537. this.follow();
  76538. };
  76539. ArcFollowCamera.prototype.getClassName = function () {
  76540. return "ArcFollowCamera";
  76541. };
  76542. return ArcFollowCamera;
  76543. }(BABYLON.TargetCamera));
  76544. BABYLON.ArcFollowCamera = ArcFollowCamera;
  76545. })(BABYLON || (BABYLON = {}));
  76546. //# sourceMappingURL=babylon.followCamera.js.map
  76547. var BABYLON;
  76548. (function (BABYLON) {
  76549. // We're mainly based on the logic defined into the FreeCamera code
  76550. var UniversalCamera = /** @class */ (function (_super) {
  76551. __extends(UniversalCamera, _super);
  76552. //-- end properties for backward compatibility for inputs
  76553. function UniversalCamera(name, position, scene) {
  76554. var _this = _super.call(this, name, position, scene) || this;
  76555. _this.inputs.addGamepad();
  76556. return _this;
  76557. }
  76558. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  76559. //-- Begin properties for backward compatibility for inputs
  76560. get: function () {
  76561. var gamepad = this.inputs.attached["gamepad"];
  76562. if (gamepad)
  76563. return gamepad.gamepadAngularSensibility;
  76564. return 0;
  76565. },
  76566. set: function (value) {
  76567. var gamepad = this.inputs.attached["gamepad"];
  76568. if (gamepad)
  76569. gamepad.gamepadAngularSensibility = value;
  76570. },
  76571. enumerable: true,
  76572. configurable: true
  76573. });
  76574. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  76575. get: function () {
  76576. var gamepad = this.inputs.attached["gamepad"];
  76577. if (gamepad)
  76578. return gamepad.gamepadMoveSensibility;
  76579. return 0;
  76580. },
  76581. set: function (value) {
  76582. var gamepad = this.inputs.attached["gamepad"];
  76583. if (gamepad)
  76584. gamepad.gamepadMoveSensibility = value;
  76585. },
  76586. enumerable: true,
  76587. configurable: true
  76588. });
  76589. UniversalCamera.prototype.getClassName = function () {
  76590. return "UniversalCamera";
  76591. };
  76592. return UniversalCamera;
  76593. }(BABYLON.TouchCamera));
  76594. BABYLON.UniversalCamera = UniversalCamera;
  76595. })(BABYLON || (BABYLON = {}));
  76596. //# sourceMappingURL=babylon.universalCamera.js.map
  76597. var BABYLON;
  76598. (function (BABYLON) {
  76599. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  76600. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  76601. });
  76602. // We're mainly based on the logic defined into the FreeCamera code
  76603. var GamepadCamera = /** @class */ (function (_super) {
  76604. __extends(GamepadCamera, _super);
  76605. //-- end properties for backward compatibility for inputs
  76606. function GamepadCamera(name, position, scene) {
  76607. return _super.call(this, name, position, scene) || this;
  76608. }
  76609. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  76610. //-- Begin properties for backward compatibility for inputs
  76611. get: function () {
  76612. var gamepad = this.inputs.attached["gamepad"];
  76613. if (gamepad)
  76614. return gamepad.gamepadAngularSensibility;
  76615. return 0;
  76616. },
  76617. set: function (value) {
  76618. var gamepad = this.inputs.attached["gamepad"];
  76619. if (gamepad)
  76620. gamepad.gamepadAngularSensibility = value;
  76621. },
  76622. enumerable: true,
  76623. configurable: true
  76624. });
  76625. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  76626. get: function () {
  76627. var gamepad = this.inputs.attached["gamepad"];
  76628. if (gamepad)
  76629. return gamepad.gamepadMoveSensibility;
  76630. return 0;
  76631. },
  76632. set: function (value) {
  76633. var gamepad = this.inputs.attached["gamepad"];
  76634. if (gamepad)
  76635. gamepad.gamepadMoveSensibility = value;
  76636. },
  76637. enumerable: true,
  76638. configurable: true
  76639. });
  76640. GamepadCamera.prototype.getClassName = function () {
  76641. return "GamepadCamera";
  76642. };
  76643. return GamepadCamera;
  76644. }(BABYLON.UniversalCamera));
  76645. BABYLON.GamepadCamera = GamepadCamera;
  76646. })(BABYLON || (BABYLON = {}));
  76647. //# sourceMappingURL=babylon.gamepadCamera.js.map
  76648. var BABYLON;
  76649. (function (BABYLON) {
  76650. var PostProcessRenderPipelineManager = /** @class */ (function () {
  76651. function PostProcessRenderPipelineManager() {
  76652. this._renderPipelines = {};
  76653. }
  76654. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  76655. this._renderPipelines[renderPipeline._name] = renderPipeline;
  76656. };
  76657. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  76658. if (unique === void 0) { unique = false; }
  76659. var renderPipeline = this._renderPipelines[renderPipelineName];
  76660. if (!renderPipeline) {
  76661. return;
  76662. }
  76663. renderPipeline._attachCameras(cameras, unique);
  76664. };
  76665. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  76666. var renderPipeline = this._renderPipelines[renderPipelineName];
  76667. if (!renderPipeline) {
  76668. return;
  76669. }
  76670. renderPipeline._detachCameras(cameras);
  76671. };
  76672. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  76673. var renderPipeline = this._renderPipelines[renderPipelineName];
  76674. if (!renderPipeline) {
  76675. return;
  76676. }
  76677. renderPipeline._enableEffect(renderEffectName, cameras);
  76678. };
  76679. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  76680. var renderPipeline = this._renderPipelines[renderPipelineName];
  76681. if (!renderPipeline) {
  76682. return;
  76683. }
  76684. renderPipeline._disableEffect(renderEffectName, cameras);
  76685. };
  76686. PostProcessRenderPipelineManager.prototype.update = function () {
  76687. for (var renderPipelineName in this._renderPipelines) {
  76688. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76689. var pipeline = this._renderPipelines[renderPipelineName];
  76690. if (!pipeline.isSupported) {
  76691. pipeline.dispose();
  76692. delete this._renderPipelines[renderPipelineName];
  76693. }
  76694. else {
  76695. pipeline._update();
  76696. }
  76697. }
  76698. }
  76699. };
  76700. /** @hidden */
  76701. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  76702. for (var renderPipelineName in this._renderPipelines) {
  76703. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76704. var pipeline = this._renderPipelines[renderPipelineName];
  76705. pipeline._rebuild();
  76706. }
  76707. }
  76708. };
  76709. PostProcessRenderPipelineManager.prototype.dispose = function () {
  76710. for (var renderPipelineName in this._renderPipelines) {
  76711. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76712. var pipeline = this._renderPipelines[renderPipelineName];
  76713. pipeline.dispose();
  76714. }
  76715. }
  76716. };
  76717. return PostProcessRenderPipelineManager;
  76718. }());
  76719. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  76720. })(BABYLON || (BABYLON = {}));
  76721. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  76722. var BABYLON;
  76723. (function (BABYLON) {
  76724. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  76725. get: function () {
  76726. if (!this._postProcessRenderPipelineManager) {
  76727. // Register the G Buffer component to the scene.
  76728. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  76729. if (!component) {
  76730. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  76731. this._addComponent(component);
  76732. }
  76733. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  76734. }
  76735. return this._postProcessRenderPipelineManager;
  76736. },
  76737. enumerable: true,
  76738. configurable: true
  76739. });
  76740. /**
  76741. * Defines the Render Pipeline scene component responsible to rendering pipelines
  76742. */
  76743. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  76744. /**
  76745. * Creates a new instance of the component for the given scene
  76746. * @param scene Defines the scene to register the component in
  76747. */
  76748. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  76749. /**
  76750. * The component name helpfull to identify the component in the list of scene components.
  76751. */
  76752. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  76753. this.scene = scene;
  76754. }
  76755. /**
  76756. * Registers the component in a given scene
  76757. */
  76758. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  76759. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  76760. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_REBUILDGEOMETRY_POSTPROCESSRENDERPIPELINEMANAGER, this, this._rebuildGeometry);
  76761. };
  76762. /**
  76763. * Rebuilds the elements related to this component in case of
  76764. * context lost for instance.
  76765. */
  76766. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  76767. // Nothing to do for this component
  76768. };
  76769. /**
  76770. * Disposes the component and the associated ressources
  76771. */
  76772. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  76773. if (this.scene._postProcessRenderPipelineManager) {
  76774. this.scene._postProcessRenderPipelineManager.dispose();
  76775. }
  76776. };
  76777. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76778. if (this.scene._postProcessRenderPipelineManager) {
  76779. this.scene._postProcessRenderPipelineManager.update();
  76780. }
  76781. };
  76782. PostProcessRenderPipelineManagerSceneComponent.prototype._rebuildGeometry = function () {
  76783. if (this.scene._postProcessRenderPipelineManager) {
  76784. this.scene._postProcessRenderPipelineManager._rebuild();
  76785. }
  76786. };
  76787. return PostProcessRenderPipelineManagerSceneComponent;
  76788. }());
  76789. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  76790. })(BABYLON || (BABYLON = {}));
  76791. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  76792. var BABYLON;
  76793. (function (BABYLON) {
  76794. /**
  76795. * This represents a set of one or more post processes in Babylon.
  76796. * A post process can be used to apply a shader to a texture after it is rendered.
  76797. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  76798. */
  76799. var PostProcessRenderEffect = /** @class */ (function () {
  76800. /**
  76801. * Instantiates a post process render effect.
  76802. * A post process can be used to apply a shader to a texture after it is rendered.
  76803. * @param engine The engine the effect is tied to
  76804. * @param name The name of the effect
  76805. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  76806. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  76807. */
  76808. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  76809. this._name = name;
  76810. this._singleInstance = singleInstance || true;
  76811. this._getPostProcesses = getPostProcesses;
  76812. this._cameras = {};
  76813. this._indicesForCamera = {};
  76814. this._postProcesses = {};
  76815. }
  76816. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  76817. /**
  76818. * Checks if all the post processes in the effect are supported.
  76819. */
  76820. get: function () {
  76821. for (var index in this._postProcesses) {
  76822. if (this._postProcesses.hasOwnProperty(index)) {
  76823. var pps = this._postProcesses[index];
  76824. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  76825. if (!pps[ppIndex].isSupported) {
  76826. return false;
  76827. }
  76828. }
  76829. }
  76830. }
  76831. return true;
  76832. },
  76833. enumerable: true,
  76834. configurable: true
  76835. });
  76836. /**
  76837. * Updates the current state of the effect
  76838. * @hidden
  76839. */
  76840. PostProcessRenderEffect.prototype._update = function () {
  76841. };
  76842. /**
  76843. * Attaches the effect on cameras
  76844. * @param cameras The camera to attach to.
  76845. * @hidden
  76846. */
  76847. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  76848. var _this = this;
  76849. var cameraKey;
  76850. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76851. if (!cams) {
  76852. return;
  76853. }
  76854. for (var i = 0; i < cams.length; i++) {
  76855. var camera = cams[i];
  76856. var cameraName = camera.name;
  76857. if (this._singleInstance) {
  76858. cameraKey = 0;
  76859. }
  76860. else {
  76861. cameraKey = cameraName;
  76862. }
  76863. if (!this._postProcesses[cameraKey]) {
  76864. var postProcess = this._getPostProcesses();
  76865. if (postProcess) {
  76866. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  76867. }
  76868. }
  76869. if (!this._indicesForCamera[cameraName]) {
  76870. this._indicesForCamera[cameraName] = [];
  76871. }
  76872. this._postProcesses[cameraKey].forEach(function (postProcess) {
  76873. var index = camera.attachPostProcess(postProcess);
  76874. _this._indicesForCamera[cameraName].push(index);
  76875. });
  76876. if (!this._cameras[cameraName]) {
  76877. this._cameras[cameraName] = camera;
  76878. }
  76879. }
  76880. };
  76881. /**
  76882. * Detatches the effect on cameras
  76883. * @param cameras The camera to detatch from.
  76884. * @hidden
  76885. */
  76886. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  76887. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76888. if (!cams) {
  76889. return;
  76890. }
  76891. for (var i = 0; i < cams.length; i++) {
  76892. var camera = cams[i];
  76893. var cameraName = camera.name;
  76894. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76895. camera.detachPostProcess(postProcess);
  76896. });
  76897. if (this._cameras[cameraName]) {
  76898. //this._indicesForCamera.splice(index, 1);
  76899. this._cameras[cameraName] = null;
  76900. }
  76901. }
  76902. };
  76903. /**
  76904. * Enables the effect on given cameras
  76905. * @param cameras The camera to enable.
  76906. * @hidden
  76907. */
  76908. PostProcessRenderEffect.prototype._enable = function (cameras) {
  76909. var _this = this;
  76910. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76911. if (!cams) {
  76912. return;
  76913. }
  76914. for (var i = 0; i < cams.length; i++) {
  76915. var camera = cams[i];
  76916. var cameraName = camera.name;
  76917. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  76918. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  76919. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76920. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  76921. });
  76922. }
  76923. }
  76924. }
  76925. };
  76926. /**
  76927. * Disables the effect on the given cameras
  76928. * @param cameras The camera to disable.
  76929. * @hidden
  76930. */
  76931. PostProcessRenderEffect.prototype._disable = function (cameras) {
  76932. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76933. if (!cams) {
  76934. return;
  76935. }
  76936. for (var i = 0; i < cams.length; i++) {
  76937. var camera = cams[i];
  76938. var cameraName = camera.name;
  76939. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76940. camera.detachPostProcess(postProcess);
  76941. });
  76942. }
  76943. };
  76944. /**
  76945. * Gets a list of the post processes contained in the effect.
  76946. * @param camera The camera to get the post processes on.
  76947. * @returns The list of the post processes in the effect.
  76948. */
  76949. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  76950. if (this._singleInstance) {
  76951. return this._postProcesses[0];
  76952. }
  76953. else {
  76954. if (!camera) {
  76955. return null;
  76956. }
  76957. return this._postProcesses[camera.name];
  76958. }
  76959. };
  76960. return PostProcessRenderEffect;
  76961. }());
  76962. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  76963. })(BABYLON || (BABYLON = {}));
  76964. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  76965. var BABYLON;
  76966. (function (BABYLON) {
  76967. var PostProcessRenderPipeline = /** @class */ (function () {
  76968. function PostProcessRenderPipeline(engine, name) {
  76969. this.engine = engine;
  76970. this._name = name;
  76971. this._renderEffects = {};
  76972. this._renderEffectsForIsolatedPass = new Array();
  76973. this._cameras = [];
  76974. }
  76975. PostProcessRenderPipeline.prototype.getClassName = function () {
  76976. return "PostProcessRenderPipeline";
  76977. };
  76978. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  76979. get: function () {
  76980. for (var renderEffectName in this._renderEffects) {
  76981. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76982. if (!this._renderEffects[renderEffectName].isSupported) {
  76983. return false;
  76984. }
  76985. }
  76986. }
  76987. return true;
  76988. },
  76989. enumerable: true,
  76990. configurable: true
  76991. });
  76992. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  76993. this._renderEffects[renderEffect._name] = renderEffect;
  76994. };
  76995. // private
  76996. /** @hidden */
  76997. PostProcessRenderPipeline.prototype._rebuild = function () {
  76998. };
  76999. /** @hidden */
  77000. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  77001. var renderEffects = this._renderEffects[renderEffectName];
  77002. if (!renderEffects) {
  77003. return;
  77004. }
  77005. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77006. };
  77007. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  77008. var renderEffects = this._renderEffects[renderEffectName];
  77009. if (!renderEffects) {
  77010. return;
  77011. }
  77012. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77013. };
  77014. /** @hidden */
  77015. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  77016. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77017. if (!cams) {
  77018. return;
  77019. }
  77020. var indicesToDelete = [];
  77021. var i;
  77022. for (i = 0; i < cams.length; i++) {
  77023. var camera = cams[i];
  77024. var cameraName = camera.name;
  77025. if (this._cameras.indexOf(camera) === -1) {
  77026. this._cameras[cameraName] = camera;
  77027. }
  77028. else if (unique) {
  77029. indicesToDelete.push(i);
  77030. }
  77031. }
  77032. for (i = 0; i < indicesToDelete.length; i++) {
  77033. cameras.splice(indicesToDelete[i], 1);
  77034. }
  77035. for (var renderEffectName in this._renderEffects) {
  77036. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77037. this._renderEffects[renderEffectName]._attachCameras(cams);
  77038. }
  77039. }
  77040. };
  77041. /** @hidden */
  77042. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  77043. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77044. if (!cams) {
  77045. return;
  77046. }
  77047. for (var renderEffectName in this._renderEffects) {
  77048. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77049. this._renderEffects[renderEffectName]._detachCameras(cams);
  77050. }
  77051. }
  77052. for (var i = 0; i < cams.length; i++) {
  77053. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  77054. }
  77055. };
  77056. /** @hidden */
  77057. PostProcessRenderPipeline.prototype._update = function () {
  77058. for (var renderEffectName in this._renderEffects) {
  77059. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77060. this._renderEffects[renderEffectName]._update();
  77061. }
  77062. }
  77063. for (var i = 0; i < this._cameras.length; i++) {
  77064. var cameraName = this._cameras[i].name;
  77065. if (this._renderEffectsForIsolatedPass[cameraName]) {
  77066. this._renderEffectsForIsolatedPass[cameraName]._update();
  77067. }
  77068. }
  77069. };
  77070. /** @hidden */
  77071. PostProcessRenderPipeline.prototype._reset = function () {
  77072. this._renderEffects = {};
  77073. this._renderEffectsForIsolatedPass = new Array();
  77074. };
  77075. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  77076. // 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)
  77077. var effectKeys = Object.keys(this._renderEffects);
  77078. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  77079. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  77080. if (postProcesses) {
  77081. postProcesses[0].samples = sampleCount;
  77082. return true;
  77083. }
  77084. }
  77085. return false;
  77086. };
  77087. PostProcessRenderPipeline.prototype.dispose = function () {
  77088. // Must be implemented by children
  77089. };
  77090. __decorate([
  77091. BABYLON.serialize()
  77092. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  77093. return PostProcessRenderPipeline;
  77094. }());
  77095. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  77096. })(BABYLON || (BABYLON = {}));
  77097. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  77098. var BABYLON;
  77099. (function (BABYLON) {
  77100. /**
  77101. * This represents a depth renderer in Babylon.
  77102. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  77103. */
  77104. var DepthRenderer = /** @class */ (function () {
  77105. /**
  77106. * Instantiates a depth renderer
  77107. * @param scene The scene the renderer belongs to
  77108. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  77109. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  77110. */
  77111. function DepthRenderer(scene, type, camera) {
  77112. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  77113. if (camera === void 0) { camera = null; }
  77114. var _this = this;
  77115. this._scene = scene;
  77116. // Register the G Buffer component to the scene.
  77117. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  77118. if (!component) {
  77119. component = new BABYLON.DepthRendererSceneComponent(scene);
  77120. scene._addComponent(component);
  77121. }
  77122. this._camera = camera;
  77123. var engine = scene.getEngine();
  77124. // Render target
  77125. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  77126. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77127. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77128. this._depthMap.refreshRate = 1;
  77129. this._depthMap.renderParticles = false;
  77130. this._depthMap.renderList = null;
  77131. // Camera to get depth map from to support multiple concurrent cameras
  77132. this._depthMap.activeCamera = this._camera;
  77133. this._depthMap.ignoreCameraViewport = true;
  77134. this._depthMap.useCameraPostProcesses = false;
  77135. // set default depth value to 1.0 (far away)
  77136. this._depthMap.onClearObservable.add(function (engine) {
  77137. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  77138. });
  77139. // Custom render function
  77140. var renderSubMesh = function (subMesh) {
  77141. var mesh = subMesh.getRenderingMesh();
  77142. var scene = _this._scene;
  77143. var engine = scene.getEngine();
  77144. var material = subMesh.getMaterial();
  77145. if (!material) {
  77146. return;
  77147. }
  77148. // Culling and reverse (right handed system)
  77149. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77150. // Managing instances
  77151. var batch = mesh._getInstancesRenderList(subMesh._id);
  77152. if (batch.mustReturn) {
  77153. return;
  77154. }
  77155. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77156. var camera = _this._camera || scene.activeCamera;
  77157. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  77158. engine.enableEffect(_this._effect);
  77159. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77160. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77161. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  77162. // Alpha test
  77163. if (material && material.needAlphaTesting()) {
  77164. var alphaTexture = material.getAlphaTestTexture();
  77165. if (alphaTexture) {
  77166. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77167. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77168. }
  77169. }
  77170. // Bones
  77171. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77172. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77173. }
  77174. // Draw
  77175. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77176. }
  77177. };
  77178. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77179. var index;
  77180. if (depthOnlySubMeshes.length) {
  77181. engine.setColorWrite(false);
  77182. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77183. renderSubMesh(depthOnlySubMeshes.data[index]);
  77184. }
  77185. engine.setColorWrite(true);
  77186. }
  77187. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77188. renderSubMesh(opaqueSubMeshes.data[index]);
  77189. }
  77190. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77191. renderSubMesh(alphaTestSubMeshes.data[index]);
  77192. }
  77193. };
  77194. }
  77195. /**
  77196. * Creates the depth rendering effect and checks if the effect is ready.
  77197. * @param subMesh The submesh to be used to render the depth map of
  77198. * @param useInstances If multiple world instances should be used
  77199. * @returns if the depth renderer is ready to render the depth map
  77200. */
  77201. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  77202. var material = subMesh.getMaterial();
  77203. if (material.disableDepthWrite) {
  77204. return false;
  77205. }
  77206. var defines = [];
  77207. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77208. var mesh = subMesh.getMesh();
  77209. // Alpha test
  77210. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  77211. defines.push("#define ALPHATEST");
  77212. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77213. attribs.push(BABYLON.VertexBuffer.UVKind);
  77214. defines.push("#define UV1");
  77215. }
  77216. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77217. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77218. defines.push("#define UV2");
  77219. }
  77220. }
  77221. // Bones
  77222. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77223. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77224. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77225. if (mesh.numBoneInfluencers > 4) {
  77226. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77227. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77228. }
  77229. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77230. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77231. }
  77232. else {
  77233. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77234. }
  77235. // Instances
  77236. if (useInstances) {
  77237. defines.push("#define INSTANCES");
  77238. attribs.push("world0");
  77239. attribs.push("world1");
  77240. attribs.push("world2");
  77241. attribs.push("world3");
  77242. }
  77243. // Get correct effect
  77244. var join = defines.join("\n");
  77245. if (this._cachedDefines !== join) {
  77246. this._cachedDefines = join;
  77247. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  77248. }
  77249. return this._effect.isReady();
  77250. };
  77251. /**
  77252. * Gets the texture which the depth map will be written to.
  77253. * @returns The depth map texture
  77254. */
  77255. DepthRenderer.prototype.getDepthMap = function () {
  77256. return this._depthMap;
  77257. };
  77258. /**
  77259. * Disposes of the depth renderer.
  77260. */
  77261. DepthRenderer.prototype.dispose = function () {
  77262. this._depthMap.dispose();
  77263. };
  77264. return DepthRenderer;
  77265. }());
  77266. BABYLON.DepthRenderer = DepthRenderer;
  77267. })(BABYLON || (BABYLON = {}));
  77268. //# sourceMappingURL=babylon.depthRenderer.js.map
  77269. var BABYLON;
  77270. (function (BABYLON) {
  77271. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  77272. camera = camera || this.activeCamera;
  77273. if (!camera) {
  77274. throw "No camera available to enable depth renderer";
  77275. }
  77276. if (!this._depthRenderer) {
  77277. this._depthRenderer = {};
  77278. }
  77279. if (!this._depthRenderer[camera.id]) {
  77280. var textureType = 0;
  77281. if (this.getEngine().getCaps().textureHalfFloatRender) {
  77282. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77283. }
  77284. else if (this.getEngine().getCaps().textureFloatRender) {
  77285. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77286. }
  77287. else {
  77288. throw "Depth renderer does not support int texture type";
  77289. }
  77290. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  77291. }
  77292. return this._depthRenderer[camera.id];
  77293. };
  77294. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  77295. camera = camera || this.activeCamera;
  77296. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  77297. return;
  77298. }
  77299. this._depthRenderer[camera.id].dispose();
  77300. delete this._depthRenderer[camera.id];
  77301. };
  77302. /**
  77303. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  77304. * in several rendering techniques.
  77305. */
  77306. var DepthRendererSceneComponent = /** @class */ (function () {
  77307. /**
  77308. * Creates a new instance of the component for the given scene
  77309. * @param scene Defines the scene to register the component in
  77310. */
  77311. function DepthRendererSceneComponent(scene) {
  77312. /**
  77313. * The component name helpfull to identify the component in the list of scene components.
  77314. */
  77315. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  77316. this.scene = scene;
  77317. }
  77318. /**
  77319. * Registers the component in a given scene
  77320. */
  77321. DepthRendererSceneComponent.prototype.register = function () {
  77322. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  77323. };
  77324. /**
  77325. * Rebuilds the elements related to this component in case of
  77326. * context lost for instance.
  77327. */
  77328. DepthRendererSceneComponent.prototype.rebuild = function () {
  77329. // Nothing to do for this component
  77330. };
  77331. /**
  77332. * Disposes the component and the associated ressources
  77333. */
  77334. DepthRendererSceneComponent.prototype.dispose = function () {
  77335. for (var key in this.scene._depthRenderer) {
  77336. this.scene._depthRenderer[key].dispose();
  77337. }
  77338. };
  77339. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77340. if (this.scene._depthRenderer) {
  77341. for (var key in this.scene._depthRenderer) {
  77342. renderTargets.push(this.scene._depthRenderer[key].getDepthMap());
  77343. }
  77344. }
  77345. };
  77346. return DepthRendererSceneComponent;
  77347. }());
  77348. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  77349. })(BABYLON || (BABYLON = {}));
  77350. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  77351. var BABYLON;
  77352. (function (BABYLON) {
  77353. /**
  77354. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  77355. */
  77356. var GeometryBufferRenderer = /** @class */ (function () {
  77357. /**
  77358. * Creates a new G Buffer for the scene
  77359. * @param scene The scene the buffer belongs to
  77360. * @param ratio How big is the buffer related to the main canvas.
  77361. */
  77362. function GeometryBufferRenderer(scene, ratio) {
  77363. if (ratio === void 0) { ratio = 1; }
  77364. this._enablePosition = false;
  77365. this._scene = scene;
  77366. this._ratio = ratio;
  77367. // Register the G Buffer component to the scene.
  77368. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  77369. if (!component) {
  77370. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  77371. scene._addComponent(component);
  77372. }
  77373. // Render target
  77374. this._createRenderTargets();
  77375. }
  77376. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  77377. /**
  77378. * Set the render list (meshes to be rendered) used in the G buffer.
  77379. */
  77380. set: function (meshes) {
  77381. this._multiRenderTarget.renderList = meshes;
  77382. },
  77383. enumerable: true,
  77384. configurable: true
  77385. });
  77386. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  77387. /**
  77388. * Gets wether or not G buffer are supported by the running hardware.
  77389. * This requires draw buffer supports
  77390. */
  77391. get: function () {
  77392. return this._multiRenderTarget.isSupported;
  77393. },
  77394. enumerable: true,
  77395. configurable: true
  77396. });
  77397. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  77398. /**
  77399. * Gets wether or not position are enabled for the G buffer.
  77400. */
  77401. get: function () {
  77402. return this._enablePosition;
  77403. },
  77404. /**
  77405. * Sets wether or not position are enabled for the G buffer.
  77406. */
  77407. set: function (enable) {
  77408. this._enablePosition = enable;
  77409. this.dispose();
  77410. this._createRenderTargets();
  77411. },
  77412. enumerable: true,
  77413. configurable: true
  77414. });
  77415. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  77416. /**
  77417. * Gets the scene associated with the buffer.
  77418. */
  77419. get: function () {
  77420. return this._scene;
  77421. },
  77422. enumerable: true,
  77423. configurable: true
  77424. });
  77425. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  77426. /**
  77427. * Gets the ratio used by the buffer during its creation.
  77428. * How big is the buffer related to the main canvas.
  77429. */
  77430. get: function () {
  77431. return this._ratio;
  77432. },
  77433. enumerable: true,
  77434. configurable: true
  77435. });
  77436. /**
  77437. * Checks wether everything is ready to render a submesh to the G buffer.
  77438. * @param subMesh the submesh to check readiness for
  77439. * @param useInstances is the mesh drawn using instance or not
  77440. * @returns true if ready otherwise false
  77441. */
  77442. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  77443. var material = subMesh.getMaterial();
  77444. if (material && material.disableDepthWrite) {
  77445. return false;
  77446. }
  77447. var defines = [];
  77448. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77449. var mesh = subMesh.getMesh();
  77450. // Alpha test
  77451. if (material && material.needAlphaTesting()) {
  77452. defines.push("#define ALPHATEST");
  77453. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77454. attribs.push(BABYLON.VertexBuffer.UVKind);
  77455. defines.push("#define UV1");
  77456. }
  77457. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77458. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77459. defines.push("#define UV2");
  77460. }
  77461. }
  77462. // Buffers
  77463. if (this._enablePosition) {
  77464. defines.push("#define POSITION");
  77465. }
  77466. // Bones
  77467. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77468. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77469. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77470. if (mesh.numBoneInfluencers > 4) {
  77471. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77472. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77473. }
  77474. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77475. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77476. }
  77477. else {
  77478. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77479. }
  77480. // Instances
  77481. if (useInstances) {
  77482. defines.push("#define INSTANCES");
  77483. attribs.push("world0");
  77484. attribs.push("world1");
  77485. attribs.push("world2");
  77486. attribs.push("world3");
  77487. }
  77488. // Get correct effect
  77489. var join = defines.join("\n");
  77490. if (this._cachedDefines !== join) {
  77491. this._cachedDefines = join;
  77492. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77493. }
  77494. return this._effect.isReady();
  77495. };
  77496. /**
  77497. * Gets the current underlying G Buffer.
  77498. * @returns the buffer
  77499. */
  77500. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77501. return this._multiRenderTarget;
  77502. };
  77503. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77504. /**
  77505. * Gets the number of samples used to render the buffer (anti aliasing).
  77506. */
  77507. get: function () {
  77508. return this._multiRenderTarget.samples;
  77509. },
  77510. /**
  77511. * Sets the number of samples used to render the buffer (anti aliasing).
  77512. */
  77513. set: function (value) {
  77514. this._multiRenderTarget.samples = value;
  77515. },
  77516. enumerable: true,
  77517. configurable: true
  77518. });
  77519. /**
  77520. * Disposes the renderer and frees up associated resources.
  77521. */
  77522. GeometryBufferRenderer.prototype.dispose = function () {
  77523. this.getGBuffer().dispose();
  77524. };
  77525. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77526. var _this = this;
  77527. var engine = this._scene.getEngine();
  77528. var count = this._enablePosition ? 3 : 2;
  77529. 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 });
  77530. if (!this.isSupported) {
  77531. return;
  77532. }
  77533. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77534. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77535. this._multiRenderTarget.refreshRate = 1;
  77536. this._multiRenderTarget.renderParticles = false;
  77537. this._multiRenderTarget.renderList = null;
  77538. // set default depth value to 1.0 (far away)
  77539. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77540. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77541. });
  77542. // Custom render function
  77543. var renderSubMesh = function (subMesh) {
  77544. var mesh = subMesh.getRenderingMesh();
  77545. var scene = _this._scene;
  77546. var engine = scene.getEngine();
  77547. var material = subMesh.getMaterial();
  77548. if (!material) {
  77549. return;
  77550. }
  77551. // Culling
  77552. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77553. // Managing instances
  77554. var batch = mesh._getInstancesRenderList(subMesh._id);
  77555. if (batch.mustReturn) {
  77556. return;
  77557. }
  77558. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77559. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77560. engine.enableEffect(_this._effect);
  77561. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77562. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77563. _this._effect.setMatrix("view", scene.getViewMatrix());
  77564. // Alpha test
  77565. if (material && material.needAlphaTesting()) {
  77566. var alphaTexture = material.getAlphaTestTexture();
  77567. if (alphaTexture) {
  77568. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77569. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77570. }
  77571. }
  77572. // Bones
  77573. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77574. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77575. }
  77576. // Draw
  77577. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77578. }
  77579. };
  77580. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77581. var index;
  77582. if (depthOnlySubMeshes.length) {
  77583. engine.setColorWrite(false);
  77584. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77585. renderSubMesh(depthOnlySubMeshes.data[index]);
  77586. }
  77587. engine.setColorWrite(true);
  77588. }
  77589. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77590. renderSubMesh(opaqueSubMeshes.data[index]);
  77591. }
  77592. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77593. renderSubMesh(alphaTestSubMeshes.data[index]);
  77594. }
  77595. };
  77596. };
  77597. return GeometryBufferRenderer;
  77598. }());
  77599. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77600. })(BABYLON || (BABYLON = {}));
  77601. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77602. var BABYLON;
  77603. (function (BABYLON) {
  77604. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  77605. get: function () {
  77606. this._geometryBufferRenderer;
  77607. },
  77608. set: function (value) {
  77609. if (value && value.isSupported) {
  77610. this._geometryBufferRenderer = value;
  77611. }
  77612. ;
  77613. },
  77614. enumerable: true,
  77615. configurable: true
  77616. });
  77617. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  77618. if (ratio === void 0) { ratio = 1; }
  77619. if (this._geometryBufferRenderer) {
  77620. return this._geometryBufferRenderer;
  77621. }
  77622. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  77623. if (!this._geometryBufferRenderer.isSupported) {
  77624. this._geometryBufferRenderer = null;
  77625. }
  77626. return this._geometryBufferRenderer;
  77627. };
  77628. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  77629. if (!this._geometryBufferRenderer) {
  77630. return;
  77631. }
  77632. this._geometryBufferRenderer.dispose();
  77633. this._geometryBufferRenderer = null;
  77634. };
  77635. /**
  77636. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer usefull
  77637. * in several rendering techniques.
  77638. */
  77639. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  77640. /**
  77641. * Creates a new instance of the component for the given scene
  77642. * @param scene Defines the scene to register the component in
  77643. */
  77644. function GeometryBufferRendererSceneComponent(scene) {
  77645. /**
  77646. * The component name helpfull to identify the component in the list of scene components.
  77647. */
  77648. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  77649. this.scene = scene;
  77650. }
  77651. /**
  77652. * Registers the component in a given scene
  77653. */
  77654. GeometryBufferRendererSceneComponent.prototype.register = function () {
  77655. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  77656. };
  77657. /**
  77658. * Rebuilds the elements related to this component in case of
  77659. * context lost for instance.
  77660. */
  77661. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  77662. // Nothing to do for this component
  77663. };
  77664. /**
  77665. * Disposes the component and the associated ressources
  77666. */
  77667. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  77668. // Nothing to do for this component
  77669. };
  77670. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77671. if (this.scene._geometryBufferRenderer) {
  77672. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  77673. }
  77674. };
  77675. return GeometryBufferRendererSceneComponent;
  77676. }());
  77677. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  77678. })(BABYLON || (BABYLON = {}));
  77679. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  77680. var BABYLON;
  77681. (function (BABYLON) {
  77682. var SSAORenderingPipeline = /** @class */ (function (_super) {
  77683. __extends(SSAORenderingPipeline, _super);
  77684. /**
  77685. * @constructor
  77686. * @param {string} name - The rendering pipeline name
  77687. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77688. * @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 }
  77689. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77690. */
  77691. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  77692. var _this = _super.call(this, scene.getEngine(), name) || this;
  77693. // Members
  77694. /**
  77695. * The PassPostProcess id in the pipeline that contains the original scene color
  77696. */
  77697. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  77698. /**
  77699. * The SSAO PostProcess id in the pipeline
  77700. */
  77701. _this.SSAORenderEffect = "SSAORenderEffect";
  77702. /**
  77703. * The horizontal blur PostProcess id in the pipeline
  77704. */
  77705. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  77706. /**
  77707. * The vertical blur PostProcess id in the pipeline
  77708. */
  77709. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  77710. /**
  77711. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  77712. */
  77713. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  77714. /**
  77715. * The output strength of the SSAO post-process. Default value is 1.0.
  77716. */
  77717. _this.totalStrength = 1.0;
  77718. /**
  77719. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  77720. */
  77721. _this.radius = 0.0001;
  77722. /**
  77723. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  77724. * Must not be equal to fallOff and superior to fallOff.
  77725. * Default value is 0.975
  77726. */
  77727. _this.area = 0.0075;
  77728. /**
  77729. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  77730. * Must not be equal to area and inferior to area.
  77731. * Default value is 0.0
  77732. */
  77733. _this.fallOff = 0.000001;
  77734. /**
  77735. * The base color of the SSAO post-process
  77736. * The final result is "base + ssao" between [0, 1]
  77737. */
  77738. _this.base = 0.5;
  77739. _this._firstUpdate = true;
  77740. _this._scene = scene;
  77741. // Set up assets
  77742. _this._createRandomTexture();
  77743. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  77744. var ssaoRatio = ratio.ssaoRatio || ratio;
  77745. var combineRatio = ratio.combineRatio || ratio;
  77746. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  77747. _this._createSSAOPostProcess(ssaoRatio);
  77748. _this._createBlurPostProcess(ssaoRatio);
  77749. _this._createSSAOCombinePostProcess(combineRatio);
  77750. // Set up pipeline
  77751. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  77752. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  77753. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  77754. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  77755. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  77756. // Finish
  77757. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77758. if (cameras)
  77759. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77760. return _this;
  77761. }
  77762. // Public Methods
  77763. /**
  77764. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  77765. */
  77766. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  77767. if (disableDepthRender === void 0) { disableDepthRender = false; }
  77768. for (var i = 0; i < this._scene.cameras.length; i++) {
  77769. var camera = this._scene.cameras[i];
  77770. this._originalColorPostProcess.dispose(camera);
  77771. this._ssaoPostProcess.dispose(camera);
  77772. this._blurHPostProcess.dispose(camera);
  77773. this._blurVPostProcess.dispose(camera);
  77774. this._ssaoCombinePostProcess.dispose(camera);
  77775. }
  77776. this._randomTexture.dispose();
  77777. if (disableDepthRender)
  77778. this._scene.disableDepthRenderer();
  77779. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77780. _super.prototype.dispose.call(this);
  77781. };
  77782. // Private Methods
  77783. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  77784. var _this = this;
  77785. var size = 16;
  77786. 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);
  77787. 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);
  77788. this._blurHPostProcess.onActivateObservable.add(function () {
  77789. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  77790. _this._blurHPostProcess.kernel = size * dw;
  77791. });
  77792. this._blurVPostProcess.onActivateObservable.add(function () {
  77793. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  77794. _this._blurVPostProcess.kernel = size * dw;
  77795. });
  77796. };
  77797. /** @hidden */
  77798. SSAORenderingPipeline.prototype._rebuild = function () {
  77799. this._firstUpdate = true;
  77800. _super.prototype._rebuild.call(this);
  77801. };
  77802. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  77803. var _this = this;
  77804. var numSamples = 16;
  77805. var sampleSphere = [
  77806. 0.5381, 0.1856, -0.4319,
  77807. 0.1379, 0.2486, 0.4430,
  77808. 0.3371, 0.5679, -0.0057,
  77809. -0.6999, -0.0451, -0.0019,
  77810. 0.0689, -0.1598, -0.8547,
  77811. 0.0560, 0.0069, -0.1843,
  77812. -0.0146, 0.1402, 0.0762,
  77813. 0.0100, -0.1924, -0.0344,
  77814. -0.3577, -0.5301, -0.4358,
  77815. -0.3169, 0.1063, 0.0158,
  77816. 0.0103, -0.5869, 0.0046,
  77817. -0.0897, -0.4940, 0.3287,
  77818. 0.7119, -0.0154, -0.0918,
  77819. -0.0533, 0.0596, -0.5411,
  77820. 0.0352, -0.0631, 0.5460,
  77821. -0.4776, 0.2847, -0.0271
  77822. ];
  77823. var samplesFactor = 1.0 / numSamples;
  77824. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  77825. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  77826. "area", "fallOff", "base", "range", "viewport"
  77827. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  77828. this._ssaoPostProcess.onApply = function (effect) {
  77829. if (_this._firstUpdate) {
  77830. effect.setArray3("sampleSphere", sampleSphere);
  77831. effect.setFloat("samplesFactor", samplesFactor);
  77832. effect.setFloat("randTextureTiles", 4.0);
  77833. }
  77834. effect.setFloat("totalStrength", _this.totalStrength);
  77835. effect.setFloat("radius", _this.radius);
  77836. effect.setFloat("area", _this.area);
  77837. effect.setFloat("fallOff", _this.fallOff);
  77838. effect.setFloat("base", _this.base);
  77839. effect.setTexture("textureSampler", _this._depthTexture);
  77840. effect.setTexture("randomSampler", _this._randomTexture);
  77841. };
  77842. };
  77843. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  77844. var _this = this;
  77845. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77846. this._ssaoCombinePostProcess.onApply = function (effect) {
  77847. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  77848. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  77849. };
  77850. };
  77851. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  77852. var size = 512;
  77853. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77854. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77855. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77856. var context = this._randomTexture.getContext();
  77857. var rand = function (min, max) {
  77858. return Math.random() * (max - min) + min;
  77859. };
  77860. var randVector = BABYLON.Vector3.Zero();
  77861. for (var x = 0; x < size; x++) {
  77862. for (var y = 0; y < size; y++) {
  77863. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  77864. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  77865. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  77866. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  77867. context.fillRect(x, y, 1, 1);
  77868. }
  77869. }
  77870. this._randomTexture.update(false);
  77871. };
  77872. __decorate([
  77873. BABYLON.serialize()
  77874. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  77875. __decorate([
  77876. BABYLON.serialize()
  77877. ], SSAORenderingPipeline.prototype, "radius", void 0);
  77878. __decorate([
  77879. BABYLON.serialize()
  77880. ], SSAORenderingPipeline.prototype, "area", void 0);
  77881. __decorate([
  77882. BABYLON.serialize()
  77883. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  77884. __decorate([
  77885. BABYLON.serialize()
  77886. ], SSAORenderingPipeline.prototype, "base", void 0);
  77887. return SSAORenderingPipeline;
  77888. }(BABYLON.PostProcessRenderPipeline));
  77889. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  77890. })(BABYLON || (BABYLON = {}));
  77891. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  77892. var BABYLON;
  77893. (function (BABYLON) {
  77894. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  77895. __extends(SSAO2RenderingPipeline, _super);
  77896. /**
  77897. * @constructor
  77898. * @param {string} name - The rendering pipeline name
  77899. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77900. * @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 }
  77901. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77902. */
  77903. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  77904. var _this = _super.call(this, scene.getEngine(), name) || this;
  77905. // Members
  77906. /**
  77907. * The PassPostProcess id in the pipeline that contains the original scene color
  77908. */
  77909. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  77910. /**
  77911. * The SSAO PostProcess id in the pipeline
  77912. */
  77913. _this.SSAORenderEffect = "SSAORenderEffect";
  77914. /**
  77915. * The horizontal blur PostProcess id in the pipeline
  77916. */
  77917. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  77918. /**
  77919. * The vertical blur PostProcess id in the pipeline
  77920. */
  77921. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  77922. /**
  77923. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  77924. */
  77925. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  77926. /**
  77927. * The output strength of the SSAO post-process. Default value is 1.0.
  77928. */
  77929. _this.totalStrength = 1.0;
  77930. /**
  77931. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  77932. */
  77933. _this.maxZ = 100.0;
  77934. /**
  77935. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  77936. */
  77937. _this.minZAspect = 0.2;
  77938. _this._samples = 8;
  77939. _this._textureSamples = 1;
  77940. /**
  77941. * Are we using bilateral blur ?
  77942. */
  77943. _this._expensiveBlur = true;
  77944. /**
  77945. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  77946. */
  77947. _this.radius = 2.0;
  77948. /**
  77949. * The base color of the SSAO post-process
  77950. * The final result is "base + ssao" between [0, 1]
  77951. */
  77952. _this.base = 0;
  77953. _this._firstUpdate = true;
  77954. _this._bits = new Uint32Array(1);
  77955. _this._scene = scene;
  77956. _this._ratio = ratio;
  77957. if (!_this.isSupported) {
  77958. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  77959. return _this;
  77960. }
  77961. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  77962. var blurRatio = _this._ratio.blurRatio || ratio;
  77963. // Set up assets
  77964. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  77965. _this._createRandomTexture();
  77966. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  77967. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  77968. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  77969. _this._originalColorPostProcess.samples = _this.textureSamples;
  77970. _this._createSSAOPostProcess(1.0);
  77971. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  77972. _this._createSSAOCombinePostProcess(blurRatio);
  77973. // Set up pipeline
  77974. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  77975. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  77976. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  77977. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  77978. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  77979. // Finish
  77980. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77981. if (cameras)
  77982. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77983. return _this;
  77984. }
  77985. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  77986. get: function () {
  77987. return this._samples;
  77988. },
  77989. /**
  77990. * Number of samples used for the SSAO calculations. Default value is 8
  77991. */
  77992. set: function (n) {
  77993. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  77994. this._samples = n;
  77995. this._sampleSphere = this._generateHemisphere();
  77996. this._firstUpdate = true;
  77997. },
  77998. enumerable: true,
  77999. configurable: true
  78000. });
  78001. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  78002. get: function () {
  78003. return this._textureSamples;
  78004. },
  78005. /**
  78006. * Number of samples to use for antialiasing
  78007. */
  78008. set: function (n) {
  78009. this._textureSamples = n;
  78010. this._originalColorPostProcess.samples = n;
  78011. this._blurHPostProcess.samples = n;
  78012. this._blurVPostProcess.samples = n;
  78013. this._ssaoPostProcess.samples = n;
  78014. this._ssaoCombinePostProcess.samples = n;
  78015. },
  78016. enumerable: true,
  78017. configurable: true
  78018. });
  78019. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  78020. get: function () {
  78021. return this._expensiveBlur;
  78022. },
  78023. set: function (b) {
  78024. 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"]);
  78025. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  78026. this._expensiveBlur = b;
  78027. this._firstUpdate = true;
  78028. },
  78029. enumerable: true,
  78030. configurable: true
  78031. });
  78032. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  78033. /**
  78034. * Support test.
  78035. */
  78036. get: function () {
  78037. var engine = BABYLON.Engine.LastCreatedEngine;
  78038. if (!engine) {
  78039. return false;
  78040. }
  78041. return engine.getCaps().drawBuffersExtension;
  78042. },
  78043. enumerable: true,
  78044. configurable: true
  78045. });
  78046. // Public Methods
  78047. /**
  78048. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78049. */
  78050. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  78051. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  78052. for (var i = 0; i < this._scene.cameras.length; i++) {
  78053. var camera = this._scene.cameras[i];
  78054. this._originalColorPostProcess.dispose(camera);
  78055. this._ssaoPostProcess.dispose(camera);
  78056. this._blurHPostProcess.dispose(camera);
  78057. this._blurVPostProcess.dispose(camera);
  78058. this._ssaoCombinePostProcess.dispose(camera);
  78059. }
  78060. this._randomTexture.dispose();
  78061. if (disableGeometryBufferRenderer)
  78062. this._scene.disableGeometryBufferRenderer();
  78063. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78064. _super.prototype.dispose.call(this);
  78065. };
  78066. // Private Methods
  78067. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  78068. var _this = this;
  78069. this._samplerOffsets = [];
  78070. var expensive = this.expensiveBlur;
  78071. for (var i = -8; i < 8; i++) {
  78072. this._samplerOffsets.push(i * 2 + 0.5);
  78073. }
  78074. 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");
  78075. this._blurHPostProcess.onApply = function (effect) {
  78076. if (!_this._scene.activeCamera) {
  78077. return;
  78078. }
  78079. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  78080. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78081. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78082. effect.setFloat("radius", _this.radius);
  78083. effect.setTexture("depthSampler", _this._depthTexture);
  78084. if (_this._firstUpdate) {
  78085. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78086. }
  78087. };
  78088. 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");
  78089. this._blurVPostProcess.onApply = function (effect) {
  78090. if (!_this._scene.activeCamera) {
  78091. return;
  78092. }
  78093. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  78094. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78095. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78096. effect.setFloat("radius", _this.radius);
  78097. effect.setTexture("depthSampler", _this._depthTexture);
  78098. if (_this._firstUpdate) {
  78099. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78100. _this._firstUpdate = false;
  78101. }
  78102. };
  78103. this._blurHPostProcess.samples = this.textureSamples;
  78104. this._blurVPostProcess.samples = this.textureSamples;
  78105. };
  78106. /** @hidden */
  78107. SSAO2RenderingPipeline.prototype._rebuild = function () {
  78108. this._firstUpdate = true;
  78109. _super.prototype._rebuild.call(this);
  78110. };
  78111. //Van der Corput radical inverse
  78112. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  78113. this._bits[0] = i;
  78114. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  78115. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  78116. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  78117. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  78118. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  78119. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  78120. };
  78121. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  78122. return [i / n, this._radicalInverse_VdC(i)];
  78123. };
  78124. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  78125. var phi = v * 2.0 * Math.PI;
  78126. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  78127. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  78128. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  78129. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  78130. };
  78131. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  78132. var numSamples = this.samples;
  78133. var result = [];
  78134. var vector;
  78135. var i = 0;
  78136. while (i < numSamples) {
  78137. if (numSamples < 16) {
  78138. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  78139. }
  78140. else {
  78141. var rand = this._hammersley(i, numSamples);
  78142. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  78143. }
  78144. result.push(vector.x, vector.y, vector.z);
  78145. i++;
  78146. }
  78147. return result;
  78148. };
  78149. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78150. var _this = this;
  78151. var numSamples = this.samples;
  78152. this._sampleSphere = this._generateHemisphere();
  78153. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  78154. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78155. "base", "range", "projection", "near", "far", "texelSize",
  78156. "xViewport", "yViewport", "maxZ", "minZAspect"
  78157. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78158. this._ssaoPostProcess.onApply = function (effect) {
  78159. if (_this._firstUpdate) {
  78160. effect.setArray3("sampleSphere", _this._sampleSphere);
  78161. effect.setFloat("randTextureTiles", 32.0);
  78162. }
  78163. if (!_this._scene.activeCamera) {
  78164. return;
  78165. }
  78166. effect.setFloat("samplesFactor", 1 / _this.samples);
  78167. effect.setFloat("totalStrength", _this.totalStrength);
  78168. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  78169. effect.setFloat("radius", _this.radius);
  78170. effect.setFloat("maxZ", _this.maxZ);
  78171. effect.setFloat("minZAspect", _this.minZAspect);
  78172. effect.setFloat("base", _this.base);
  78173. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78174. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78175. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  78176. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  78177. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  78178. effect.setTexture("textureSampler", _this._depthTexture);
  78179. effect.setTexture("normalSampler", _this._normalTexture);
  78180. effect.setTexture("randomSampler", _this._randomTexture);
  78181. };
  78182. this._ssaoPostProcess.samples = this.textureSamples;
  78183. };
  78184. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78185. var _this = this;
  78186. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78187. this._ssaoCombinePostProcess.onApply = function (effect) {
  78188. var viewport = _this._scene.activeCamera.viewport;
  78189. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  78190. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78191. };
  78192. this._ssaoCombinePostProcess.samples = this.textureSamples;
  78193. };
  78194. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  78195. var size = 128;
  78196. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78197. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78198. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78199. var context = this._randomTexture.getContext();
  78200. var rand = function (min, max) {
  78201. return Math.random() * (max - min) + min;
  78202. };
  78203. var randVector = BABYLON.Vector3.Zero();
  78204. for (var x = 0; x < size; x++) {
  78205. for (var y = 0; y < size; y++) {
  78206. randVector.x = rand(0.0, 1.0);
  78207. randVector.y = rand(0.0, 1.0);
  78208. randVector.z = 0.0;
  78209. randVector.normalize();
  78210. randVector.scaleInPlace(255);
  78211. randVector.x = Math.floor(randVector.x);
  78212. randVector.y = Math.floor(randVector.y);
  78213. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  78214. context.fillRect(x, y, 1, 1);
  78215. }
  78216. }
  78217. this._randomTexture.update(false);
  78218. };
  78219. /**
  78220. * Serialize the rendering pipeline (Used when exporting)
  78221. * @returns the serialized object
  78222. */
  78223. SSAO2RenderingPipeline.prototype.serialize = function () {
  78224. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78225. serializationObject.customType = "SSAO2RenderingPipeline";
  78226. return serializationObject;
  78227. };
  78228. /**
  78229. * Parse the serialized pipeline
  78230. * @param source Source pipeline.
  78231. * @param scene The scene to load the pipeline to.
  78232. * @param rootUrl The URL of the serialized pipeline.
  78233. * @returns An instantiated pipeline from the serialized object.
  78234. */
  78235. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  78236. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  78237. };
  78238. __decorate([
  78239. BABYLON.serialize()
  78240. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  78241. __decorate([
  78242. BABYLON.serialize()
  78243. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  78244. __decorate([
  78245. BABYLON.serialize()
  78246. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  78247. __decorate([
  78248. BABYLON.serialize("samples")
  78249. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  78250. __decorate([
  78251. BABYLON.serialize("textureSamples")
  78252. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  78253. __decorate([
  78254. BABYLON.serialize()
  78255. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  78256. __decorate([
  78257. BABYLON.serialize("expensiveBlur")
  78258. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  78259. __decorate([
  78260. BABYLON.serialize()
  78261. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  78262. __decorate([
  78263. BABYLON.serialize()
  78264. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  78265. return SSAO2RenderingPipeline;
  78266. }(BABYLON.PostProcessRenderPipeline));
  78267. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  78268. })(BABYLON || (BABYLON = {}));
  78269. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  78270. // BABYLON.JS Chromatic Aberration GLSL Shader
  78271. // Author: Olivier Guyot
  78272. // Separates very slightly R, G and B colors on the edges of the screen
  78273. // Inspired by Francois Tarlier & Martins Upitis
  78274. var BABYLON;
  78275. (function (BABYLON) {
  78276. var LensRenderingPipeline = /** @class */ (function (_super) {
  78277. __extends(LensRenderingPipeline, _super);
  78278. /**
  78279. * @constructor
  78280. *
  78281. * Effect parameters are as follow:
  78282. * {
  78283. * chromatic_aberration: number; // from 0 to x (1 for realism)
  78284. * edge_blur: number; // from 0 to x (1 for realism)
  78285. * distortion: number; // from 0 to x (1 for realism)
  78286. * grain_amount: number; // from 0 to 1
  78287. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  78288. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  78289. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  78290. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  78291. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  78292. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  78293. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  78294. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  78295. * }
  78296. * Note: if an effect parameter is unset, effect is disabled
  78297. *
  78298. * @param {string} name - The rendering pipeline name
  78299. * @param {object} parameters - An object containing all parameters (see above)
  78300. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78301. * @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)
  78302. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78303. */
  78304. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  78305. if (ratio === void 0) { ratio = 1.0; }
  78306. var _this = _super.call(this, scene.getEngine(), name) || this;
  78307. // Lens effects can be of the following:
  78308. // - chromatic aberration (slight shift of RGB colors)
  78309. // - blur on the edge of the lens
  78310. // - lens distortion
  78311. // - depth-of-field blur & highlights enhancing
  78312. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  78313. // - grain effect (noise or custom texture)
  78314. // Two additional texture samplers are needed:
  78315. // - depth map (for depth-of-field)
  78316. // - grain texture
  78317. /**
  78318. * The chromatic aberration PostProcess id in the pipeline
  78319. */
  78320. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  78321. /**
  78322. * The highlights enhancing PostProcess id in the pipeline
  78323. */
  78324. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  78325. /**
  78326. * The depth-of-field PostProcess id in the pipeline
  78327. */
  78328. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  78329. _this._scene = scene;
  78330. // Fetch texture samplers
  78331. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  78332. if (parameters.grain_texture) {
  78333. _this._grainTexture = parameters.grain_texture;
  78334. }
  78335. else {
  78336. _this._createGrainTexture();
  78337. }
  78338. // save parameters
  78339. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  78340. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  78341. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  78342. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  78343. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  78344. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  78345. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  78346. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  78347. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  78348. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  78349. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  78350. // Create effects
  78351. _this._createChromaticAberrationPostProcess(ratio);
  78352. _this._createHighlightsPostProcess(ratio);
  78353. _this._createDepthOfFieldPostProcess(ratio / 4);
  78354. // Set up pipeline
  78355. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  78356. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  78357. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  78358. if (_this._highlightsGain === -1) {
  78359. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  78360. }
  78361. // Finish
  78362. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78363. if (cameras) {
  78364. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78365. }
  78366. return _this;
  78367. }
  78368. // public methods (self explanatory)
  78369. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  78370. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  78371. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  78372. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  78373. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  78374. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  78375. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  78376. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  78377. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  78378. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  78379. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  78380. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  78381. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  78382. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  78383. };
  78384. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  78385. this._highlightsPostProcess.updateEffect();
  78386. };
  78387. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  78388. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  78389. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  78390. this._highlightsGain = amount;
  78391. };
  78392. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  78393. if (this._highlightsGain === -1) {
  78394. this._highlightsGain = 1.0;
  78395. }
  78396. this._highlightsThreshold = amount;
  78397. };
  78398. LensRenderingPipeline.prototype.disableHighlights = function () {
  78399. this._highlightsGain = -1;
  78400. };
  78401. /**
  78402. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  78403. */
  78404. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  78405. if (disableDepthRender === void 0) { disableDepthRender = false; }
  78406. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78407. this._chromaticAberrationPostProcess = null;
  78408. this._highlightsPostProcess = null;
  78409. this._depthOfFieldPostProcess = null;
  78410. this._grainTexture.dispose();
  78411. if (disableDepthRender)
  78412. this._scene.disableDepthRenderer();
  78413. };
  78414. // colors shifting and distortion
  78415. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  78416. var _this = this;
  78417. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  78418. [], // samplers
  78419. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78420. this._chromaticAberrationPostProcess.onApply = function (effect) {
  78421. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  78422. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78423. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78424. effect.setFloat('radialIntensity', 1);
  78425. effect.setFloat2('direction', 17, 17);
  78426. effect.setFloat2('centerPosition', 0.5, 0.5);
  78427. };
  78428. };
  78429. // highlights enhancing
  78430. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  78431. var _this = this;
  78432. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  78433. [], // samplers
  78434. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  78435. this._highlightsPostProcess.onApply = function (effect) {
  78436. effect.setFloat('gain', _this._highlightsGain);
  78437. effect.setFloat('threshold', _this._highlightsThreshold);
  78438. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  78439. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78440. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78441. };
  78442. };
  78443. // colors shifting and distortion
  78444. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  78445. var _this = this;
  78446. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  78447. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  78448. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  78449. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78450. this._depthOfFieldPostProcess.onApply = function (effect) {
  78451. effect.setTexture("depthSampler", _this._depthTexture);
  78452. effect.setTexture("grainSampler", _this._grainTexture);
  78453. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  78454. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  78455. effect.setFloat('grain_amount', _this._grainAmount);
  78456. effect.setBool('blur_noise', _this._blurNoise);
  78457. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78458. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78459. effect.setFloat('distortion', _this._distortion);
  78460. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  78461. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  78462. effect.setFloat('aperture', _this._dofAperture);
  78463. effect.setFloat('darken', _this._dofDarken);
  78464. effect.setFloat('edge_blur', _this._edgeBlur);
  78465. effect.setBool('highlights', (_this._highlightsGain !== -1));
  78466. if (_this._scene.activeCamera) {
  78467. effect.setFloat('near', _this._scene.activeCamera.minZ);
  78468. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  78469. }
  78470. };
  78471. };
  78472. // creates a black and white random noise texture, 512x512
  78473. LensRenderingPipeline.prototype._createGrainTexture = function () {
  78474. var size = 512;
  78475. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78476. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78477. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78478. var context = this._grainTexture.getContext();
  78479. var rand = function (min, max) {
  78480. return Math.random() * (max - min) + min;
  78481. };
  78482. var value;
  78483. for (var x = 0; x < size; x++) {
  78484. for (var y = 0; y < size; y++) {
  78485. value = Math.floor(rand(0.42, 0.58) * 255);
  78486. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  78487. context.fillRect(x, y, 1, 1);
  78488. }
  78489. }
  78490. this._grainTexture.update(false);
  78491. };
  78492. return LensRenderingPipeline;
  78493. }(BABYLON.PostProcessRenderPipeline));
  78494. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  78495. })(BABYLON || (BABYLON = {}));
  78496. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  78497. var BABYLON;
  78498. (function (BABYLON) {
  78499. var StandardRenderingPipeline = /** @class */ (function (_super) {
  78500. __extends(StandardRenderingPipeline, _super);
  78501. /**
  78502. * @constructor
  78503. * @param {string} name - The rendering pipeline name
  78504. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78505. * @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)
  78506. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  78507. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78508. */
  78509. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  78510. if (originalPostProcess === void 0) { originalPostProcess = null; }
  78511. var _this = _super.call(this, scene.getEngine(), name) || this;
  78512. /**
  78513. * Post-process used to down scale an image x4
  78514. */
  78515. _this.downSampleX4PostProcess = null;
  78516. /**
  78517. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  78518. */
  78519. _this.brightPassPostProcess = null;
  78520. /**
  78521. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  78522. */
  78523. _this.blurHPostProcesses = [];
  78524. /**
  78525. * Post-process array storing all the vertical blur post-processes used by the pipeline
  78526. */
  78527. _this.blurVPostProcesses = [];
  78528. /**
  78529. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  78530. */
  78531. _this.textureAdderPostProcess = null;
  78532. /**
  78533. * Post-process used to create volumetric lighting effect
  78534. */
  78535. _this.volumetricLightPostProcess = null;
  78536. /**
  78537. * Post-process used to smooth the previous volumetric light post-process on the X axis
  78538. */
  78539. _this.volumetricLightSmoothXPostProcess = null;
  78540. /**
  78541. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  78542. */
  78543. _this.volumetricLightSmoothYPostProcess = null;
  78544. /**
  78545. * Post-process used to merge the volumetric light effect and the real scene color
  78546. */
  78547. _this.volumetricLightMergePostProces = null;
  78548. /**
  78549. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  78550. */
  78551. _this.volumetricLightFinalPostProcess = null;
  78552. /**
  78553. * Base post-process used to calculate the average luminance of the final image for HDR
  78554. */
  78555. _this.luminancePostProcess = null;
  78556. /**
  78557. * Post-processes used to create down sample post-processes in order to get
  78558. * the average luminance of the final image for HDR
  78559. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  78560. */
  78561. _this.luminanceDownSamplePostProcesses = [];
  78562. /**
  78563. * Post-process used to create a HDR effect (light adaptation)
  78564. */
  78565. _this.hdrPostProcess = null;
  78566. /**
  78567. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  78568. */
  78569. _this.textureAdderFinalPostProcess = null;
  78570. /**
  78571. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  78572. */
  78573. _this.lensFlareFinalPostProcess = null;
  78574. /**
  78575. * Post-process used to merge the final HDR post-process and the real scene color
  78576. */
  78577. _this.hdrFinalPostProcess = null;
  78578. /**
  78579. * Post-process used to create a lens flare effect
  78580. */
  78581. _this.lensFlarePostProcess = null;
  78582. /**
  78583. * Post-process that merges the result of the lens flare post-process and the real scene color
  78584. */
  78585. _this.lensFlareComposePostProcess = null;
  78586. /**
  78587. * Post-process used to create a motion blur effect
  78588. */
  78589. _this.motionBlurPostProcess = null;
  78590. /**
  78591. * Post-process used to create a depth of field effect
  78592. */
  78593. _this.depthOfFieldPostProcess = null;
  78594. /**
  78595. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  78596. */
  78597. _this.fxaaPostProcess = null;
  78598. // Values
  78599. /**
  78600. * Represents the brightness threshold in order to configure the illuminated surfaces
  78601. */
  78602. _this.brightThreshold = 1.0;
  78603. /**
  78604. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  78605. */
  78606. _this.blurWidth = 512.0;
  78607. /**
  78608. * Sets if the blur for highlighted surfaces must be only horizontal
  78609. */
  78610. _this.horizontalBlur = false;
  78611. /**
  78612. * Sets the overall exposure used by the pipeline
  78613. */
  78614. _this.exposure = 1.0;
  78615. /**
  78616. * Texture used typically to simulate "dirty" on camera lens
  78617. */
  78618. _this.lensTexture = null;
  78619. /**
  78620. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  78621. */
  78622. _this.volumetricLightCoefficient = 0.2;
  78623. /**
  78624. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  78625. */
  78626. _this.volumetricLightPower = 4.0;
  78627. /**
  78628. * Used the set the blur intensity to smooth the volumetric lights
  78629. */
  78630. _this.volumetricLightBlurScale = 64.0;
  78631. /**
  78632. * Light (spot or directional) used to generate the volumetric lights rays
  78633. * The source light must have a shadow generate so the pipeline can get its
  78634. * depth map
  78635. */
  78636. _this.sourceLight = null;
  78637. /**
  78638. * For eye adaptation, represents the minimum luminance the eye can see
  78639. */
  78640. _this.hdrMinimumLuminance = 1.0;
  78641. /**
  78642. * For eye adaptation, represents the decrease luminance speed
  78643. */
  78644. _this.hdrDecreaseRate = 0.5;
  78645. /**
  78646. * For eye adaptation, represents the increase luminance speed
  78647. */
  78648. _this.hdrIncreaseRate = 0.5;
  78649. /**
  78650. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  78651. */
  78652. _this.lensColorTexture = null;
  78653. /**
  78654. * The overall strengh for the lens flare effect
  78655. */
  78656. _this.lensFlareStrength = 20.0;
  78657. /**
  78658. * Dispersion coefficient for lens flare ghosts
  78659. */
  78660. _this.lensFlareGhostDispersal = 1.4;
  78661. /**
  78662. * Main lens flare halo width
  78663. */
  78664. _this.lensFlareHaloWidth = 0.7;
  78665. /**
  78666. * Based on the lens distortion effect, defines how much the lens flare result
  78667. * is distorted
  78668. */
  78669. _this.lensFlareDistortionStrength = 16.0;
  78670. /**
  78671. * Lens star texture must be used to simulate rays on the flares and is available
  78672. * in the documentation
  78673. */
  78674. _this.lensStarTexture = null;
  78675. /**
  78676. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  78677. * flare effect by taking account of the dirt texture
  78678. */
  78679. _this.lensFlareDirtTexture = null;
  78680. /**
  78681. * Represents the focal length for the depth of field effect
  78682. */
  78683. _this.depthOfFieldDistance = 10.0;
  78684. /**
  78685. * Represents the blur intensity for the blurred part of the depth of field effect
  78686. */
  78687. _this.depthOfFieldBlurWidth = 64.0;
  78688. /**
  78689. * For motion blur, defines how much the image is blurred by the movement
  78690. */
  78691. _this.motionStrength = 1.0;
  78692. /**
  78693. * List of animations for the pipeline (IAnimatable implementation)
  78694. */
  78695. _this.animations = [];
  78696. _this._currentDepthOfFieldSource = null;
  78697. _this._hdrCurrentLuminance = 1.0;
  78698. // Getters and setters
  78699. _this._bloomEnabled = false;
  78700. _this._depthOfFieldEnabled = false;
  78701. _this._vlsEnabled = false;
  78702. _this._lensFlareEnabled = false;
  78703. _this._hdrEnabled = false;
  78704. _this._motionBlurEnabled = false;
  78705. _this._fxaaEnabled = false;
  78706. _this._motionBlurSamples = 64.0;
  78707. _this._volumetricLightStepsCount = 50.0;
  78708. _this._samples = 1;
  78709. _this._cameras = cameras || [];
  78710. // Initialize
  78711. _this._scene = scene;
  78712. _this._basePostProcess = originalPostProcess;
  78713. _this._ratio = ratio;
  78714. // Misc
  78715. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78716. // Finish
  78717. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78718. _this._buildPipeline();
  78719. return _this;
  78720. }
  78721. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  78722. /**
  78723. * Specifies if the bloom pipeline is enabled
  78724. */
  78725. get: function () {
  78726. return this._bloomEnabled;
  78727. },
  78728. set: function (enabled) {
  78729. if (this._bloomEnabled === enabled) {
  78730. return;
  78731. }
  78732. this._bloomEnabled = enabled;
  78733. this._buildPipeline();
  78734. },
  78735. enumerable: true,
  78736. configurable: true
  78737. });
  78738. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  78739. /**
  78740. * Specifies if the depth of field pipeline is enabed
  78741. */
  78742. get: function () {
  78743. return this._depthOfFieldEnabled;
  78744. },
  78745. set: function (enabled) {
  78746. if (this._depthOfFieldEnabled === enabled) {
  78747. return;
  78748. }
  78749. this._depthOfFieldEnabled = enabled;
  78750. this._buildPipeline();
  78751. },
  78752. enumerable: true,
  78753. configurable: true
  78754. });
  78755. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  78756. /**
  78757. * Specifies if the lens flare pipeline is enabed
  78758. */
  78759. get: function () {
  78760. return this._lensFlareEnabled;
  78761. },
  78762. set: function (enabled) {
  78763. if (this._lensFlareEnabled === enabled) {
  78764. return;
  78765. }
  78766. this._lensFlareEnabled = enabled;
  78767. this._buildPipeline();
  78768. },
  78769. enumerable: true,
  78770. configurable: true
  78771. });
  78772. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  78773. /**
  78774. * Specifies if the HDR pipeline is enabled
  78775. */
  78776. get: function () {
  78777. return this._hdrEnabled;
  78778. },
  78779. set: function (enabled) {
  78780. if (this._hdrEnabled === enabled) {
  78781. return;
  78782. }
  78783. this._hdrEnabled = enabled;
  78784. this._buildPipeline();
  78785. },
  78786. enumerable: true,
  78787. configurable: true
  78788. });
  78789. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  78790. /**
  78791. * Specifies if the volumetric lights scattering effect is enabled
  78792. */
  78793. get: function () {
  78794. return this._vlsEnabled;
  78795. },
  78796. set: function (enabled) {
  78797. if (this._vlsEnabled === enabled) {
  78798. return;
  78799. }
  78800. if (enabled) {
  78801. var geometry = this._scene.enableGeometryBufferRenderer();
  78802. if (!geometry) {
  78803. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  78804. return;
  78805. }
  78806. }
  78807. this._vlsEnabled = enabled;
  78808. this._buildPipeline();
  78809. },
  78810. enumerable: true,
  78811. configurable: true
  78812. });
  78813. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  78814. /**
  78815. * Specifies if the motion blur effect is enabled
  78816. */
  78817. get: function () {
  78818. return this._motionBlurEnabled;
  78819. },
  78820. set: function (enabled) {
  78821. if (this._motionBlurEnabled === enabled) {
  78822. return;
  78823. }
  78824. this._motionBlurEnabled = enabled;
  78825. this._buildPipeline();
  78826. },
  78827. enumerable: true,
  78828. configurable: true
  78829. });
  78830. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  78831. /**
  78832. * Specifies if anti-aliasing is enabled
  78833. */
  78834. get: function () {
  78835. return this._fxaaEnabled;
  78836. },
  78837. set: function (enabled) {
  78838. if (this._fxaaEnabled === enabled) {
  78839. return;
  78840. }
  78841. this._fxaaEnabled = enabled;
  78842. this._buildPipeline();
  78843. },
  78844. enumerable: true,
  78845. configurable: true
  78846. });
  78847. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  78848. /**
  78849. * Specifies the number of steps used to calculate the volumetric lights
  78850. * Typically in interval [50, 200]
  78851. */
  78852. get: function () {
  78853. return this._volumetricLightStepsCount;
  78854. },
  78855. set: function (count) {
  78856. if (this.volumetricLightPostProcess) {
  78857. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  78858. }
  78859. this._volumetricLightStepsCount = count;
  78860. },
  78861. enumerable: true,
  78862. configurable: true
  78863. });
  78864. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  78865. /**
  78866. * Specifies the number of samples used for the motion blur effect
  78867. * Typically in interval [16, 64]
  78868. */
  78869. get: function () {
  78870. return this._motionBlurSamples;
  78871. },
  78872. set: function (samples) {
  78873. if (this.motionBlurPostProcess) {
  78874. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  78875. }
  78876. this._motionBlurSamples = samples;
  78877. },
  78878. enumerable: true,
  78879. configurable: true
  78880. });
  78881. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  78882. /**
  78883. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  78884. */
  78885. get: function () {
  78886. return this._samples;
  78887. },
  78888. set: function (sampleCount) {
  78889. if (this._samples === sampleCount) {
  78890. return;
  78891. }
  78892. this._samples = sampleCount;
  78893. this._buildPipeline();
  78894. },
  78895. enumerable: true,
  78896. configurable: true
  78897. });
  78898. StandardRenderingPipeline.prototype._buildPipeline = function () {
  78899. var _this = this;
  78900. var ratio = this._ratio;
  78901. var scene = this._scene;
  78902. this._disposePostProcesses();
  78903. this._reset();
  78904. // Create pass post-process
  78905. if (!this._basePostProcess) {
  78906. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  78907. this.originalPostProcess.onApply = function (effect) {
  78908. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  78909. };
  78910. }
  78911. else {
  78912. this.originalPostProcess = this._basePostProcess;
  78913. }
  78914. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  78915. this._currentDepthOfFieldSource = this.originalPostProcess;
  78916. if (this._bloomEnabled) {
  78917. // Create down sample X4 post-process
  78918. this._createDownSampleX4PostProcess(scene, ratio / 2);
  78919. // Create bright pass post-process
  78920. this._createBrightPassPostProcess(scene, ratio / 2);
  78921. // Create gaussian blur post-processes (down sampling blurs)
  78922. this._createBlurPostProcesses(scene, ratio / 4, 1);
  78923. // Create texture adder post-process
  78924. this._createTextureAdderPostProcess(scene, ratio);
  78925. // Create depth-of-field source post-process
  78926. 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);
  78927. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  78928. }
  78929. if (this._vlsEnabled) {
  78930. // Create volumetric light
  78931. this._createVolumetricLightPostProcess(scene, ratio);
  78932. // Create volumetric light final post-process
  78933. 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);
  78934. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  78935. }
  78936. if (this._lensFlareEnabled) {
  78937. // Create lens flare post-process
  78938. this._createLensFlarePostProcess(scene, ratio);
  78939. // Create depth-of-field source post-process post lens-flare and disable it now
  78940. 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);
  78941. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  78942. }
  78943. if (this._hdrEnabled) {
  78944. // Create luminance
  78945. this._createLuminancePostProcesses(scene, this._floatTextureType);
  78946. // Create HDR
  78947. this._createHdrPostProcess(scene, ratio);
  78948. // Create depth-of-field source post-process post hdr and disable it now
  78949. 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);
  78950. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  78951. }
  78952. if (this._depthOfFieldEnabled) {
  78953. // Create gaussian blur used by depth-of-field
  78954. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  78955. // Create depth-of-field post-process
  78956. this._createDepthOfFieldPostProcess(scene, ratio);
  78957. }
  78958. if (this._motionBlurEnabled) {
  78959. // Create motion blur post-process
  78960. this._createMotionBlurPostProcess(scene, ratio);
  78961. }
  78962. if (this._fxaaEnabled) {
  78963. // Create fxaa post-process
  78964. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78965. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  78966. }
  78967. if (this._cameras !== null) {
  78968. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  78969. }
  78970. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  78971. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  78972. }
  78973. };
  78974. // Down Sample X4 Post-Processs
  78975. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  78976. var _this = this;
  78977. var downSampleX4Offsets = new Array(32);
  78978. 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);
  78979. this.downSampleX4PostProcess.onApply = function (effect) {
  78980. var id = 0;
  78981. var width = _this.downSampleX4PostProcess.width;
  78982. var height = _this.downSampleX4PostProcess.height;
  78983. for (var i = -2; i < 2; i++) {
  78984. for (var j = -2; j < 2; j++) {
  78985. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  78986. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  78987. id += 2;
  78988. }
  78989. }
  78990. effect.setArray2("dsOffsets", downSampleX4Offsets);
  78991. };
  78992. // Add to pipeline
  78993. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  78994. };
  78995. // Brightpass Post-Process
  78996. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  78997. var _this = this;
  78998. var brightOffsets = new Array(8);
  78999. 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);
  79000. this.brightPassPostProcess.onApply = function (effect) {
  79001. var sU = (1.0 / _this.brightPassPostProcess.width);
  79002. var sV = (1.0 / _this.brightPassPostProcess.height);
  79003. brightOffsets[0] = -0.5 * sU;
  79004. brightOffsets[1] = 0.5 * sV;
  79005. brightOffsets[2] = 0.5 * sU;
  79006. brightOffsets[3] = 0.5 * sV;
  79007. brightOffsets[4] = -0.5 * sU;
  79008. brightOffsets[5] = -0.5 * sV;
  79009. brightOffsets[6] = 0.5 * sU;
  79010. brightOffsets[7] = -0.5 * sV;
  79011. effect.setArray2("dsOffsets", brightOffsets);
  79012. effect.setFloat("brightThreshold", _this.brightThreshold);
  79013. };
  79014. // Add to pipeline
  79015. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  79016. };
  79017. // Create blur H&V post-processes
  79018. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  79019. var _this = this;
  79020. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  79021. var engine = scene.getEngine();
  79022. 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);
  79023. 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);
  79024. blurX.onActivateObservable.add(function () {
  79025. var dw = blurX.width / engine.getRenderWidth();
  79026. blurX.kernel = _this[blurWidthKey] * dw;
  79027. });
  79028. blurY.onActivateObservable.add(function () {
  79029. var dw = blurY.height / engine.getRenderHeight();
  79030. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  79031. });
  79032. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  79033. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  79034. this.blurHPostProcesses.push(blurX);
  79035. this.blurVPostProcesses.push(blurY);
  79036. };
  79037. // Create texture adder post-process
  79038. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  79039. var _this = this;
  79040. 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);
  79041. this.textureAdderPostProcess.onApply = function (effect) {
  79042. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  79043. effect.setTexture("lensSampler", _this.lensTexture);
  79044. effect.setFloat("exposure", _this.exposure);
  79045. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  79046. };
  79047. // Add to pipeline
  79048. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  79049. };
  79050. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  79051. var _this = this;
  79052. var geometryRenderer = scene.enableGeometryBufferRenderer();
  79053. geometryRenderer.enablePosition = true;
  79054. var geometry = geometryRenderer.getGBuffer();
  79055. // Base post-process
  79056. 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));
  79057. var depthValues = BABYLON.Vector2.Zero();
  79058. this.volumetricLightPostProcess.onApply = function (effect) {
  79059. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  79060. var generator = _this.sourceLight.getShadowGenerator();
  79061. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  79062. effect.setTexture("positionSampler", geometry.textures[2]);
  79063. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  79064. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  79065. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  79066. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  79067. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  79068. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  79069. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  79070. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  79071. effect.setVector2("depthValues", depthValues);
  79072. }
  79073. };
  79074. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  79075. // Smooth
  79076. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  79077. // Merge
  79078. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  79079. this.volumetricLightMergePostProces.onApply = function (effect) {
  79080. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  79081. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  79082. };
  79083. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  79084. };
  79085. // Create luminance
  79086. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  79087. var _this = this;
  79088. // Create luminance
  79089. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  79090. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  79091. var offsets = [];
  79092. this.luminancePostProcess.onApply = function (effect) {
  79093. var sU = (1.0 / _this.luminancePostProcess.width);
  79094. var sV = (1.0 / _this.luminancePostProcess.height);
  79095. offsets[0] = -0.5 * sU;
  79096. offsets[1] = 0.5 * sV;
  79097. offsets[2] = 0.5 * sU;
  79098. offsets[3] = 0.5 * sV;
  79099. offsets[4] = -0.5 * sU;
  79100. offsets[5] = -0.5 * sV;
  79101. offsets[6] = 0.5 * sU;
  79102. offsets[7] = -0.5 * sV;
  79103. effect.setArray2("lumOffsets", offsets);
  79104. };
  79105. // Add to pipeline
  79106. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  79107. // Create down sample luminance
  79108. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  79109. var size = Math.pow(3, i);
  79110. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  79111. if (i === 0) {
  79112. defines += "#define FINAL_DOWN_SAMPLER";
  79113. }
  79114. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  79115. this.luminanceDownSamplePostProcesses.push(postProcess);
  79116. }
  79117. // Create callbacks and add effects
  79118. var lastLuminance = this.luminancePostProcess;
  79119. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  79120. var downSampleOffsets = new Array(18);
  79121. pp.onApply = function (effect) {
  79122. if (!lastLuminance) {
  79123. return;
  79124. }
  79125. var id = 0;
  79126. for (var x = -1; x < 2; x++) {
  79127. for (var y = -1; y < 2; y++) {
  79128. downSampleOffsets[id] = x / lastLuminance.width;
  79129. downSampleOffsets[id + 1] = y / lastLuminance.height;
  79130. id += 2;
  79131. }
  79132. }
  79133. effect.setArray2("dsOffsets", downSampleOffsets);
  79134. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  79135. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  79136. lastLuminance = _this.luminancePostProcess;
  79137. }
  79138. else {
  79139. lastLuminance = pp;
  79140. }
  79141. };
  79142. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  79143. pp.onAfterRender = function (effect) {
  79144. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  79145. 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);
  79146. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  79147. };
  79148. }
  79149. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  79150. });
  79151. };
  79152. // Create HDR post-process
  79153. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  79154. var _this = this;
  79155. 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);
  79156. var outputLiminance = 1;
  79157. var time = 0;
  79158. var lastTime = 0;
  79159. this.hdrPostProcess.onApply = function (effect) {
  79160. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  79161. time += scene.getEngine().getDeltaTime();
  79162. if (outputLiminance < 0) {
  79163. outputLiminance = _this._hdrCurrentLuminance;
  79164. }
  79165. else {
  79166. var dt = (lastTime - time) / 1000.0;
  79167. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  79168. outputLiminance += _this.hdrDecreaseRate * dt;
  79169. }
  79170. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  79171. outputLiminance -= _this.hdrIncreaseRate * dt;
  79172. }
  79173. else {
  79174. outputLiminance = _this._hdrCurrentLuminance;
  79175. }
  79176. }
  79177. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  79178. effect.setFloat("averageLuminance", outputLiminance);
  79179. lastTime = time;
  79180. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  79181. };
  79182. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  79183. };
  79184. // Create lens flare post-process
  79185. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  79186. var _this = this;
  79187. 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);
  79188. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  79189. this._createBlurPostProcesses(scene, ratio / 4, 2);
  79190. 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);
  79191. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  79192. var resolution = new BABYLON.Vector2(0, 0);
  79193. // Lens flare
  79194. this.lensFlarePostProcess.onApply = function (effect) {
  79195. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  79196. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  79197. effect.setFloat("strength", _this.lensFlareStrength);
  79198. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  79199. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  79200. // Shift
  79201. resolution.x = _this.lensFlarePostProcess.width;
  79202. resolution.y = _this.lensFlarePostProcess.height;
  79203. effect.setVector2("resolution", resolution);
  79204. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  79205. };
  79206. // Compose
  79207. 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);
  79208. 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);
  79209. this.lensFlareComposePostProcess.onApply = function (effect) {
  79210. if (!_this._scene.activeCamera) {
  79211. return;
  79212. }
  79213. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  79214. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  79215. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  79216. // Lens start rotation matrix
  79217. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  79218. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  79219. 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));
  79220. camRot *= 4.0;
  79221. 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);
  79222. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  79223. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  79224. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  79225. };
  79226. };
  79227. // Create depth-of-field post-process
  79228. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  79229. var _this = this;
  79230. 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);
  79231. this.depthOfFieldPostProcess.onApply = function (effect) {
  79232. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  79233. effect.setTexture("depthSampler", _this._getDepthTexture());
  79234. effect.setFloat("distance", _this.depthOfFieldDistance);
  79235. };
  79236. // Add to pipeline
  79237. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  79238. };
  79239. // Create motion blur post-process
  79240. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  79241. var _this = this;
  79242. 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);
  79243. var motionScale = 0;
  79244. var prevViewProjection = BABYLON.Matrix.Identity();
  79245. var invViewProjection = BABYLON.Matrix.Identity();
  79246. var viewProjection = BABYLON.Matrix.Identity();
  79247. var screenSize = BABYLON.Vector2.Zero();
  79248. this.motionBlurPostProcess.onApply = function (effect) {
  79249. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  79250. viewProjection.invertToRef(invViewProjection);
  79251. effect.setMatrix("inverseViewProjection", invViewProjection);
  79252. effect.setMatrix("prevViewProjection", prevViewProjection);
  79253. prevViewProjection = viewProjection;
  79254. screenSize.x = _this.motionBlurPostProcess.width;
  79255. screenSize.y = _this.motionBlurPostProcess.height;
  79256. effect.setVector2("screenSize", screenSize);
  79257. motionScale = scene.getEngine().getFps() / 60.0;
  79258. effect.setFloat("motionScale", motionScale);
  79259. effect.setFloat("motionStrength", _this.motionStrength);
  79260. effect.setTexture("depthSampler", _this._getDepthTexture());
  79261. };
  79262. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  79263. };
  79264. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  79265. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  79266. var renderer = this._scene.enableGeometryBufferRenderer();
  79267. return renderer.getGBuffer().textures[0];
  79268. }
  79269. return this._scene.enableDepthRenderer().getDepthMap();
  79270. };
  79271. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  79272. for (var i = 0; i < this._cameras.length; i++) {
  79273. var camera = this._cameras[i];
  79274. if (this.originalPostProcess) {
  79275. this.originalPostProcess.dispose(camera);
  79276. }
  79277. if (this.downSampleX4PostProcess) {
  79278. this.downSampleX4PostProcess.dispose(camera);
  79279. }
  79280. if (this.brightPassPostProcess) {
  79281. this.brightPassPostProcess.dispose(camera);
  79282. }
  79283. if (this.textureAdderPostProcess) {
  79284. this.textureAdderPostProcess.dispose(camera);
  79285. }
  79286. if (this.textureAdderFinalPostProcess) {
  79287. this.textureAdderFinalPostProcess.dispose(camera);
  79288. }
  79289. if (this.volumetricLightPostProcess) {
  79290. this.volumetricLightPostProcess.dispose(camera);
  79291. }
  79292. if (this.volumetricLightSmoothXPostProcess) {
  79293. this.volumetricLightSmoothXPostProcess.dispose(camera);
  79294. }
  79295. if (this.volumetricLightSmoothYPostProcess) {
  79296. this.volumetricLightSmoothYPostProcess.dispose(camera);
  79297. }
  79298. if (this.volumetricLightMergePostProces) {
  79299. this.volumetricLightMergePostProces.dispose(camera);
  79300. }
  79301. if (this.volumetricLightFinalPostProcess) {
  79302. this.volumetricLightFinalPostProcess.dispose(camera);
  79303. }
  79304. if (this.lensFlarePostProcess) {
  79305. this.lensFlarePostProcess.dispose(camera);
  79306. }
  79307. if (this.lensFlareComposePostProcess) {
  79308. this.lensFlareComposePostProcess.dispose(camera);
  79309. }
  79310. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  79311. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  79312. }
  79313. if (this.luminancePostProcess) {
  79314. this.luminancePostProcess.dispose(camera);
  79315. }
  79316. if (this.hdrPostProcess) {
  79317. this.hdrPostProcess.dispose(camera);
  79318. }
  79319. if (this.hdrFinalPostProcess) {
  79320. this.hdrFinalPostProcess.dispose(camera);
  79321. }
  79322. if (this.depthOfFieldPostProcess) {
  79323. this.depthOfFieldPostProcess.dispose(camera);
  79324. }
  79325. if (this.motionBlurPostProcess) {
  79326. this.motionBlurPostProcess.dispose(camera);
  79327. }
  79328. if (this.fxaaPostProcess) {
  79329. this.fxaaPostProcess.dispose(camera);
  79330. }
  79331. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  79332. this.blurHPostProcesses[j].dispose(camera);
  79333. }
  79334. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  79335. this.blurVPostProcesses[j].dispose(camera);
  79336. }
  79337. }
  79338. this.originalPostProcess = null;
  79339. this.downSampleX4PostProcess = null;
  79340. this.brightPassPostProcess = null;
  79341. this.textureAdderPostProcess = null;
  79342. this.textureAdderFinalPostProcess = null;
  79343. this.volumetricLightPostProcess = null;
  79344. this.volumetricLightSmoothXPostProcess = null;
  79345. this.volumetricLightSmoothYPostProcess = null;
  79346. this.volumetricLightMergePostProces = null;
  79347. this.volumetricLightFinalPostProcess = null;
  79348. this.lensFlarePostProcess = null;
  79349. this.lensFlareComposePostProcess = null;
  79350. this.luminancePostProcess = null;
  79351. this.hdrPostProcess = null;
  79352. this.hdrFinalPostProcess = null;
  79353. this.depthOfFieldPostProcess = null;
  79354. this.motionBlurPostProcess = null;
  79355. this.fxaaPostProcess = null;
  79356. this.luminanceDownSamplePostProcesses = [];
  79357. this.blurHPostProcesses = [];
  79358. this.blurVPostProcesses = [];
  79359. };
  79360. /**
  79361. * Dispose of the pipeline and stop all post processes
  79362. */
  79363. StandardRenderingPipeline.prototype.dispose = function () {
  79364. this._disposePostProcesses();
  79365. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  79366. _super.prototype.dispose.call(this);
  79367. };
  79368. /**
  79369. * Serialize the rendering pipeline (Used when exporting)
  79370. * @returns the serialized object
  79371. */
  79372. StandardRenderingPipeline.prototype.serialize = function () {
  79373. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79374. if (this.sourceLight) {
  79375. serializationObject.sourceLightId = this.sourceLight.id;
  79376. }
  79377. serializationObject.customType = "StandardRenderingPipeline";
  79378. return serializationObject;
  79379. };
  79380. /**
  79381. * Parse the serialized pipeline
  79382. * @param source Source pipeline.
  79383. * @param scene The scene to load the pipeline to.
  79384. * @param rootUrl The URL of the serialized pipeline.
  79385. * @returns An instantiated pipeline from the serialized object.
  79386. */
  79387. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  79388. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  79389. if (source.sourceLightId) {
  79390. p.sourceLight = scene.getLightByID(source.sourceLightId);
  79391. }
  79392. return p;
  79393. };
  79394. // Luminance steps
  79395. StandardRenderingPipeline.LuminanceSteps = 6;
  79396. __decorate([
  79397. BABYLON.serialize()
  79398. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  79399. __decorate([
  79400. BABYLON.serialize()
  79401. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  79402. __decorate([
  79403. BABYLON.serialize()
  79404. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  79405. __decorate([
  79406. BABYLON.serialize()
  79407. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  79408. __decorate([
  79409. BABYLON.serializeAsTexture("lensTexture")
  79410. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  79411. __decorate([
  79412. BABYLON.serialize()
  79413. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  79414. __decorate([
  79415. BABYLON.serialize()
  79416. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  79417. __decorate([
  79418. BABYLON.serialize()
  79419. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  79420. __decorate([
  79421. BABYLON.serialize()
  79422. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  79423. __decorate([
  79424. BABYLON.serialize()
  79425. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  79426. __decorate([
  79427. BABYLON.serialize()
  79428. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  79429. __decorate([
  79430. BABYLON.serializeAsTexture("lensColorTexture")
  79431. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  79432. __decorate([
  79433. BABYLON.serialize()
  79434. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  79435. __decorate([
  79436. BABYLON.serialize()
  79437. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  79438. __decorate([
  79439. BABYLON.serialize()
  79440. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  79441. __decorate([
  79442. BABYLON.serialize()
  79443. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  79444. __decorate([
  79445. BABYLON.serializeAsTexture("lensStarTexture")
  79446. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  79447. __decorate([
  79448. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  79449. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  79450. __decorate([
  79451. BABYLON.serialize()
  79452. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  79453. __decorate([
  79454. BABYLON.serialize()
  79455. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  79456. __decorate([
  79457. BABYLON.serialize()
  79458. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  79459. __decorate([
  79460. BABYLON.serialize()
  79461. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  79462. __decorate([
  79463. BABYLON.serialize()
  79464. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  79465. __decorate([
  79466. BABYLON.serialize()
  79467. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  79468. __decorate([
  79469. BABYLON.serialize()
  79470. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  79471. __decorate([
  79472. BABYLON.serialize()
  79473. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  79474. __decorate([
  79475. BABYLON.serialize()
  79476. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  79477. __decorate([
  79478. BABYLON.serialize()
  79479. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  79480. __decorate([
  79481. BABYLON.serialize()
  79482. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  79483. __decorate([
  79484. BABYLON.serialize()
  79485. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  79486. __decorate([
  79487. BABYLON.serialize()
  79488. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  79489. __decorate([
  79490. BABYLON.serialize()
  79491. ], StandardRenderingPipeline.prototype, "samples", null);
  79492. return StandardRenderingPipeline;
  79493. }(BABYLON.PostProcessRenderPipeline));
  79494. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  79495. })(BABYLON || (BABYLON = {}));
  79496. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  79497. var BABYLON;
  79498. (function (BABYLON) {
  79499. var FxaaPostProcess = /** @class */ (function (_super) {
  79500. __extends(FxaaPostProcess, _super);
  79501. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79502. if (camera === void 0) { camera = null; }
  79503. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79504. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  79505. var defines = _this._getDefines();
  79506. _this.updateEffect(defines);
  79507. _this.onApplyObservable.add(function (effect) {
  79508. var texelSize = _this.texelSize;
  79509. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  79510. });
  79511. return _this;
  79512. }
  79513. FxaaPostProcess.prototype._getDefines = function () {
  79514. var engine = this.getEngine();
  79515. if (!engine) {
  79516. return null;
  79517. }
  79518. var glInfo = engine.getGlInfo();
  79519. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  79520. return "#define MALI 1\n";
  79521. }
  79522. return null;
  79523. };
  79524. return FxaaPostProcess;
  79525. }(BABYLON.PostProcess));
  79526. BABYLON.FxaaPostProcess = FxaaPostProcess;
  79527. })(BABYLON || (BABYLON = {}));
  79528. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  79529. var BABYLON;
  79530. (function (BABYLON) {
  79531. /**
  79532. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  79533. */
  79534. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  79535. __extends(ChromaticAberrationPostProcess, _super);
  79536. /**
  79537. * Creates a new instance ChromaticAberrationPostProcess
  79538. * @param name The name of the effect.
  79539. * @param screenWidth The width of the screen to apply the effect on.
  79540. * @param screenHeight The height of the screen to apply the effect on.
  79541. * @param options The required width/height ratio to downsize to before computing the render pass.
  79542. * @param camera The camera to apply the render pass to.
  79543. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79544. * @param engine The engine which the post process will be applied. (default: current engine)
  79545. * @param reusable If the post process can be reused on the same frame. (default: false)
  79546. * @param textureType Type of textures used when performing the post process. (default: 0)
  79547. * @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)
  79548. */
  79549. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79550. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79551. if (blockCompilation === void 0) { blockCompilation = false; }
  79552. 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;
  79553. /**
  79554. * The amount of seperation of rgb channels (default: 30)
  79555. */
  79556. _this.aberrationAmount = 30;
  79557. /**
  79558. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  79559. */
  79560. _this.radialIntensity = 0;
  79561. /**
  79562. * 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))
  79563. */
  79564. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  79565. /**
  79566. * 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))
  79567. */
  79568. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  79569. _this.onApplyObservable.add(function (effect) {
  79570. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  79571. effect.setFloat('screen_width', screenWidth);
  79572. effect.setFloat('screen_height', screenHeight);
  79573. effect.setFloat('radialIntensity', _this.radialIntensity);
  79574. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  79575. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  79576. });
  79577. return _this;
  79578. }
  79579. return ChromaticAberrationPostProcess;
  79580. }(BABYLON.PostProcess));
  79581. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  79582. })(BABYLON || (BABYLON = {}));
  79583. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  79584. var BABYLON;
  79585. (function (BABYLON) {
  79586. /**
  79587. * The GrainPostProcess adds noise to the image at mid luminance levels
  79588. */
  79589. var GrainPostProcess = /** @class */ (function (_super) {
  79590. __extends(GrainPostProcess, _super);
  79591. /**
  79592. * Creates a new instance of @see GrainPostProcess
  79593. * @param name The name of the effect.
  79594. * @param options The required width/height ratio to downsize to before computing the render pass.
  79595. * @param camera The camera to apply the render pass to.
  79596. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79597. * @param engine The engine which the post process will be applied. (default: current engine)
  79598. * @param reusable If the post process can be reused on the same frame. (default: false)
  79599. * @param textureType Type of textures used when performing the post process. (default: 0)
  79600. * @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)
  79601. */
  79602. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79603. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79604. if (blockCompilation === void 0) { blockCompilation = false; }
  79605. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79606. /**
  79607. * The intensity of the grain added (default: 30)
  79608. */
  79609. _this.intensity = 30;
  79610. /**
  79611. * If the grain should be randomized on every frame
  79612. */
  79613. _this.animated = false;
  79614. _this.onApplyObservable.add(function (effect) {
  79615. effect.setFloat('intensity', _this.intensity);
  79616. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  79617. });
  79618. return _this;
  79619. }
  79620. return GrainPostProcess;
  79621. }(BABYLON.PostProcess));
  79622. BABYLON.GrainPostProcess = GrainPostProcess;
  79623. })(BABYLON || (BABYLON = {}));
  79624. //# sourceMappingURL=babylon.grainPostProcess.js.map
  79625. var BABYLON;
  79626. (function (BABYLON) {
  79627. /**
  79628. * The SharpenPostProcess applies a sharpen kernel to every pixel
  79629. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  79630. */
  79631. var SharpenPostProcess = /** @class */ (function (_super) {
  79632. __extends(SharpenPostProcess, _super);
  79633. /**
  79634. * Creates a new instance ConvolutionPostProcess
  79635. * @param name The name of the effect.
  79636. * @param options The required width/height ratio to downsize to before computing the render pass.
  79637. * @param camera The camera to apply the render pass to.
  79638. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79639. * @param engine The engine which the post process will be applied. (default: current engine)
  79640. * @param reusable If the post process can be reused on the same frame. (default: false)
  79641. * @param textureType Type of textures used when performing the post process. (default: 0)
  79642. * @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)
  79643. */
  79644. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79645. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79646. if (blockCompilation === void 0) { blockCompilation = false; }
  79647. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79648. /**
  79649. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  79650. */
  79651. _this.colorAmount = 1.0;
  79652. /**
  79653. * How much sharpness should be applied (default: 0.3)
  79654. */
  79655. _this.edgeAmount = 0.3;
  79656. _this.onApply = function (effect) {
  79657. effect.setFloat2("screenSize", _this.width, _this.height);
  79658. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  79659. };
  79660. return _this;
  79661. }
  79662. return SharpenPostProcess;
  79663. }(BABYLON.PostProcess));
  79664. BABYLON.SharpenPostProcess = SharpenPostProcess;
  79665. })(BABYLON || (BABYLON = {}));
  79666. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  79667. var BABYLON;
  79668. (function (BABYLON) {
  79669. /**
  79670. * The Blur Post Process which blurs an image based on a kernel and direction.
  79671. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  79672. */
  79673. var BlurPostProcess = /** @class */ (function (_super) {
  79674. __extends(BlurPostProcess, _super);
  79675. /**
  79676. * Creates a new instance BlurPostProcess
  79677. * @param name The name of the effect.
  79678. * @param direction The direction in which to blur the image.
  79679. * @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.
  79680. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  79681. * @param camera The camera to apply the render pass to.
  79682. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79683. * @param engine The engine which the post process will be applied. (default: current engine)
  79684. * @param reusable If the post process can be reused on the same frame. (default: false)
  79685. * @param textureType Type of textures used when performing the post process. (default: 0)
  79686. * @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)
  79687. */
  79688. function BlurPostProcess(name,
  79689. /** The direction in which to blur the image. */
  79690. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  79691. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79692. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79693. if (defines === void 0) { defines = ""; }
  79694. if (blockCompilation === void 0) { blockCompilation = false; }
  79695. 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;
  79696. _this.direction = direction;
  79697. _this.blockCompilation = blockCompilation;
  79698. _this._packedFloat = false;
  79699. _this._staticDefines = "";
  79700. _this._staticDefines = defines;
  79701. _this.onApplyObservable.add(function (effect) {
  79702. if (_this._outputTexture) {
  79703. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  79704. }
  79705. else {
  79706. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  79707. }
  79708. });
  79709. _this.kernel = kernel;
  79710. return _this;
  79711. }
  79712. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  79713. /**
  79714. * Gets the length in pixels of the blur sample region
  79715. */
  79716. get: function () {
  79717. return this._idealKernel;
  79718. },
  79719. /**
  79720. * Sets the length in pixels of the blur sample region
  79721. */
  79722. set: function (v) {
  79723. if (this._idealKernel === v) {
  79724. return;
  79725. }
  79726. v = Math.max(v, 1);
  79727. this._idealKernel = v;
  79728. this._kernel = this._nearestBestKernel(v);
  79729. if (!this.blockCompilation) {
  79730. this._updateParameters();
  79731. }
  79732. },
  79733. enumerable: true,
  79734. configurable: true
  79735. });
  79736. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  79737. /**
  79738. * Gets wether or not the blur is unpacking/repacking floats
  79739. */
  79740. get: function () {
  79741. return this._packedFloat;
  79742. },
  79743. /**
  79744. * Sets wether or not the blur needs to unpack/repack floats
  79745. */
  79746. set: function (v) {
  79747. if (this._packedFloat === v) {
  79748. return;
  79749. }
  79750. this._packedFloat = v;
  79751. if (!this.blockCompilation) {
  79752. this._updateParameters();
  79753. }
  79754. },
  79755. enumerable: true,
  79756. configurable: true
  79757. });
  79758. /**
  79759. * Updates the effect with the current post process compile time values and recompiles the shader.
  79760. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  79761. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  79762. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  79763. * @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
  79764. * @param onCompiled Called when the shader has been compiled.
  79765. * @param onError Called if there is an error when compiling a shader.
  79766. */
  79767. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  79768. if (defines === void 0) { defines = null; }
  79769. if (uniforms === void 0) { uniforms = null; }
  79770. if (samplers === void 0) { samplers = null; }
  79771. this._updateParameters(onCompiled, onError);
  79772. };
  79773. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  79774. // Generate sampling offsets and weights
  79775. var N = this._kernel;
  79776. var centerIndex = (N - 1) / 2;
  79777. // Generate Gaussian sampling weights over kernel
  79778. var offsets = [];
  79779. var weights = [];
  79780. var totalWeight = 0;
  79781. for (var i = 0; i < N; i++) {
  79782. var u = i / (N - 1);
  79783. var w = this._gaussianWeight(u * 2.0 - 1);
  79784. offsets[i] = (i - centerIndex);
  79785. weights[i] = w;
  79786. totalWeight += w;
  79787. }
  79788. // Normalize weights
  79789. for (var i = 0; i < weights.length; i++) {
  79790. weights[i] /= totalWeight;
  79791. }
  79792. // Optimize: combine samples to take advantage of hardware linear sampling
  79793. // Walk from left to center, combining pairs (symmetrically)
  79794. var linearSamplingWeights = [];
  79795. var linearSamplingOffsets = [];
  79796. var linearSamplingMap = [];
  79797. for (var i = 0; i <= centerIndex; i += 2) {
  79798. var j = Math.min(i + 1, Math.floor(centerIndex));
  79799. var singleCenterSample = i === j;
  79800. if (singleCenterSample) {
  79801. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  79802. }
  79803. else {
  79804. var sharedCell = j === centerIndex;
  79805. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  79806. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  79807. if (offsetLinear === 0) {
  79808. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  79809. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  79810. }
  79811. else {
  79812. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  79813. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  79814. }
  79815. }
  79816. }
  79817. for (var i = 0; i < linearSamplingMap.length; i++) {
  79818. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  79819. linearSamplingWeights[i] = linearSamplingMap[i].w;
  79820. }
  79821. // Replace with optimized
  79822. offsets = linearSamplingOffsets;
  79823. weights = linearSamplingWeights;
  79824. // Generate shaders
  79825. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  79826. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  79827. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  79828. var defines = "";
  79829. defines += this._staticDefines;
  79830. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  79831. if (this._staticDefines.indexOf("DOF") != -1) {
  79832. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  79833. varyingCount--;
  79834. }
  79835. for (var i = 0; i < varyingCount; i++) {
  79836. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  79837. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  79838. }
  79839. var depCount = 0;
  79840. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  79841. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  79842. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  79843. depCount++;
  79844. }
  79845. if (this.packedFloat) {
  79846. defines += "#define PACKEDFLOAT 1";
  79847. }
  79848. this.blockCompilation = false;
  79849. _super.prototype.updateEffect.call(this, defines, null, null, {
  79850. varyingCount: varyingCount,
  79851. depCount: depCount
  79852. }, onCompiled, onError);
  79853. };
  79854. /**
  79855. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  79856. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  79857. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  79858. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  79859. * The gaps between physical kernels are compensated for in the weighting of the samples
  79860. * @param idealKernel Ideal blur kernel.
  79861. * @return Nearest best kernel.
  79862. */
  79863. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  79864. var v = Math.round(idealKernel);
  79865. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  79866. var k = _a[_i];
  79867. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  79868. return Math.max(k, 3);
  79869. }
  79870. }
  79871. return Math.max(v, 3);
  79872. };
  79873. /**
  79874. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  79875. * @param x The point on the Gaussian distribution to sample.
  79876. * @return the value of the Gaussian function at x.
  79877. */
  79878. BlurPostProcess.prototype._gaussianWeight = function (x) {
  79879. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  79880. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  79881. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  79882. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  79883. // truncated at around 1.3% of peak strength.
  79884. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  79885. var sigma = (1 / 3);
  79886. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  79887. var exponent = -((x * x) / (2.0 * sigma * sigma));
  79888. var weight = (1.0 / denominator) * Math.exp(exponent);
  79889. return weight;
  79890. };
  79891. /**
  79892. * Generates a string that can be used as a floating point number in GLSL.
  79893. * @param x Value to print.
  79894. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  79895. * @return GLSL float string.
  79896. */
  79897. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  79898. if (decimalFigures === void 0) { decimalFigures = 8; }
  79899. return x.toFixed(decimalFigures).replace(/0+$/, '');
  79900. };
  79901. return BlurPostProcess;
  79902. }(BABYLON.PostProcess));
  79903. BABYLON.BlurPostProcess = BlurPostProcess;
  79904. })(BABYLON || (BABYLON = {}));
  79905. //# sourceMappingURL=babylon.blurPostProcess.js.map
  79906. var BABYLON;
  79907. (function (BABYLON) {
  79908. /**
  79909. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  79910. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  79911. * based on samples that have a large difference in distance than the center pixel.
  79912. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  79913. */
  79914. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  79915. __extends(DepthOfFieldBlurPostProcess, _super);
  79916. /**
  79917. * Creates a new instance CircleOfConfusionPostProcess
  79918. * @param name The name of the effect.
  79919. * @param scene The scene the effect belongs to.
  79920. * @param direction The direction the blur should be applied.
  79921. * @param kernel The size of the kernel used to blur.
  79922. * @param options The required width/height ratio to downsize to before computing the render pass.
  79923. * @param camera The camera to apply the render pass to.
  79924. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  79925. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  79926. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79927. * @param engine The engine which the post process will be applied. (default: current engine)
  79928. * @param reusable If the post process can be reused on the same frame. (default: false)
  79929. * @param textureType Type of textures used when performing the post process. (default: 0)
  79930. * @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)
  79931. */
  79932. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  79933. if (imageToBlur === void 0) { imageToBlur = null; }
  79934. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79935. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79936. if (blockCompilation === void 0) { blockCompilation = false; }
  79937. 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;
  79938. _this.direction = direction;
  79939. _this.onApplyObservable.add(function (effect) {
  79940. if (imageToBlur != null) {
  79941. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  79942. }
  79943. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  79944. if (scene.activeCamera) {
  79945. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  79946. }
  79947. });
  79948. return _this;
  79949. }
  79950. return DepthOfFieldBlurPostProcess;
  79951. }(BABYLON.BlurPostProcess));
  79952. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  79953. })(BABYLON || (BABYLON = {}));
  79954. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  79955. var BABYLON;
  79956. (function (BABYLON) {
  79957. /**
  79958. * Options to be set when merging outputs from the default pipeline.
  79959. */
  79960. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  79961. function DepthOfFieldMergePostProcessOptions() {
  79962. }
  79963. return DepthOfFieldMergePostProcessOptions;
  79964. }());
  79965. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  79966. /**
  79967. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  79968. */
  79969. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  79970. __extends(DepthOfFieldMergePostProcess, _super);
  79971. /**
  79972. * Creates a new instance of DepthOfFieldMergePostProcess
  79973. * @param name The name of the effect.
  79974. * @param originalFromInput Post process which's input will be used for the merge.
  79975. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  79976. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  79977. * @param options The required width/height ratio to downsize to before computing the render pass.
  79978. * @param camera The camera to apply the render pass to.
  79979. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79980. * @param engine The engine which the post process will be applied. (default: current engine)
  79981. * @param reusable If the post process can be reused on the same frame. (default: false)
  79982. * @param textureType Type of textures used when performing the post process. (default: 0)
  79983. * @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)
  79984. */
  79985. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79986. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79987. if (blockCompilation === void 0) { blockCompilation = false; }
  79988. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  79989. _this.blurSteps = blurSteps;
  79990. _this.onApplyObservable.add(function (effect) {
  79991. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  79992. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  79993. blurSteps.forEach(function (step, index) {
  79994. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  79995. });
  79996. });
  79997. if (!blockCompilation) {
  79998. _this.updateEffect();
  79999. }
  80000. return _this;
  80001. }
  80002. /**
  80003. * Updates the effect with the current post process compile time values and recompiles the shader.
  80004. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80005. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80006. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80007. * @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
  80008. * @param onCompiled Called when the shader has been compiled.
  80009. * @param onError Called if there is an error when compiling a shader.
  80010. */
  80011. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80012. if (defines === void 0) { defines = null; }
  80013. if (uniforms === void 0) { uniforms = null; }
  80014. if (samplers === void 0) { samplers = null; }
  80015. if (!defines) {
  80016. defines = "";
  80017. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  80018. }
  80019. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  80020. };
  80021. return DepthOfFieldMergePostProcess;
  80022. }(BABYLON.PostProcess));
  80023. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  80024. })(BABYLON || (BABYLON = {}));
  80025. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  80026. var BABYLON;
  80027. (function (BABYLON) {
  80028. /**
  80029. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  80030. */
  80031. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  80032. __extends(CircleOfConfusionPostProcess, _super);
  80033. /**
  80034. * Creates a new instance CircleOfConfusionPostProcess
  80035. * @param name The name of the effect.
  80036. * @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.
  80037. * @param options The required width/height ratio to downsize to before computing the render pass.
  80038. * @param camera The camera to apply the render pass to.
  80039. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80040. * @param engine The engine which the post process will be applied. (default: current engine)
  80041. * @param reusable If the post process can be reused on the same frame. (default: false)
  80042. * @param textureType Type of textures used when performing the post process. (default: 0)
  80043. * @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)
  80044. */
  80045. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80046. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80047. if (blockCompilation === void 0) { blockCompilation = false; }
  80048. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80049. /**
  80050. * 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.
  80051. */
  80052. _this.lensSize = 50;
  80053. /**
  80054. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  80055. */
  80056. _this.fStop = 1.4;
  80057. /**
  80058. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  80059. */
  80060. _this.focusDistance = 2000;
  80061. /**
  80062. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  80063. */
  80064. _this.focalLength = 50;
  80065. _this._depthTexture = null;
  80066. _this._depthTexture = depthTexture;
  80067. _this.onApplyObservable.add(function (effect) {
  80068. if (!_this._depthTexture) {
  80069. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  80070. return;
  80071. }
  80072. effect.setTexture("depthSampler", _this._depthTexture);
  80073. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  80074. var aperture = _this.lensSize / _this.fStop;
  80075. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  80076. effect.setFloat('focusDistance', _this.focusDistance);
  80077. effect.setFloat('cocPrecalculation', cocPrecalculation);
  80078. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  80079. });
  80080. return _this;
  80081. }
  80082. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  80083. /**
  80084. * 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.
  80085. */
  80086. set: function (value) {
  80087. this._depthTexture = value;
  80088. },
  80089. enumerable: true,
  80090. configurable: true
  80091. });
  80092. return CircleOfConfusionPostProcess;
  80093. }(BABYLON.PostProcess));
  80094. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  80095. })(BABYLON || (BABYLON = {}));
  80096. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  80097. var BABYLON;
  80098. (function (BABYLON) {
  80099. /**
  80100. * Specifies the level of max blur that should be applied when using the depth of field effect
  80101. */
  80102. var DepthOfFieldEffectBlurLevel;
  80103. (function (DepthOfFieldEffectBlurLevel) {
  80104. /**
  80105. * Subtle blur
  80106. */
  80107. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  80108. /**
  80109. * Medium blur
  80110. */
  80111. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  80112. /**
  80113. * Large blur
  80114. */
  80115. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  80116. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  80117. ;
  80118. /**
  80119. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  80120. */
  80121. var DepthOfFieldEffect = /** @class */ (function (_super) {
  80122. __extends(DepthOfFieldEffect, _super);
  80123. /**
  80124. * Creates a new instance DepthOfFieldEffect
  80125. * @param scene The scene the effect belongs to.
  80126. * @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.
  80127. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  80128. * @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)
  80129. */
  80130. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  80131. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  80132. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  80133. if (blockCompilation === void 0) { blockCompilation = false; }
  80134. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  80135. return _this._effects;
  80136. }, true) || this;
  80137. /**
  80138. * @hidden Internal post processes in depth of field effect
  80139. */
  80140. _this._effects = [];
  80141. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  80142. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80143. // 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)
  80144. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  80145. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  80146. _this._depthOfFieldBlurY = [];
  80147. _this._depthOfFieldBlurX = [];
  80148. var blurCount = 1;
  80149. var kernelSize = 15;
  80150. switch (blurLevel) {
  80151. case DepthOfFieldEffectBlurLevel.High: {
  80152. blurCount = 3;
  80153. kernelSize = 51;
  80154. break;
  80155. }
  80156. case DepthOfFieldEffectBlurLevel.Medium: {
  80157. blurCount = 2;
  80158. kernelSize = 31;
  80159. break;
  80160. }
  80161. default: {
  80162. kernelSize = 15;
  80163. blurCount = 1;
  80164. break;
  80165. }
  80166. }
  80167. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  80168. var ratio = 1.0;
  80169. for (var i = 0; i < blurCount; i++) {
  80170. 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);
  80171. blurY.autoClear = false;
  80172. ratio = 0.75 / Math.pow(2, i);
  80173. 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);
  80174. blurX.autoClear = false;
  80175. _this._depthOfFieldBlurY.push(blurY);
  80176. _this._depthOfFieldBlurX.push(blurX);
  80177. }
  80178. // Set all post processes on the effect.
  80179. _this._effects = [_this._circleOfConfusion];
  80180. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  80181. _this._effects.push(_this._depthOfFieldBlurY[i]);
  80182. _this._effects.push(_this._depthOfFieldBlurX[i]);
  80183. }
  80184. // Merge blurred images with original image based on circleOfConfusion
  80185. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80186. _this._dofMerge.autoClear = false;
  80187. _this._effects.push(_this._dofMerge);
  80188. return _this;
  80189. }
  80190. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  80191. get: function () {
  80192. return this._circleOfConfusion.focalLength;
  80193. },
  80194. /**
  80195. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  80196. */
  80197. set: function (value) {
  80198. this._circleOfConfusion.focalLength = value;
  80199. },
  80200. enumerable: true,
  80201. configurable: true
  80202. });
  80203. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  80204. get: function () {
  80205. return this._circleOfConfusion.fStop;
  80206. },
  80207. /**
  80208. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  80209. */
  80210. set: function (value) {
  80211. this._circleOfConfusion.fStop = value;
  80212. },
  80213. enumerable: true,
  80214. configurable: true
  80215. });
  80216. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  80217. get: function () {
  80218. return this._circleOfConfusion.focusDistance;
  80219. },
  80220. /**
  80221. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  80222. */
  80223. set: function (value) {
  80224. this._circleOfConfusion.focusDistance = value;
  80225. },
  80226. enumerable: true,
  80227. configurable: true
  80228. });
  80229. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  80230. get: function () {
  80231. return this._circleOfConfusion.lensSize;
  80232. },
  80233. /**
  80234. * 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.
  80235. */
  80236. set: function (value) {
  80237. this._circleOfConfusion.lensSize = value;
  80238. },
  80239. enumerable: true,
  80240. configurable: true
  80241. });
  80242. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  80243. /**
  80244. * 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.
  80245. */
  80246. set: function (value) {
  80247. this._circleOfConfusion.depthTexture = value;
  80248. },
  80249. enumerable: true,
  80250. configurable: true
  80251. });
  80252. /**
  80253. * Disposes each of the internal effects for a given camera.
  80254. * @param camera The camera to dispose the effect on.
  80255. */
  80256. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  80257. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80258. this._effects[effectIndex].dispose(camera);
  80259. }
  80260. };
  80261. /**
  80262. * @hidden Internal
  80263. */
  80264. DepthOfFieldEffect.prototype._updateEffects = function () {
  80265. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80266. this._effects[effectIndex].updateEffect();
  80267. }
  80268. };
  80269. /**
  80270. * Internal
  80271. * @returns if all the contained post processes are ready.
  80272. * @hidden
  80273. */
  80274. DepthOfFieldEffect.prototype._isReady = function () {
  80275. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80276. if (!this._effects[effectIndex].isReady()) {
  80277. return false;
  80278. }
  80279. }
  80280. return true;
  80281. };
  80282. return DepthOfFieldEffect;
  80283. }(BABYLON.PostProcessRenderEffect));
  80284. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  80285. })(BABYLON || (BABYLON = {}));
  80286. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  80287. var BABYLON;
  80288. (function (BABYLON) {
  80289. /**
  80290. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  80291. */
  80292. var BloomMergePostProcess = /** @class */ (function (_super) {
  80293. __extends(BloomMergePostProcess, _super);
  80294. /**
  80295. * Creates a new instance of @see BloomMergePostProcess
  80296. * @param name The name of the effect.
  80297. * @param originalFromInput Post process which's input will be used for the merge.
  80298. * @param blurred Blurred highlights post process which's output will be used.
  80299. * @param weight Weight of the bloom to be added to the original input.
  80300. * @param options The required width/height ratio to downsize to before computing the render pass.
  80301. * @param camera The camera to apply the render pass to.
  80302. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80303. * @param engine The engine which the post process will be applied. (default: current engine)
  80304. * @param reusable If the post process can be reused on the same frame. (default: false)
  80305. * @param textureType Type of textures used when performing the post process. (default: 0)
  80306. * @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)
  80307. */
  80308. function BloomMergePostProcess(name, originalFromInput, blurred,
  80309. /** Weight of the bloom to be added to the original input. */
  80310. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80311. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80312. if (blockCompilation === void 0) { blockCompilation = false; }
  80313. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  80314. _this.weight = weight;
  80315. _this.onApplyObservable.add(function (effect) {
  80316. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  80317. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  80318. effect.setFloat("bloomWeight", _this.weight);
  80319. });
  80320. if (!blockCompilation) {
  80321. _this.updateEffect();
  80322. }
  80323. return _this;
  80324. }
  80325. return BloomMergePostProcess;
  80326. }(BABYLON.PostProcess));
  80327. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  80328. })(BABYLON || (BABYLON = {}));
  80329. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  80330. var BABYLON;
  80331. (function (BABYLON) {
  80332. /**
  80333. * 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.
  80334. */
  80335. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  80336. __extends(ExtractHighlightsPostProcess, _super);
  80337. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80338. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80339. if (blockCompilation === void 0) { blockCompilation = false; }
  80340. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80341. /**
  80342. * The luminance threshold, pixels below this value will be set to black.
  80343. */
  80344. _this.threshold = 0.9;
  80345. /** @hidden */
  80346. _this._exposure = 1;
  80347. /**
  80348. * Post process which has the input texture to be used when performing highlight extraction
  80349. * @hidden
  80350. */
  80351. _this._inputPostProcess = null;
  80352. _this.onApplyObservable.add(function (effect) {
  80353. if (_this._inputPostProcess) {
  80354. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  80355. }
  80356. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  80357. effect.setFloat('exposure', _this._exposure);
  80358. });
  80359. return _this;
  80360. }
  80361. return ExtractHighlightsPostProcess;
  80362. }(BABYLON.PostProcess));
  80363. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  80364. })(BABYLON || (BABYLON = {}));
  80365. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  80366. var BABYLON;
  80367. (function (BABYLON) {
  80368. /**
  80369. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  80370. */
  80371. var BloomEffect = /** @class */ (function (_super) {
  80372. __extends(BloomEffect, _super);
  80373. /**
  80374. * Creates a new instance of @see BloomEffect
  80375. * @param scene The scene the effect belongs to.
  80376. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  80377. * @param bloomKernel The size of the kernel to be used when applying the blur.
  80378. * @param bloomWeight The the strength of bloom.
  80379. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  80380. * @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)
  80381. */
  80382. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  80383. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  80384. if (blockCompilation === void 0) { blockCompilation = false; }
  80385. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  80386. return _this._effects;
  80387. }, true) || this;
  80388. _this.bloomScale = bloomScale;
  80389. /**
  80390. * @hidden Internal
  80391. */
  80392. _this._effects = [];
  80393. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80394. _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);
  80395. _this._blurX.alwaysForcePOT = true;
  80396. _this._blurX.autoClear = false;
  80397. _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);
  80398. _this._blurY.alwaysForcePOT = true;
  80399. _this._blurY.autoClear = false;
  80400. _this.kernel = bloomKernel;
  80401. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  80402. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80403. _this._merge.autoClear = false;
  80404. _this._effects.push(_this._merge);
  80405. return _this;
  80406. }
  80407. Object.defineProperty(BloomEffect.prototype, "threshold", {
  80408. /**
  80409. * The luminance threshold to find bright areas of the image to bloom.
  80410. */
  80411. get: function () {
  80412. return this._downscale.threshold;
  80413. },
  80414. set: function (value) {
  80415. this._downscale.threshold = value;
  80416. },
  80417. enumerable: true,
  80418. configurable: true
  80419. });
  80420. Object.defineProperty(BloomEffect.prototype, "weight", {
  80421. /**
  80422. * The strength of the bloom.
  80423. */
  80424. get: function () {
  80425. return this._merge.weight;
  80426. },
  80427. set: function (value) {
  80428. this._merge.weight = value;
  80429. },
  80430. enumerable: true,
  80431. configurable: true
  80432. });
  80433. Object.defineProperty(BloomEffect.prototype, "kernel", {
  80434. /**
  80435. * Specifies the size of the bloom blur kernel, relative to the final output size
  80436. */
  80437. get: function () {
  80438. return this._blurX.kernel / this.bloomScale;
  80439. },
  80440. set: function (value) {
  80441. this._blurX.kernel = value * this.bloomScale;
  80442. this._blurY.kernel = value * this.bloomScale;
  80443. },
  80444. enumerable: true,
  80445. configurable: true
  80446. });
  80447. /**
  80448. * Disposes each of the internal effects for a given camera.
  80449. * @param camera The camera to dispose the effect on.
  80450. */
  80451. BloomEffect.prototype.disposeEffects = function (camera) {
  80452. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80453. this._effects[effectIndex].dispose(camera);
  80454. }
  80455. };
  80456. /**
  80457. * @hidden Internal
  80458. */
  80459. BloomEffect.prototype._updateEffects = function () {
  80460. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80461. this._effects[effectIndex].updateEffect();
  80462. }
  80463. };
  80464. /**
  80465. * Internal
  80466. * @returns if all the contained post processes are ready.
  80467. * @hidden
  80468. */
  80469. BloomEffect.prototype._isReady = function () {
  80470. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80471. if (!this._effects[effectIndex].isReady()) {
  80472. return false;
  80473. }
  80474. }
  80475. return true;
  80476. };
  80477. return BloomEffect;
  80478. }(BABYLON.PostProcessRenderEffect));
  80479. BABYLON.BloomEffect = BloomEffect;
  80480. })(BABYLON || (BABYLON = {}));
  80481. //# sourceMappingURL=babylon.bloomEffect.js.map
  80482. var BABYLON;
  80483. (function (BABYLON) {
  80484. /**
  80485. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  80486. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  80487. */
  80488. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  80489. __extends(DefaultRenderingPipeline, _super);
  80490. /**
  80491. * @constructor
  80492. * @param {string} name - The rendering pipeline name (default: "")
  80493. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  80494. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  80495. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  80496. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  80497. */
  80498. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  80499. if (name === void 0) { name = ""; }
  80500. if (hdr === void 0) { hdr = true; }
  80501. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  80502. if (automaticBuild === void 0) { automaticBuild = true; }
  80503. var _this = _super.call(this, scene.getEngine(), name) || this;
  80504. _this._camerasToBeAttached = [];
  80505. /**
  80506. * ID of the sharpen post process,
  80507. */
  80508. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  80509. /**
  80510. * ID of the image processing post process;
  80511. */
  80512. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  80513. /**
  80514. * ID of the Fast Approximate Anti-Aliasing post process;
  80515. */
  80516. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  80517. /**
  80518. * ID of the chromatic aberration post process,
  80519. */
  80520. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  80521. /**
  80522. * ID of the grain post process
  80523. */
  80524. _this.GrainPostProcessId = "GrainPostProcessEffect";
  80525. /**
  80526. * Glow post process which adds a glow to emmisive areas of the image
  80527. */
  80528. _this._glowLayer = null;
  80529. /**
  80530. * Animations which can be used to tweak settings over a period of time
  80531. */
  80532. _this.animations = [];
  80533. _this._imageProcessingConfigurationObserver = null;
  80534. // Values
  80535. _this._sharpenEnabled = false;
  80536. _this._bloomEnabled = false;
  80537. _this._depthOfFieldEnabled = false;
  80538. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  80539. _this._fxaaEnabled = false;
  80540. _this._imageProcessingEnabled = true;
  80541. _this._bloomScale = 0.5;
  80542. _this._chromaticAberrationEnabled = false;
  80543. _this._grainEnabled = false;
  80544. _this._buildAllowed = true;
  80545. _this._resizeObserver = null;
  80546. _this._hardwareScaleLevel = 1.0;
  80547. _this._bloomKernel = 64;
  80548. /**
  80549. * Specifies the weight of the bloom in the final rendering
  80550. */
  80551. _this._bloomWeight = 0.15;
  80552. /**
  80553. * Specifies the luma threshold for the area that will be blurred by the bloom
  80554. */
  80555. _this._bloomThreshold = 0.9;
  80556. _this._samples = 1;
  80557. _this._hasCleared = false;
  80558. _this._prevPostProcess = null;
  80559. _this._prevPrevPostProcess = null;
  80560. _this._cameras = cameras || scene.cameras;
  80561. _this._cameras = _this._cameras.slice();
  80562. _this._camerasToBeAttached = _this._cameras.slice();
  80563. _this._buildAllowed = automaticBuild;
  80564. // Initialize
  80565. _this._scene = scene;
  80566. var caps = _this._scene.getEngine().getCaps();
  80567. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  80568. // Misc
  80569. if (_this._hdr) {
  80570. if (caps.textureHalfFloatRender) {
  80571. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80572. }
  80573. else if (caps.textureFloatRender) {
  80574. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80575. }
  80576. }
  80577. else {
  80578. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80579. }
  80580. // Attach
  80581. scene.postProcessRenderPipelineManager.addPipeline(_this);
  80582. var engine = _this._scene.getEngine();
  80583. // Create post processes before hand so they can be modified before enabled.
  80584. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  80585. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  80586. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  80587. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  80588. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  80589. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  80590. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  80591. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  80592. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  80593. _this._resizeObserver = engine.onResizeObservable.add(function () {
  80594. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  80595. _this.bloomKernel = _this.bloomKernel;
  80596. });
  80597. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  80598. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  80599. });
  80600. _this._buildPipeline();
  80601. return _this;
  80602. }
  80603. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  80604. get: function () {
  80605. return this._sharpenEnabled;
  80606. },
  80607. /**
  80608. * Enable or disable the sharpen process from the pipeline
  80609. */
  80610. set: function (enabled) {
  80611. if (this._sharpenEnabled === enabled) {
  80612. return;
  80613. }
  80614. this._sharpenEnabled = enabled;
  80615. this._buildPipeline();
  80616. },
  80617. enumerable: true,
  80618. configurable: true
  80619. });
  80620. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  80621. /**
  80622. * Specifies the size of the bloom blur kernel, relative to the final output size
  80623. */
  80624. get: function () {
  80625. return this._bloomKernel;
  80626. },
  80627. set: function (value) {
  80628. this._bloomKernel = value;
  80629. this.bloom.kernel = value / this._hardwareScaleLevel;
  80630. },
  80631. enumerable: true,
  80632. configurable: true
  80633. });
  80634. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  80635. get: function () {
  80636. return this._bloomWeight;
  80637. },
  80638. /**
  80639. * The strength of the bloom.
  80640. */
  80641. set: function (value) {
  80642. if (this._bloomWeight === value) {
  80643. return;
  80644. }
  80645. this.bloom.weight = value;
  80646. this._bloomWeight = value;
  80647. },
  80648. enumerable: true,
  80649. configurable: true
  80650. });
  80651. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  80652. get: function () {
  80653. return this._bloomThreshold;
  80654. },
  80655. /**
  80656. * The strength of the bloom.
  80657. */
  80658. set: function (value) {
  80659. if (this._bloomThreshold === value) {
  80660. return;
  80661. }
  80662. this.bloom.threshold = value;
  80663. this._bloomThreshold = value;
  80664. },
  80665. enumerable: true,
  80666. configurable: true
  80667. });
  80668. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  80669. get: function () {
  80670. return this._bloomScale;
  80671. },
  80672. /**
  80673. * The scale of the bloom, lower value will provide better performance.
  80674. */
  80675. set: function (value) {
  80676. if (this._bloomScale === value) {
  80677. return;
  80678. }
  80679. this._bloomScale = value;
  80680. // recreate bloom and dispose old as this setting is not dynamic
  80681. this._rebuildBloom();
  80682. this._buildPipeline();
  80683. },
  80684. enumerable: true,
  80685. configurable: true
  80686. });
  80687. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  80688. get: function () {
  80689. return this._bloomEnabled;
  80690. },
  80691. /**
  80692. * Enable or disable the bloom from the pipeline
  80693. */
  80694. set: function (enabled) {
  80695. if (this._bloomEnabled === enabled) {
  80696. return;
  80697. }
  80698. this._bloomEnabled = enabled;
  80699. this._buildPipeline();
  80700. },
  80701. enumerable: true,
  80702. configurable: true
  80703. });
  80704. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  80705. // recreate bloom and dispose old as this setting is not dynamic
  80706. var oldBloom = this.bloom;
  80707. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  80708. this.bloom.threshold = oldBloom.threshold;
  80709. for (var i = 0; i < this._cameras.length; i++) {
  80710. oldBloom.disposeEffects(this._cameras[i]);
  80711. }
  80712. };
  80713. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  80714. /**
  80715. * If the depth of field is enabled.
  80716. */
  80717. get: function () {
  80718. return this._depthOfFieldEnabled;
  80719. },
  80720. set: function (enabled) {
  80721. if (this._depthOfFieldEnabled === enabled) {
  80722. return;
  80723. }
  80724. this._depthOfFieldEnabled = enabled;
  80725. this._buildPipeline();
  80726. },
  80727. enumerable: true,
  80728. configurable: true
  80729. });
  80730. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  80731. /**
  80732. * Blur level of the depth of field effect. (Higher blur will effect performance)
  80733. */
  80734. get: function () {
  80735. return this._depthOfFieldBlurLevel;
  80736. },
  80737. set: function (value) {
  80738. if (this._depthOfFieldBlurLevel === value) {
  80739. return;
  80740. }
  80741. this._depthOfFieldBlurLevel = value;
  80742. // recreate dof and dispose old as this setting is not dynamic
  80743. var oldDof = this.depthOfField;
  80744. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  80745. this.depthOfField.focalLength = oldDof.focalLength;
  80746. this.depthOfField.focusDistance = oldDof.focusDistance;
  80747. this.depthOfField.fStop = oldDof.fStop;
  80748. this.depthOfField.lensSize = oldDof.lensSize;
  80749. for (var i = 0; i < this._cameras.length; i++) {
  80750. oldDof.disposeEffects(this._cameras[i]);
  80751. }
  80752. this._buildPipeline();
  80753. },
  80754. enumerable: true,
  80755. configurable: true
  80756. });
  80757. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  80758. get: function () {
  80759. return this._fxaaEnabled;
  80760. },
  80761. /**
  80762. * If the anti aliasing is enabled.
  80763. */
  80764. set: function (enabled) {
  80765. if (this._fxaaEnabled === enabled) {
  80766. return;
  80767. }
  80768. this._fxaaEnabled = enabled;
  80769. this._buildPipeline();
  80770. },
  80771. enumerable: true,
  80772. configurable: true
  80773. });
  80774. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  80775. get: function () {
  80776. return this._samples;
  80777. },
  80778. /**
  80779. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  80780. */
  80781. set: function (sampleCount) {
  80782. if (this._samples === sampleCount) {
  80783. return;
  80784. }
  80785. this._samples = sampleCount;
  80786. this._buildPipeline();
  80787. },
  80788. enumerable: true,
  80789. configurable: true
  80790. });
  80791. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  80792. get: function () {
  80793. return this._imageProcessingEnabled;
  80794. },
  80795. /**
  80796. * If image processing is enabled.
  80797. */
  80798. set: function (enabled) {
  80799. if (this._imageProcessingEnabled === enabled) {
  80800. return;
  80801. }
  80802. this._imageProcessingEnabled = enabled;
  80803. this._buildPipeline();
  80804. },
  80805. enumerable: true,
  80806. configurable: true
  80807. });
  80808. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  80809. get: function () {
  80810. return this._glowLayer == null;
  80811. },
  80812. /**
  80813. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  80814. */
  80815. set: function (enabled) {
  80816. if (enabled && !this._glowLayer) {
  80817. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  80818. }
  80819. else if (!enabled && this._glowLayer) {
  80820. this._glowLayer.dispose();
  80821. this._glowLayer = null;
  80822. }
  80823. },
  80824. enumerable: true,
  80825. configurable: true
  80826. });
  80827. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  80828. get: function () {
  80829. return this._chromaticAberrationEnabled;
  80830. },
  80831. /**
  80832. * Enable or disable the chromaticAberration process from the pipeline
  80833. */
  80834. set: function (enabled) {
  80835. if (this._chromaticAberrationEnabled === enabled) {
  80836. return;
  80837. }
  80838. this._chromaticAberrationEnabled = enabled;
  80839. this._buildPipeline();
  80840. },
  80841. enumerable: true,
  80842. configurable: true
  80843. });
  80844. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  80845. get: function () {
  80846. return this._grainEnabled;
  80847. },
  80848. /**
  80849. * Enable or disable the grain process from the pipeline
  80850. */
  80851. set: function (enabled) {
  80852. if (this._grainEnabled === enabled) {
  80853. return;
  80854. }
  80855. this._grainEnabled = enabled;
  80856. this._buildPipeline();
  80857. },
  80858. enumerable: true,
  80859. configurable: true
  80860. });
  80861. /**
  80862. * Force the compilation of the entire pipeline.
  80863. */
  80864. DefaultRenderingPipeline.prototype.prepare = function () {
  80865. var previousState = this._buildAllowed;
  80866. this._buildAllowed = true;
  80867. this._buildPipeline();
  80868. this._buildAllowed = previousState;
  80869. };
  80870. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  80871. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  80872. if (this._hasCleared) {
  80873. postProcess.autoClear = false;
  80874. }
  80875. else {
  80876. postProcess.autoClear = true;
  80877. this._scene.autoClear = false;
  80878. this._hasCleared = true;
  80879. }
  80880. if (!skipTextureSharing) {
  80881. if (this._prevPrevPostProcess) {
  80882. postProcess.shareOutputWith(this._prevPrevPostProcess);
  80883. }
  80884. else {
  80885. postProcess.useOwnOutput();
  80886. }
  80887. if (this._prevPostProcess) {
  80888. this._prevPrevPostProcess = this._prevPostProcess;
  80889. }
  80890. this._prevPostProcess = postProcess;
  80891. }
  80892. };
  80893. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  80894. var _this = this;
  80895. if (!this._buildAllowed) {
  80896. return;
  80897. }
  80898. this._scene.autoClear = true;
  80899. var engine = this._scene.getEngine();
  80900. this._disposePostProcesses();
  80901. if (this._cameras !== null) {
  80902. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80903. // get back cameras to be used to reattach pipeline
  80904. this._cameras = this._camerasToBeAttached.slice();
  80905. }
  80906. this._reset();
  80907. this._prevPostProcess = null;
  80908. this._prevPrevPostProcess = null;
  80909. this._hasCleared = false;
  80910. if (this.depthOfFieldEnabled) {
  80911. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  80912. this.depthOfField.depthTexture = depthTexture;
  80913. if (!this.depthOfField._isReady()) {
  80914. this.depthOfField._updateEffects();
  80915. }
  80916. this.addEffect(this.depthOfField);
  80917. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  80918. }
  80919. if (this.bloomEnabled) {
  80920. if (!this.bloom._isReady()) {
  80921. this.bloom._updateEffects();
  80922. }
  80923. this.addEffect(this.bloom);
  80924. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  80925. }
  80926. if (this._imageProcessingEnabled) {
  80927. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  80928. if (this._hdr) {
  80929. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  80930. this._setAutoClearAndTextureSharing(this.imageProcessing);
  80931. }
  80932. else {
  80933. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  80934. }
  80935. }
  80936. if (this.sharpenEnabled) {
  80937. if (!this.sharpen.isReady()) {
  80938. this.sharpen.updateEffect();
  80939. }
  80940. this.addEffect(this._sharpenEffect);
  80941. this._setAutoClearAndTextureSharing(this.sharpen);
  80942. }
  80943. if (this.grainEnabled) {
  80944. if (!this.grain.isReady()) {
  80945. this.grain.updateEffect();
  80946. }
  80947. this.addEffect(this._grainEffect);
  80948. this._setAutoClearAndTextureSharing(this.grain);
  80949. }
  80950. if (this.chromaticAberrationEnabled) {
  80951. if (!this.chromaticAberration.isReady()) {
  80952. this.chromaticAberration.updateEffect();
  80953. }
  80954. this.addEffect(this._chromaticAberrationEffect);
  80955. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  80956. }
  80957. if (this.fxaaEnabled) {
  80958. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  80959. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  80960. this._setAutoClearAndTextureSharing(this.fxaa, true);
  80961. }
  80962. if (this._cameras !== null) {
  80963. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  80964. }
  80965. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  80966. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  80967. }
  80968. };
  80969. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  80970. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  80971. for (var i = 0; i < this._cameras.length; i++) {
  80972. var camera = this._cameras[i];
  80973. if (this.imageProcessing) {
  80974. this.imageProcessing.dispose(camera);
  80975. }
  80976. if (this.fxaa) {
  80977. this.fxaa.dispose(camera);
  80978. }
  80979. // These are created in the constructor and should not be disposed on every pipeline change
  80980. if (disposeNonRecreated) {
  80981. if (this.sharpen) {
  80982. this.sharpen.dispose(camera);
  80983. }
  80984. if (this.depthOfField) {
  80985. this.depthOfField.disposeEffects(camera);
  80986. }
  80987. if (this.bloom) {
  80988. this.bloom.disposeEffects(camera);
  80989. }
  80990. if (this.chromaticAberration) {
  80991. this.chromaticAberration.dispose(camera);
  80992. }
  80993. if (this.grain) {
  80994. this.grain.dispose(camera);
  80995. }
  80996. if (this._glowLayer) {
  80997. this._glowLayer.dispose();
  80998. }
  80999. }
  81000. }
  81001. this.imageProcessing = null;
  81002. this.fxaa = null;
  81003. if (disposeNonRecreated) {
  81004. this.sharpen = null;
  81005. this._sharpenEffect = null;
  81006. this.depthOfField = null;
  81007. this.bloom = null;
  81008. this.chromaticAberration = null;
  81009. this._chromaticAberrationEffect = null;
  81010. this.grain = null;
  81011. this._grainEffect = null;
  81012. this._glowLayer = null;
  81013. }
  81014. };
  81015. /**
  81016. * Adds a camera to the pipeline
  81017. * @param camera the camera to be added
  81018. */
  81019. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  81020. this._camerasToBeAttached.push(camera);
  81021. this._buildPipeline();
  81022. };
  81023. /**
  81024. * Removes a camera from the pipeline
  81025. * @param camera the camera to remove
  81026. */
  81027. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  81028. var index = this._camerasToBeAttached.indexOf(camera);
  81029. this._camerasToBeAttached.splice(index, 1);
  81030. this._buildPipeline();
  81031. };
  81032. /**
  81033. * Dispose of the pipeline and stop all post processes
  81034. */
  81035. DefaultRenderingPipeline.prototype.dispose = function () {
  81036. this._disposePostProcesses(true);
  81037. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81038. this._scene.autoClear = true;
  81039. if (this._resizeObserver) {
  81040. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  81041. this._resizeObserver = null;
  81042. }
  81043. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  81044. _super.prototype.dispose.call(this);
  81045. };
  81046. /**
  81047. * Serialize the rendering pipeline (Used when exporting)
  81048. * @returns the serialized object
  81049. */
  81050. DefaultRenderingPipeline.prototype.serialize = function () {
  81051. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81052. serializationObject.customType = "DefaultRenderingPipeline";
  81053. return serializationObject;
  81054. };
  81055. /**
  81056. * Parse the serialized pipeline
  81057. * @param source Source pipeline.
  81058. * @param scene The scene to load the pipeline to.
  81059. * @param rootUrl The URL of the serialized pipeline.
  81060. * @returns An instantiated pipeline from the serialized object.
  81061. */
  81062. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  81063. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  81064. };
  81065. __decorate([
  81066. BABYLON.serialize()
  81067. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  81068. __decorate([
  81069. BABYLON.serialize()
  81070. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  81071. __decorate([
  81072. BABYLON.serialize()
  81073. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  81074. __decorate([
  81075. BABYLON.serialize()
  81076. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  81077. __decorate([
  81078. BABYLON.serialize()
  81079. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  81080. __decorate([
  81081. BABYLON.serialize()
  81082. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  81083. __decorate([
  81084. BABYLON.serialize()
  81085. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  81086. __decorate([
  81087. BABYLON.serialize()
  81088. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  81089. __decorate([
  81090. BABYLON.serialize()
  81091. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  81092. __decorate([
  81093. BABYLON.serialize()
  81094. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  81095. __decorate([
  81096. BABYLON.serialize()
  81097. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  81098. __decorate([
  81099. BABYLON.serialize()
  81100. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  81101. __decorate([
  81102. BABYLON.serialize()
  81103. ], DefaultRenderingPipeline.prototype, "samples", null);
  81104. __decorate([
  81105. BABYLON.serialize()
  81106. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  81107. __decorate([
  81108. BABYLON.serialize()
  81109. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  81110. __decorate([
  81111. BABYLON.serialize()
  81112. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  81113. __decorate([
  81114. BABYLON.serialize()
  81115. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  81116. return DefaultRenderingPipeline;
  81117. }(BABYLON.PostProcessRenderPipeline));
  81118. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  81119. })(BABYLON || (BABYLON = {}));
  81120. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  81121. var BABYLON;
  81122. (function (BABYLON) {
  81123. /**
  81124. * @hidden
  81125. */
  81126. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  81127. __extends(ImageProcessingConfigurationDefines, _super);
  81128. function ImageProcessingConfigurationDefines() {
  81129. var _this = _super.call(this) || this;
  81130. _this.IMAGEPROCESSING = false;
  81131. _this.VIGNETTE = false;
  81132. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  81133. _this.VIGNETTEBLENDMODEOPAQUE = false;
  81134. _this.TONEMAPPING = false;
  81135. _this.TONEMAPPING_ACES = false;
  81136. _this.CONTRAST = false;
  81137. _this.COLORCURVES = false;
  81138. _this.COLORGRADING = false;
  81139. _this.COLORGRADING3D = false;
  81140. _this.SAMPLER3DGREENDEPTH = false;
  81141. _this.SAMPLER3DBGRMAP = false;
  81142. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  81143. _this.EXPOSURE = false;
  81144. _this.rebuild();
  81145. return _this;
  81146. }
  81147. return ImageProcessingConfigurationDefines;
  81148. }(BABYLON.MaterialDefines));
  81149. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  81150. /**
  81151. * This groups together the common properties used for image processing either in direct forward pass
  81152. * or through post processing effect depending on the use of the image processing pipeline in your scene
  81153. * or not.
  81154. */
  81155. var ImageProcessingConfiguration = /** @class */ (function () {
  81156. function ImageProcessingConfiguration() {
  81157. /**
  81158. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  81159. */
  81160. this.colorCurves = new BABYLON.ColorCurves();
  81161. this._colorCurvesEnabled = false;
  81162. this._colorGradingEnabled = false;
  81163. this._colorGradingWithGreenDepth = true;
  81164. this._colorGradingBGR = true;
  81165. /** @hidden */
  81166. this._exposure = 1.0;
  81167. this._toneMappingEnabled = false;
  81168. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  81169. this._contrast = 1.0;
  81170. /**
  81171. * Vignette stretch size.
  81172. */
  81173. this.vignetteStretch = 0;
  81174. /**
  81175. * Vignette centre X Offset.
  81176. */
  81177. this.vignetteCentreX = 0;
  81178. /**
  81179. * Vignette centre Y Offset.
  81180. */
  81181. this.vignetteCentreY = 0;
  81182. /**
  81183. * Vignette weight or intensity of the vignette effect.
  81184. */
  81185. this.vignetteWeight = 1.5;
  81186. /**
  81187. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  81188. * if vignetteEnabled is set to true.
  81189. */
  81190. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81191. /**
  81192. * Camera field of view used by the Vignette effect.
  81193. */
  81194. this.vignetteCameraFov = 0.5;
  81195. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  81196. this._vignetteEnabled = false;
  81197. this._applyByPostProcess = false;
  81198. this._isEnabled = true;
  81199. /**
  81200. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  81201. */
  81202. this.onUpdateParameters = new BABYLON.Observable();
  81203. }
  81204. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  81205. /**
  81206. * Gets wether the color curves effect is enabled.
  81207. */
  81208. get: function () {
  81209. return this._colorCurvesEnabled;
  81210. },
  81211. /**
  81212. * Sets wether the color curves effect is enabled.
  81213. */
  81214. set: function (value) {
  81215. if (this._colorCurvesEnabled === value) {
  81216. return;
  81217. }
  81218. this._colorCurvesEnabled = value;
  81219. this._updateParameters();
  81220. },
  81221. enumerable: true,
  81222. configurable: true
  81223. });
  81224. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  81225. /**
  81226. * Gets wether the color grading effect is enabled.
  81227. */
  81228. get: function () {
  81229. return this._colorGradingEnabled;
  81230. },
  81231. /**
  81232. * Sets wether the color grading effect is enabled.
  81233. */
  81234. set: function (value) {
  81235. if (this._colorGradingEnabled === value) {
  81236. return;
  81237. }
  81238. this._colorGradingEnabled = value;
  81239. this._updateParameters();
  81240. },
  81241. enumerable: true,
  81242. configurable: true
  81243. });
  81244. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  81245. /**
  81246. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  81247. */
  81248. get: function () {
  81249. return this._colorGradingWithGreenDepth;
  81250. },
  81251. /**
  81252. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  81253. */
  81254. set: function (value) {
  81255. if (this._colorGradingWithGreenDepth === value) {
  81256. return;
  81257. }
  81258. this._colorGradingWithGreenDepth = value;
  81259. this._updateParameters();
  81260. },
  81261. enumerable: true,
  81262. configurable: true
  81263. });
  81264. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  81265. /**
  81266. * Gets wether the color grading texture contains BGR values.
  81267. */
  81268. get: function () {
  81269. return this._colorGradingBGR;
  81270. },
  81271. /**
  81272. * Sets wether the color grading texture contains BGR values.
  81273. */
  81274. set: function (value) {
  81275. if (this._colorGradingBGR === value) {
  81276. return;
  81277. }
  81278. this._colorGradingBGR = value;
  81279. this._updateParameters();
  81280. },
  81281. enumerable: true,
  81282. configurable: true
  81283. });
  81284. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  81285. /**
  81286. * Gets the Exposure used in the effect.
  81287. */
  81288. get: function () {
  81289. return this._exposure;
  81290. },
  81291. /**
  81292. * Sets the Exposure used in the effect.
  81293. */
  81294. set: function (value) {
  81295. if (this._exposure === value) {
  81296. return;
  81297. }
  81298. this._exposure = value;
  81299. this._updateParameters();
  81300. },
  81301. enumerable: true,
  81302. configurable: true
  81303. });
  81304. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  81305. /**
  81306. * Gets wether the tone mapping effect is enabled.
  81307. */
  81308. get: function () {
  81309. return this._toneMappingEnabled;
  81310. },
  81311. /**
  81312. * Sets wether the tone mapping effect is enabled.
  81313. */
  81314. set: function (value) {
  81315. if (this._toneMappingEnabled === value) {
  81316. return;
  81317. }
  81318. this._toneMappingEnabled = value;
  81319. this._updateParameters();
  81320. },
  81321. enumerable: true,
  81322. configurable: true
  81323. });
  81324. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  81325. /**
  81326. * Gets the type of tone mapping effect.
  81327. */
  81328. get: function () {
  81329. return this._toneMappingType;
  81330. },
  81331. /**
  81332. * Sets the type of tone mapping effect used in BabylonJS.
  81333. */
  81334. set: function (value) {
  81335. if (this._toneMappingType === value) {
  81336. return;
  81337. }
  81338. this._toneMappingType = value;
  81339. this._updateParameters();
  81340. },
  81341. enumerable: true,
  81342. configurable: true
  81343. });
  81344. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  81345. /**
  81346. * Gets the contrast used in the effect.
  81347. */
  81348. get: function () {
  81349. return this._contrast;
  81350. },
  81351. /**
  81352. * Sets the contrast used in the effect.
  81353. */
  81354. set: function (value) {
  81355. if (this._contrast === value) {
  81356. return;
  81357. }
  81358. this._contrast = value;
  81359. this._updateParameters();
  81360. },
  81361. enumerable: true,
  81362. configurable: true
  81363. });
  81364. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  81365. /**
  81366. * Gets the vignette blend mode allowing different kind of effect.
  81367. */
  81368. get: function () {
  81369. return this._vignetteBlendMode;
  81370. },
  81371. /**
  81372. * Sets the vignette blend mode allowing different kind of effect.
  81373. */
  81374. set: function (value) {
  81375. if (this._vignetteBlendMode === value) {
  81376. return;
  81377. }
  81378. this._vignetteBlendMode = value;
  81379. this._updateParameters();
  81380. },
  81381. enumerable: true,
  81382. configurable: true
  81383. });
  81384. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  81385. /**
  81386. * Gets wether the vignette effect is enabled.
  81387. */
  81388. get: function () {
  81389. return this._vignetteEnabled;
  81390. },
  81391. /**
  81392. * Sets wether the vignette effect is enabled.
  81393. */
  81394. set: function (value) {
  81395. if (this._vignetteEnabled === value) {
  81396. return;
  81397. }
  81398. this._vignetteEnabled = value;
  81399. this._updateParameters();
  81400. },
  81401. enumerable: true,
  81402. configurable: true
  81403. });
  81404. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  81405. /**
  81406. * Gets wether the image processing is applied through a post process or not.
  81407. */
  81408. get: function () {
  81409. return this._applyByPostProcess;
  81410. },
  81411. /**
  81412. * Sets wether the image processing is applied through a post process or not.
  81413. */
  81414. set: function (value) {
  81415. if (this._applyByPostProcess === value) {
  81416. return;
  81417. }
  81418. this._applyByPostProcess = value;
  81419. this._updateParameters();
  81420. },
  81421. enumerable: true,
  81422. configurable: true
  81423. });
  81424. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  81425. /**
  81426. * Gets wether the image processing is enabled or not.
  81427. */
  81428. get: function () {
  81429. return this._isEnabled;
  81430. },
  81431. /**
  81432. * Sets wether the image processing is enabled or not.
  81433. */
  81434. set: function (value) {
  81435. if (this._isEnabled === value) {
  81436. return;
  81437. }
  81438. this._isEnabled = value;
  81439. this._updateParameters();
  81440. },
  81441. enumerable: true,
  81442. configurable: true
  81443. });
  81444. /**
  81445. * Method called each time the image processing information changes requires to recompile the effect.
  81446. */
  81447. ImageProcessingConfiguration.prototype._updateParameters = function () {
  81448. this.onUpdateParameters.notifyObservers(this);
  81449. };
  81450. ImageProcessingConfiguration.prototype.getClassName = function () {
  81451. return "ImageProcessingConfiguration";
  81452. };
  81453. /**
  81454. * Prepare the list of uniforms associated with the Image Processing effects.
  81455. * @param uniformsList The list of uniforms used in the effect
  81456. * @param defines the list of defines currently in use
  81457. */
  81458. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  81459. if (defines.EXPOSURE) {
  81460. uniforms.push("exposureLinear");
  81461. }
  81462. if (defines.CONTRAST) {
  81463. uniforms.push("contrast");
  81464. }
  81465. if (defines.COLORGRADING) {
  81466. uniforms.push("colorTransformSettings");
  81467. }
  81468. if (defines.VIGNETTE) {
  81469. uniforms.push("vInverseScreenSize");
  81470. uniforms.push("vignetteSettings1");
  81471. uniforms.push("vignetteSettings2");
  81472. }
  81473. if (defines.COLORCURVES) {
  81474. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  81475. }
  81476. };
  81477. /**
  81478. * Prepare the list of samplers associated with the Image Processing effects.
  81479. * @param uniformsList The list of uniforms used in the effect
  81480. * @param defines the list of defines currently in use
  81481. */
  81482. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  81483. if (defines.COLORGRADING) {
  81484. samplersList.push("txColorTransform");
  81485. }
  81486. };
  81487. /**
  81488. * Prepare the list of defines associated to the shader.
  81489. * @param defines the list of defines to complete
  81490. */
  81491. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  81492. if (forPostProcess === void 0) { forPostProcess = false; }
  81493. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  81494. defines.VIGNETTE = false;
  81495. defines.TONEMAPPING = false;
  81496. defines.TONEMAPPING_ACES = false;
  81497. defines.CONTRAST = false;
  81498. defines.EXPOSURE = false;
  81499. defines.COLORCURVES = false;
  81500. defines.COLORGRADING = false;
  81501. defines.COLORGRADING3D = false;
  81502. defines.IMAGEPROCESSING = false;
  81503. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  81504. return;
  81505. }
  81506. defines.VIGNETTE = this.vignetteEnabled;
  81507. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  81508. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  81509. defines.TONEMAPPING = this.toneMappingEnabled;
  81510. switch (this._toneMappingType) {
  81511. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  81512. defines.TONEMAPPING_ACES = true;
  81513. break;
  81514. }
  81515. defines.CONTRAST = (this.contrast !== 1.0);
  81516. defines.EXPOSURE = (this.exposure !== 1.0);
  81517. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  81518. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  81519. if (defines.COLORGRADING) {
  81520. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  81521. }
  81522. else {
  81523. defines.COLORGRADING3D = false;
  81524. }
  81525. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  81526. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  81527. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  81528. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  81529. };
  81530. /**
  81531. * Returns true if all the image processing information are ready.
  81532. */
  81533. ImageProcessingConfiguration.prototype.isReady = function () {
  81534. // Color Grading texure can not be none blocking.
  81535. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  81536. };
  81537. /**
  81538. * Binds the image processing to the shader.
  81539. * @param effect The effect to bind to
  81540. */
  81541. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  81542. if (aspectRatio === void 0) { aspectRatio = 1; }
  81543. // Color Curves
  81544. if (this._colorCurvesEnabled && this.colorCurves) {
  81545. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  81546. }
  81547. // Vignette
  81548. if (this._vignetteEnabled) {
  81549. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  81550. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  81551. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  81552. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  81553. var vignetteScaleX = vignetteScaleY * aspectRatio;
  81554. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  81555. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  81556. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  81557. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  81558. var vignettePower = -2.0 * this.vignetteWeight;
  81559. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  81560. }
  81561. // Exposure
  81562. effect.setFloat("exposureLinear", this.exposure);
  81563. // Contrast
  81564. effect.setFloat("contrast", this.contrast);
  81565. // Color transform settings
  81566. if (this.colorGradingTexture) {
  81567. effect.setTexture("txColorTransform", this.colorGradingTexture);
  81568. var textureSize = this.colorGradingTexture.getSize().height;
  81569. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  81570. 0.5 / textureSize, // textureOffset
  81571. textureSize, // textureSize
  81572. this.colorGradingTexture.level // weight
  81573. );
  81574. }
  81575. };
  81576. /**
  81577. * Clones the current image processing instance.
  81578. * @return The cloned image processing
  81579. */
  81580. ImageProcessingConfiguration.prototype.clone = function () {
  81581. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  81582. };
  81583. /**
  81584. * Serializes the current image processing instance to a json representation.
  81585. * @return a JSON representation
  81586. */
  81587. ImageProcessingConfiguration.prototype.serialize = function () {
  81588. return BABYLON.SerializationHelper.Serialize(this);
  81589. };
  81590. /**
  81591. * Parses the image processing from a json representation.
  81592. * @param source the JSON source to parse
  81593. * @return The parsed image processing
  81594. */
  81595. ImageProcessingConfiguration.Parse = function (source) {
  81596. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  81597. };
  81598. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  81599. /**
  81600. * Used to apply the vignette as a mix with the pixel color.
  81601. */
  81602. get: function () {
  81603. return this._VIGNETTEMODE_MULTIPLY;
  81604. },
  81605. enumerable: true,
  81606. configurable: true
  81607. });
  81608. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  81609. /**
  81610. * Used to apply the vignette as a replacement of the pixel color.
  81611. */
  81612. get: function () {
  81613. return this._VIGNETTEMODE_OPAQUE;
  81614. },
  81615. enumerable: true,
  81616. configurable: true
  81617. });
  81618. /**
  81619. * Default tone mapping applied in BabylonJS.
  81620. */
  81621. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  81622. /**
  81623. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  81624. * to other engines rendering to increase portability.
  81625. */
  81626. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  81627. // Static constants associated to the image processing.
  81628. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  81629. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  81630. __decorate([
  81631. BABYLON.serializeAsColorCurves()
  81632. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  81633. __decorate([
  81634. BABYLON.serialize()
  81635. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  81636. __decorate([
  81637. BABYLON.serializeAsTexture()
  81638. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  81639. __decorate([
  81640. BABYLON.serialize()
  81641. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  81642. __decorate([
  81643. BABYLON.serialize()
  81644. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  81645. __decorate([
  81646. BABYLON.serialize()
  81647. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  81648. __decorate([
  81649. BABYLON.serialize()
  81650. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  81651. __decorate([
  81652. BABYLON.serialize()
  81653. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  81654. __decorate([
  81655. BABYLON.serialize()
  81656. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  81657. __decorate([
  81658. BABYLON.serialize()
  81659. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  81660. __decorate([
  81661. BABYLON.serialize()
  81662. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  81663. __decorate([
  81664. BABYLON.serialize()
  81665. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  81666. __decorate([
  81667. BABYLON.serialize()
  81668. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  81669. __decorate([
  81670. BABYLON.serialize()
  81671. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  81672. __decorate([
  81673. BABYLON.serializeAsColor4()
  81674. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  81675. __decorate([
  81676. BABYLON.serialize()
  81677. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  81678. __decorate([
  81679. BABYLON.serialize()
  81680. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  81681. __decorate([
  81682. BABYLON.serialize()
  81683. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  81684. __decorate([
  81685. BABYLON.serialize()
  81686. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  81687. __decorate([
  81688. BABYLON.serialize()
  81689. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  81690. return ImageProcessingConfiguration;
  81691. }());
  81692. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  81693. })(BABYLON || (BABYLON = {}));
  81694. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  81695. var BABYLON;
  81696. (function (BABYLON) {
  81697. /**
  81698. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  81699. * It can help converting any input color in a desired output one. This can then be used to create effects
  81700. * from sepia, black and white to sixties or futuristic rendering...
  81701. *
  81702. * The only supported format is currently 3dl.
  81703. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  81704. */
  81705. var ColorGradingTexture = /** @class */ (function (_super) {
  81706. __extends(ColorGradingTexture, _super);
  81707. /**
  81708. * Instantiates a ColorGradingTexture from the following parameters.
  81709. *
  81710. * @param url The location of the color gradind data (currently only supporting 3dl)
  81711. * @param scene The scene the texture will be used in
  81712. */
  81713. function ColorGradingTexture(url, scene) {
  81714. var _this = _super.call(this, scene) || this;
  81715. if (!url) {
  81716. return _this;
  81717. }
  81718. _this._engine = scene.getEngine();
  81719. _this._textureMatrix = BABYLON.Matrix.Identity();
  81720. _this.name = url;
  81721. _this.url = url;
  81722. _this.hasAlpha = false;
  81723. _this.isCube = false;
  81724. _this.is3D = _this._engine.webGLVersion > 1;
  81725. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81726. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81727. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81728. _this.anisotropicFilteringLevel = 1;
  81729. _this._texture = _this._getFromCache(url, true);
  81730. if (!_this._texture) {
  81731. if (!scene.useDelayedTextureLoading) {
  81732. _this.loadTexture();
  81733. }
  81734. else {
  81735. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  81736. }
  81737. }
  81738. return _this;
  81739. }
  81740. /**
  81741. * Returns the texture matrix used in most of the material.
  81742. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  81743. */
  81744. ColorGradingTexture.prototype.getTextureMatrix = function () {
  81745. return this._textureMatrix;
  81746. };
  81747. /**
  81748. * Occurs when the file being loaded is a .3dl LUT file.
  81749. */
  81750. ColorGradingTexture.prototype.load3dlTexture = function () {
  81751. var engine = this._engine;
  81752. var texture;
  81753. if (engine.webGLVersion === 1) {
  81754. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81755. }
  81756. else {
  81757. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81758. }
  81759. this._texture = texture;
  81760. var callback = function (text) {
  81761. if (typeof text !== "string") {
  81762. return;
  81763. }
  81764. var data = null;
  81765. var tempData = null;
  81766. var line;
  81767. var lines = text.split('\n');
  81768. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  81769. var maxColor = 0;
  81770. for (var i = 0; i < lines.length; i++) {
  81771. line = lines[i];
  81772. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  81773. continue;
  81774. if (line.indexOf('#') === 0)
  81775. continue;
  81776. var words = line.split(" ");
  81777. if (size === 0) {
  81778. // Number of space + one
  81779. size = words.length;
  81780. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  81781. tempData = new Float32Array(size * size * size * 4);
  81782. continue;
  81783. }
  81784. if (size != 0) {
  81785. var r = Math.max(parseInt(words[0]), 0);
  81786. var g = Math.max(parseInt(words[1]), 0);
  81787. var b = Math.max(parseInt(words[2]), 0);
  81788. maxColor = Math.max(r, maxColor);
  81789. maxColor = Math.max(g, maxColor);
  81790. maxColor = Math.max(b, maxColor);
  81791. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  81792. if (tempData) {
  81793. tempData[pixelStorageIndex + 0] = r;
  81794. tempData[pixelStorageIndex + 1] = g;
  81795. tempData[pixelStorageIndex + 2] = b;
  81796. }
  81797. pixelIndexSlice++;
  81798. if (pixelIndexSlice % size == 0) {
  81799. pixelIndexH++;
  81800. pixelIndexSlice = 0;
  81801. if (pixelIndexH % size == 0) {
  81802. pixelIndexW++;
  81803. pixelIndexH = 0;
  81804. }
  81805. }
  81806. }
  81807. }
  81808. if (tempData && data) {
  81809. for (var i = 0; i < tempData.length; i++) {
  81810. if (i > 0 && (i + 1) % 4 === 0) {
  81811. data[i] = 255;
  81812. }
  81813. else {
  81814. var value = tempData[i];
  81815. data[i] = (value / maxColor * 255);
  81816. }
  81817. }
  81818. }
  81819. if (texture.is3D) {
  81820. texture.updateSize(size, size, size);
  81821. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  81822. }
  81823. else {
  81824. texture.updateSize(size * size, size);
  81825. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  81826. }
  81827. };
  81828. var scene = this.getScene();
  81829. if (scene) {
  81830. scene._loadFile(this.url, callback);
  81831. }
  81832. else {
  81833. this._engine._loadFile(this.url, callback);
  81834. }
  81835. return this._texture;
  81836. };
  81837. /**
  81838. * Starts the loading process of the texture.
  81839. */
  81840. ColorGradingTexture.prototype.loadTexture = function () {
  81841. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  81842. this.load3dlTexture();
  81843. }
  81844. };
  81845. /**
  81846. * Clones the color gradind texture.
  81847. */
  81848. ColorGradingTexture.prototype.clone = function () {
  81849. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  81850. // Base texture
  81851. newTexture.level = this.level;
  81852. return newTexture;
  81853. };
  81854. /**
  81855. * Called during delayed load for textures.
  81856. */
  81857. ColorGradingTexture.prototype.delayLoad = function () {
  81858. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81859. return;
  81860. }
  81861. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81862. this._texture = this._getFromCache(this.url, true);
  81863. if (!this._texture) {
  81864. this.loadTexture();
  81865. }
  81866. };
  81867. /**
  81868. * Parses a color grading texture serialized by Babylon.
  81869. * @param parsedTexture The texture information being parsedTexture
  81870. * @param scene The scene to load the texture in
  81871. * @param rootUrl The root url of the data assets to load
  81872. * @return A color gradind texture
  81873. */
  81874. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81875. var texture = null;
  81876. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81877. texture = new ColorGradingTexture(parsedTexture.name, scene);
  81878. texture.name = parsedTexture.name;
  81879. texture.level = parsedTexture.level;
  81880. }
  81881. return texture;
  81882. };
  81883. /**
  81884. * Serializes the LUT texture to json format.
  81885. */
  81886. ColorGradingTexture.prototype.serialize = function () {
  81887. if (!this.name) {
  81888. return null;
  81889. }
  81890. var serializationObject = {};
  81891. serializationObject.name = this.name;
  81892. serializationObject.level = this.level;
  81893. serializationObject.customType = "BABYLON.ColorGradingTexture";
  81894. return serializationObject;
  81895. };
  81896. /**
  81897. * Empty line regex stored for GC.
  81898. */
  81899. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  81900. return ColorGradingTexture;
  81901. }(BABYLON.BaseTexture));
  81902. BABYLON.ColorGradingTexture = ColorGradingTexture;
  81903. })(BABYLON || (BABYLON = {}));
  81904. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  81905. var BABYLON;
  81906. (function (BABYLON) {
  81907. /**
  81908. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  81909. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  81910. * 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;
  81911. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  81912. */
  81913. var ColorCurves = /** @class */ (function () {
  81914. function ColorCurves() {
  81915. this._dirty = true;
  81916. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  81917. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  81918. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  81919. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  81920. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  81921. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  81922. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  81923. this._globalHue = 30;
  81924. this._globalDensity = 0;
  81925. this._globalSaturation = 0;
  81926. this._globalExposure = 0;
  81927. this._highlightsHue = 30;
  81928. this._highlightsDensity = 0;
  81929. this._highlightsSaturation = 0;
  81930. this._highlightsExposure = 0;
  81931. this._midtonesHue = 30;
  81932. this._midtonesDensity = 0;
  81933. this._midtonesSaturation = 0;
  81934. this._midtonesExposure = 0;
  81935. this._shadowsHue = 30;
  81936. this._shadowsDensity = 0;
  81937. this._shadowsSaturation = 0;
  81938. this._shadowsExposure = 0;
  81939. }
  81940. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  81941. /**
  81942. * Gets the global Hue value.
  81943. * 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).
  81944. */
  81945. get: function () {
  81946. return this._globalHue;
  81947. },
  81948. /**
  81949. * Sets the global Hue value.
  81950. * 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).
  81951. */
  81952. set: function (value) {
  81953. this._globalHue = value;
  81954. this._dirty = true;
  81955. },
  81956. enumerable: true,
  81957. configurable: true
  81958. });
  81959. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  81960. /**
  81961. * Gets the global Density value.
  81962. * 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.
  81963. * Values less than zero provide a filter of opposite hue.
  81964. */
  81965. get: function () {
  81966. return this._globalDensity;
  81967. },
  81968. /**
  81969. * Sets the global Density value.
  81970. * 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.
  81971. * Values less than zero provide a filter of opposite hue.
  81972. */
  81973. set: function (value) {
  81974. this._globalDensity = value;
  81975. this._dirty = true;
  81976. },
  81977. enumerable: true,
  81978. configurable: true
  81979. });
  81980. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  81981. /**
  81982. * Gets the global Saturation value.
  81983. * 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.
  81984. */
  81985. get: function () {
  81986. return this._globalSaturation;
  81987. },
  81988. /**
  81989. * Sets the global Saturation value.
  81990. * 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.
  81991. */
  81992. set: function (value) {
  81993. this._globalSaturation = value;
  81994. this._dirty = true;
  81995. },
  81996. enumerable: true,
  81997. configurable: true
  81998. });
  81999. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  82000. /**
  82001. * Gets the global Exposure value.
  82002. * 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.
  82003. */
  82004. get: function () {
  82005. return this._globalExposure;
  82006. },
  82007. /**
  82008. * Sets the global Exposure value.
  82009. * 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.
  82010. */
  82011. set: function (value) {
  82012. this._globalExposure = value;
  82013. this._dirty = true;
  82014. },
  82015. enumerable: true,
  82016. configurable: true
  82017. });
  82018. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  82019. /**
  82020. * Gets the highlights Hue value.
  82021. * 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).
  82022. */
  82023. get: function () {
  82024. return this._highlightsHue;
  82025. },
  82026. /**
  82027. * Sets the highlights Hue value.
  82028. * 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).
  82029. */
  82030. set: function (value) {
  82031. this._highlightsHue = value;
  82032. this._dirty = true;
  82033. },
  82034. enumerable: true,
  82035. configurable: true
  82036. });
  82037. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  82038. /**
  82039. * Gets the highlights Density value.
  82040. * 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.
  82041. * Values less than zero provide a filter of opposite hue.
  82042. */
  82043. get: function () {
  82044. return this._highlightsDensity;
  82045. },
  82046. /**
  82047. * Sets the highlights Density value.
  82048. * 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.
  82049. * Values less than zero provide a filter of opposite hue.
  82050. */
  82051. set: function (value) {
  82052. this._highlightsDensity = value;
  82053. this._dirty = true;
  82054. },
  82055. enumerable: true,
  82056. configurable: true
  82057. });
  82058. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  82059. /**
  82060. * Gets the highlights Saturation value.
  82061. * 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.
  82062. */
  82063. get: function () {
  82064. return this._highlightsSaturation;
  82065. },
  82066. /**
  82067. * Sets the highlights Saturation value.
  82068. * 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.
  82069. */
  82070. set: function (value) {
  82071. this._highlightsSaturation = value;
  82072. this._dirty = true;
  82073. },
  82074. enumerable: true,
  82075. configurable: true
  82076. });
  82077. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  82078. /**
  82079. * Gets the highlights Exposure value.
  82080. * 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.
  82081. */
  82082. get: function () {
  82083. return this._highlightsExposure;
  82084. },
  82085. /**
  82086. * Sets the highlights Exposure value.
  82087. * 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.
  82088. */
  82089. set: function (value) {
  82090. this._highlightsExposure = value;
  82091. this._dirty = true;
  82092. },
  82093. enumerable: true,
  82094. configurable: true
  82095. });
  82096. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  82097. /**
  82098. * Gets the midtones Hue value.
  82099. * 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).
  82100. */
  82101. get: function () {
  82102. return this._midtonesHue;
  82103. },
  82104. /**
  82105. * Sets the midtones Hue value.
  82106. * 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).
  82107. */
  82108. set: function (value) {
  82109. this._midtonesHue = value;
  82110. this._dirty = true;
  82111. },
  82112. enumerable: true,
  82113. configurable: true
  82114. });
  82115. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  82116. /**
  82117. * Gets the midtones Density value.
  82118. * 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.
  82119. * Values less than zero provide a filter of opposite hue.
  82120. */
  82121. get: function () {
  82122. return this._midtonesDensity;
  82123. },
  82124. /**
  82125. * Sets the midtones Density value.
  82126. * 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.
  82127. * Values less than zero provide a filter of opposite hue.
  82128. */
  82129. set: function (value) {
  82130. this._midtonesDensity = value;
  82131. this._dirty = true;
  82132. },
  82133. enumerable: true,
  82134. configurable: true
  82135. });
  82136. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  82137. /**
  82138. * Gets the midtones Saturation value.
  82139. * 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.
  82140. */
  82141. get: function () {
  82142. return this._midtonesSaturation;
  82143. },
  82144. /**
  82145. * Sets the midtones Saturation value.
  82146. * 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.
  82147. */
  82148. set: function (value) {
  82149. this._midtonesSaturation = value;
  82150. this._dirty = true;
  82151. },
  82152. enumerable: true,
  82153. configurable: true
  82154. });
  82155. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  82156. /**
  82157. * Gets the midtones Exposure value.
  82158. * 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.
  82159. */
  82160. get: function () {
  82161. return this._midtonesExposure;
  82162. },
  82163. /**
  82164. * Sets the midtones Exposure value.
  82165. * 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.
  82166. */
  82167. set: function (value) {
  82168. this._midtonesExposure = value;
  82169. this._dirty = true;
  82170. },
  82171. enumerable: true,
  82172. configurable: true
  82173. });
  82174. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  82175. /**
  82176. * Gets the shadows Hue value.
  82177. * 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).
  82178. */
  82179. get: function () {
  82180. return this._shadowsHue;
  82181. },
  82182. /**
  82183. * Sets the shadows Hue value.
  82184. * 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).
  82185. */
  82186. set: function (value) {
  82187. this._shadowsHue = value;
  82188. this._dirty = true;
  82189. },
  82190. enumerable: true,
  82191. configurable: true
  82192. });
  82193. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  82194. /**
  82195. * Gets the shadows Density value.
  82196. * 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.
  82197. * Values less than zero provide a filter of opposite hue.
  82198. */
  82199. get: function () {
  82200. return this._shadowsDensity;
  82201. },
  82202. /**
  82203. * Sets the shadows Density value.
  82204. * 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.
  82205. * Values less than zero provide a filter of opposite hue.
  82206. */
  82207. set: function (value) {
  82208. this._shadowsDensity = value;
  82209. this._dirty = true;
  82210. },
  82211. enumerable: true,
  82212. configurable: true
  82213. });
  82214. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  82215. /**
  82216. * Gets the shadows Saturation value.
  82217. * 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.
  82218. */
  82219. get: function () {
  82220. return this._shadowsSaturation;
  82221. },
  82222. /**
  82223. * Sets the shadows Saturation value.
  82224. * 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.
  82225. */
  82226. set: function (value) {
  82227. this._shadowsSaturation = value;
  82228. this._dirty = true;
  82229. },
  82230. enumerable: true,
  82231. configurable: true
  82232. });
  82233. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  82234. /**
  82235. * Gets the shadows Exposure value.
  82236. * 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.
  82237. */
  82238. get: function () {
  82239. return this._shadowsExposure;
  82240. },
  82241. /**
  82242. * Sets the shadows Exposure value.
  82243. * 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.
  82244. */
  82245. set: function (value) {
  82246. this._shadowsExposure = value;
  82247. this._dirty = true;
  82248. },
  82249. enumerable: true,
  82250. configurable: true
  82251. });
  82252. ColorCurves.prototype.getClassName = function () {
  82253. return "ColorCurves";
  82254. };
  82255. /**
  82256. * Binds the color curves to the shader.
  82257. * @param colorCurves The color curve to bind
  82258. * @param effect The effect to bind to
  82259. */
  82260. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  82261. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  82262. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  82263. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  82264. if (colorCurves._dirty) {
  82265. colorCurves._dirty = false;
  82266. // Fill in global info.
  82267. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  82268. // Compute highlights info.
  82269. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  82270. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  82271. // Compute midtones info.
  82272. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  82273. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  82274. // Compute shadows info.
  82275. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  82276. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  82277. // Compute deltas (neutral is midtones).
  82278. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  82279. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  82280. }
  82281. if (effect) {
  82282. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  82283. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  82284. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  82285. }
  82286. };
  82287. /**
  82288. * Prepare the list of uniforms associated with the ColorCurves effects.
  82289. * @param uniformsList The list of uniforms used in the effect
  82290. */
  82291. ColorCurves.PrepareUniforms = function (uniformsList) {
  82292. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  82293. };
  82294. /**
  82295. * Returns color grading data based on a hue, density, saturation and exposure value.
  82296. * @param filterHue The hue of the color filter.
  82297. * @param filterDensity The density of the color filter.
  82298. * @param saturation The saturation.
  82299. * @param exposure The exposure.
  82300. * @param result The result data container.
  82301. */
  82302. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  82303. if (hue == null) {
  82304. return;
  82305. }
  82306. hue = ColorCurves.clamp(hue, 0, 360);
  82307. density = ColorCurves.clamp(density, -100, 100);
  82308. saturation = ColorCurves.clamp(saturation, -100, 100);
  82309. exposure = ColorCurves.clamp(exposure, -100, 100);
  82310. // Remap the slider/config filter density with non-linear mapping and also scale by half
  82311. // so that the maximum filter density is only 50% control. This provides fine control
  82312. // for small values and reasonable range.
  82313. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  82314. density *= 0.5;
  82315. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  82316. if (density < 0) {
  82317. density *= -1;
  82318. hue = (hue + 180) % 360;
  82319. }
  82320. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  82321. result.scaleToRef(2, result);
  82322. result.a = 1 + 0.01 * saturation;
  82323. };
  82324. /**
  82325. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  82326. * @param value The input slider value in range [-100,100].
  82327. * @returns Adjusted value.
  82328. */
  82329. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  82330. value /= 100;
  82331. var x = Math.abs(value);
  82332. x = Math.pow(x, 2);
  82333. if (value < 0) {
  82334. x *= -1;
  82335. }
  82336. x *= 100;
  82337. return x;
  82338. };
  82339. /**
  82340. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  82341. * @param hue The hue (H) input.
  82342. * @param saturation The saturation (S) input.
  82343. * @param brightness The brightness (B) input.
  82344. * @result An RGBA color represented as Vector4.
  82345. */
  82346. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  82347. var h = ColorCurves.clamp(hue, 0, 360);
  82348. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  82349. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  82350. if (s === 0) {
  82351. result.r = v;
  82352. result.g = v;
  82353. result.b = v;
  82354. }
  82355. else {
  82356. // sector 0 to 5
  82357. h /= 60;
  82358. var i = Math.floor(h);
  82359. // fractional part of h
  82360. var f = h - i;
  82361. var p = v * (1 - s);
  82362. var q = v * (1 - s * f);
  82363. var t = v * (1 - s * (1 - f));
  82364. switch (i) {
  82365. case 0:
  82366. result.r = v;
  82367. result.g = t;
  82368. result.b = p;
  82369. break;
  82370. case 1:
  82371. result.r = q;
  82372. result.g = v;
  82373. result.b = p;
  82374. break;
  82375. case 2:
  82376. result.r = p;
  82377. result.g = v;
  82378. result.b = t;
  82379. break;
  82380. case 3:
  82381. result.r = p;
  82382. result.g = q;
  82383. result.b = v;
  82384. break;
  82385. case 4:
  82386. result.r = t;
  82387. result.g = p;
  82388. result.b = v;
  82389. break;
  82390. default: // case 5:
  82391. result.r = v;
  82392. result.g = p;
  82393. result.b = q;
  82394. break;
  82395. }
  82396. }
  82397. result.a = 1;
  82398. };
  82399. /**
  82400. * Returns a value clamped between min and max
  82401. * @param value The value to clamp
  82402. * @param min The minimum of value
  82403. * @param max The maximum of value
  82404. * @returns The clamped value.
  82405. */
  82406. ColorCurves.clamp = function (value, min, max) {
  82407. return Math.min(Math.max(value, min), max);
  82408. };
  82409. /**
  82410. * Clones the current color curve instance.
  82411. * @return The cloned curves
  82412. */
  82413. ColorCurves.prototype.clone = function () {
  82414. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  82415. };
  82416. /**
  82417. * Serializes the current color curve instance to a json representation.
  82418. * @return a JSON representation
  82419. */
  82420. ColorCurves.prototype.serialize = function () {
  82421. return BABYLON.SerializationHelper.Serialize(this);
  82422. };
  82423. /**
  82424. * Parses the color curve from a json representation.
  82425. * @param source the JSON source to parse
  82426. * @return The parsed curves
  82427. */
  82428. ColorCurves.Parse = function (source) {
  82429. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  82430. };
  82431. __decorate([
  82432. BABYLON.serialize()
  82433. ], ColorCurves.prototype, "_globalHue", void 0);
  82434. __decorate([
  82435. BABYLON.serialize()
  82436. ], ColorCurves.prototype, "_globalDensity", void 0);
  82437. __decorate([
  82438. BABYLON.serialize()
  82439. ], ColorCurves.prototype, "_globalSaturation", void 0);
  82440. __decorate([
  82441. BABYLON.serialize()
  82442. ], ColorCurves.prototype, "_globalExposure", void 0);
  82443. __decorate([
  82444. BABYLON.serialize()
  82445. ], ColorCurves.prototype, "_highlightsHue", void 0);
  82446. __decorate([
  82447. BABYLON.serialize()
  82448. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  82449. __decorate([
  82450. BABYLON.serialize()
  82451. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  82452. __decorate([
  82453. BABYLON.serialize()
  82454. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  82455. __decorate([
  82456. BABYLON.serialize()
  82457. ], ColorCurves.prototype, "_midtonesHue", void 0);
  82458. __decorate([
  82459. BABYLON.serialize()
  82460. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  82461. __decorate([
  82462. BABYLON.serialize()
  82463. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  82464. __decorate([
  82465. BABYLON.serialize()
  82466. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  82467. return ColorCurves;
  82468. }());
  82469. BABYLON.ColorCurves = ColorCurves;
  82470. })(BABYLON || (BABYLON = {}));
  82471. //# sourceMappingURL=babylon.colorCurves.js.map
  82472. var BABYLON;
  82473. (function (BABYLON) {
  82474. var RefractionPostProcess = /** @class */ (function (_super) {
  82475. __extends(RefractionPostProcess, _super);
  82476. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  82477. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  82478. _this.color = color;
  82479. _this.depth = depth;
  82480. _this.colorLevel = colorLevel;
  82481. _this._ownRefractionTexture = true;
  82482. _this.onActivateObservable.add(function (cam) {
  82483. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  82484. });
  82485. _this.onApplyObservable.add(function (effect) {
  82486. effect.setColor3("baseColor", _this.color);
  82487. effect.setFloat("depth", _this.depth);
  82488. effect.setFloat("colorLevel", _this.colorLevel);
  82489. effect.setTexture("refractionSampler", _this._refTexture);
  82490. });
  82491. return _this;
  82492. }
  82493. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  82494. /**
  82495. * Gets or sets the refraction texture
  82496. * Please note that you are responsible for disposing the texture if you set it manually
  82497. */
  82498. get: function () {
  82499. return this._refTexture;
  82500. },
  82501. set: function (value) {
  82502. if (this._refTexture && this._ownRefractionTexture) {
  82503. this._refTexture.dispose();
  82504. }
  82505. this._refTexture = value;
  82506. this._ownRefractionTexture = false;
  82507. },
  82508. enumerable: true,
  82509. configurable: true
  82510. });
  82511. // Methods
  82512. RefractionPostProcess.prototype.dispose = function (camera) {
  82513. if (this._refTexture && this._ownRefractionTexture) {
  82514. this._refTexture.dispose();
  82515. this._refTexture = null;
  82516. }
  82517. _super.prototype.dispose.call(this, camera);
  82518. };
  82519. return RefractionPostProcess;
  82520. }(BABYLON.PostProcess));
  82521. BABYLON.RefractionPostProcess = RefractionPostProcess;
  82522. })(BABYLON || (BABYLON = {}));
  82523. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  82524. var BABYLON;
  82525. (function (BABYLON) {
  82526. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  82527. __extends(BlackAndWhitePostProcess, _super);
  82528. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  82529. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  82530. _this.degree = 1;
  82531. _this.onApplyObservable.add(function (effect) {
  82532. effect.setFloat("degree", _this.degree);
  82533. });
  82534. return _this;
  82535. }
  82536. return BlackAndWhitePostProcess;
  82537. }(BABYLON.PostProcess));
  82538. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  82539. })(BABYLON || (BABYLON = {}));
  82540. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  82541. var BABYLON;
  82542. (function (BABYLON) {
  82543. /**
  82544. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  82545. * input texture to perform effects such as edge detection or sharpening
  82546. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  82547. */
  82548. var ConvolutionPostProcess = /** @class */ (function (_super) {
  82549. __extends(ConvolutionPostProcess, _super);
  82550. /**
  82551. * Creates a new instance ConvolutionPostProcess
  82552. * @param name The name of the effect.
  82553. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  82554. * @param options The required width/height ratio to downsize to before computing the render pass.
  82555. * @param camera The camera to apply the render pass to.
  82556. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82557. * @param engine The engine which the post process will be applied. (default: current engine)
  82558. * @param reusable If the post process can be reused on the same frame. (default: false)
  82559. * @param textureType Type of textures used when performing the post process. (default: 0)
  82560. */
  82561. function ConvolutionPostProcess(name,
  82562. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  82563. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  82564. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82565. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  82566. _this.kernel = kernel;
  82567. _this.onApply = function (effect) {
  82568. effect.setFloat2("screenSize", _this.width, _this.height);
  82569. effect.setArray("kernel", _this.kernel);
  82570. };
  82571. return _this;
  82572. }
  82573. // Statics
  82574. /**
  82575. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  82576. */
  82577. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  82578. /**
  82579. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  82580. */
  82581. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  82582. /**
  82583. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  82584. */
  82585. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  82586. /**
  82587. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  82588. */
  82589. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  82590. /**
  82591. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  82592. */
  82593. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  82594. /**
  82595. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  82596. */
  82597. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  82598. return ConvolutionPostProcess;
  82599. }(BABYLON.PostProcess));
  82600. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  82601. })(BABYLON || (BABYLON = {}));
  82602. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  82603. var BABYLON;
  82604. (function (BABYLON) {
  82605. var FilterPostProcess = /** @class */ (function (_super) {
  82606. __extends(FilterPostProcess, _super);
  82607. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  82608. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  82609. _this.kernelMatrix = kernelMatrix;
  82610. _this.onApply = function (effect) {
  82611. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  82612. };
  82613. return _this;
  82614. }
  82615. return FilterPostProcess;
  82616. }(BABYLON.PostProcess));
  82617. BABYLON.FilterPostProcess = FilterPostProcess;
  82618. })(BABYLON || (BABYLON = {}));
  82619. //# sourceMappingURL=babylon.filterPostProcess.js.map
  82620. var BABYLON;
  82621. (function (BABYLON) {
  82622. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  82623. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  82624. __extends(VolumetricLightScatteringPostProcess, _super);
  82625. /**
  82626. * @constructor
  82627. * @param {string} name - The post-process name
  82628. * @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)
  82629. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  82630. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  82631. * @param {number} samples - The post-process quality, default 100
  82632. * @param {number} samplingMode - The post-process filtering mode
  82633. * @param {BABYLON.Engine} engine - The babylon engine
  82634. * @param {boolean} reusable - If the post-process is reusable
  82635. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  82636. */
  82637. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  82638. if (samples === void 0) { samples = 100; }
  82639. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82640. 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;
  82641. _this._screenCoordinates = BABYLON.Vector2.Zero();
  82642. /**
  82643. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  82644. */
  82645. _this.customMeshPosition = BABYLON.Vector3.Zero();
  82646. /**
  82647. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  82648. */
  82649. _this.useCustomMeshPosition = false;
  82650. /**
  82651. * If the post-process should inverse the light scattering direction
  82652. */
  82653. _this.invert = true;
  82654. /**
  82655. * Array containing the excluded meshes not rendered in the internal pass
  82656. */
  82657. _this.excludedMeshes = new Array();
  82658. /**
  82659. * Controls the overall intensity of the post-process
  82660. */
  82661. _this.exposure = 0.3;
  82662. /**
  82663. * Dissipates each sample's contribution in range [0, 1]
  82664. */
  82665. _this.decay = 0.96815;
  82666. /**
  82667. * Controls the overall intensity of each sample
  82668. */
  82669. _this.weight = 0.58767;
  82670. /**
  82671. * Controls the density of each sample
  82672. */
  82673. _this.density = 0.926;
  82674. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  82675. engine = scene.getEngine();
  82676. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  82677. // Configure mesh
  82678. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  82679. // Configure
  82680. _this._createPass(scene, ratio.passRatio || ratio);
  82681. _this.onActivate = function (camera) {
  82682. if (!_this.isSupported) {
  82683. _this.dispose(camera);
  82684. }
  82685. _this.onActivate = null;
  82686. };
  82687. _this.onApplyObservable.add(function (effect) {
  82688. _this._updateMeshScreenCoordinates(scene);
  82689. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  82690. effect.setFloat("exposure", _this.exposure);
  82691. effect.setFloat("decay", _this.decay);
  82692. effect.setFloat("weight", _this.weight);
  82693. effect.setFloat("density", _this.density);
  82694. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  82695. });
  82696. return _this;
  82697. }
  82698. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  82699. get: function () {
  82700. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  82701. return false;
  82702. },
  82703. set: function (useDiffuseColor) {
  82704. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  82705. },
  82706. enumerable: true,
  82707. configurable: true
  82708. });
  82709. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  82710. return "VolumetricLightScatteringPostProcess";
  82711. };
  82712. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  82713. var mesh = subMesh.getMesh();
  82714. // Render this.mesh as default
  82715. if (mesh === this.mesh && mesh.material) {
  82716. return mesh.material.isReady(mesh);
  82717. }
  82718. var defines = [];
  82719. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82720. var material = subMesh.getMaterial();
  82721. // Alpha test
  82722. if (material) {
  82723. if (material.needAlphaTesting()) {
  82724. defines.push("#define ALPHATEST");
  82725. }
  82726. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82727. attribs.push(BABYLON.VertexBuffer.UVKind);
  82728. defines.push("#define UV1");
  82729. }
  82730. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82731. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82732. defines.push("#define UV2");
  82733. }
  82734. }
  82735. // Bones
  82736. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82737. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82738. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82739. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82740. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  82741. }
  82742. else {
  82743. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82744. }
  82745. // Instances
  82746. if (useInstances) {
  82747. defines.push("#define INSTANCES");
  82748. attribs.push("world0");
  82749. attribs.push("world1");
  82750. attribs.push("world2");
  82751. attribs.push("world3");
  82752. }
  82753. // Get correct effect
  82754. var join = defines.join("\n");
  82755. if (this._cachedDefines !== join) {
  82756. this._cachedDefines = join;
  82757. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  82758. }
  82759. return this._volumetricLightScatteringPass.isReady();
  82760. };
  82761. /**
  82762. * Sets the new light position for light scattering effect
  82763. * @param {BABYLON.Vector3} The new custom light position
  82764. */
  82765. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  82766. this.customMeshPosition = position;
  82767. };
  82768. /**
  82769. * Returns the light position for light scattering effect
  82770. * @return {BABYLON.Vector3} The custom light position
  82771. */
  82772. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  82773. return this.customMeshPosition;
  82774. };
  82775. /**
  82776. * Disposes the internal assets and detaches the post-process from the camera
  82777. */
  82778. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  82779. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  82780. if (rttIndex !== -1) {
  82781. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  82782. }
  82783. this._volumetricLightScatteringRTT.dispose();
  82784. _super.prototype.dispose.call(this, camera);
  82785. };
  82786. /**
  82787. * Returns the render target texture used by the post-process
  82788. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  82789. */
  82790. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  82791. return this._volumetricLightScatteringRTT;
  82792. };
  82793. // Private methods
  82794. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  82795. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  82796. return true;
  82797. }
  82798. return false;
  82799. };
  82800. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  82801. var _this = this;
  82802. var engine = scene.getEngine();
  82803. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82804. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82805. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82806. this._volumetricLightScatteringRTT.renderList = null;
  82807. this._volumetricLightScatteringRTT.renderParticles = false;
  82808. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  82809. var camera = this.getCamera();
  82810. if (camera) {
  82811. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  82812. }
  82813. else {
  82814. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  82815. }
  82816. // Custom render function for submeshes
  82817. var renderSubMesh = function (subMesh) {
  82818. var mesh = subMesh.getRenderingMesh();
  82819. if (_this._meshExcluded(mesh)) {
  82820. return;
  82821. }
  82822. var material = subMesh.getMaterial();
  82823. if (!material) {
  82824. return;
  82825. }
  82826. var scene = mesh.getScene();
  82827. var engine = scene.getEngine();
  82828. // Culling
  82829. engine.setState(material.backFaceCulling);
  82830. // Managing instances
  82831. var batch = mesh._getInstancesRenderList(subMesh._id);
  82832. if (batch.mustReturn) {
  82833. return;
  82834. }
  82835. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  82836. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  82837. var effect = _this._volumetricLightScatteringPass;
  82838. if (mesh === _this.mesh) {
  82839. if (subMesh.effect) {
  82840. effect = subMesh.effect;
  82841. }
  82842. else {
  82843. effect = material.getEffect();
  82844. }
  82845. }
  82846. engine.enableEffect(effect);
  82847. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  82848. if (mesh === _this.mesh) {
  82849. material.bind(mesh.getWorldMatrix(), mesh);
  82850. }
  82851. else {
  82852. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  82853. // Alpha test
  82854. if (material && material.needAlphaTesting()) {
  82855. var alphaTexture = material.getAlphaTestTexture();
  82856. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  82857. if (alphaTexture) {
  82858. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82859. }
  82860. }
  82861. // Bones
  82862. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82863. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82864. }
  82865. }
  82866. // Draw
  82867. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  82868. }
  82869. };
  82870. // Render target texture callbacks
  82871. var savedSceneClearColor;
  82872. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  82873. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  82874. savedSceneClearColor = scene.clearColor;
  82875. scene.clearColor = sceneClearColor;
  82876. });
  82877. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  82878. scene.clearColor = savedSceneClearColor;
  82879. });
  82880. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82881. var engine = scene.getEngine();
  82882. var index;
  82883. if (depthOnlySubMeshes.length) {
  82884. engine.setColorWrite(false);
  82885. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82886. renderSubMesh(depthOnlySubMeshes.data[index]);
  82887. }
  82888. engine.setColorWrite(true);
  82889. }
  82890. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82891. renderSubMesh(opaqueSubMeshes.data[index]);
  82892. }
  82893. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82894. renderSubMesh(alphaTestSubMeshes.data[index]);
  82895. }
  82896. if (transparentSubMeshes.length) {
  82897. // Sort sub meshes
  82898. for (index = 0; index < transparentSubMeshes.length; index++) {
  82899. var submesh = transparentSubMeshes.data[index];
  82900. var boundingInfo = submesh.getBoundingInfo();
  82901. if (boundingInfo && scene.activeCamera) {
  82902. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  82903. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  82904. }
  82905. }
  82906. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  82907. sortedArray.sort(function (a, b) {
  82908. // Alpha index first
  82909. if (a._alphaIndex > b._alphaIndex) {
  82910. return 1;
  82911. }
  82912. if (a._alphaIndex < b._alphaIndex) {
  82913. return -1;
  82914. }
  82915. // Then distance to camera
  82916. if (a._distanceToCamera < b._distanceToCamera) {
  82917. return 1;
  82918. }
  82919. if (a._distanceToCamera > b._distanceToCamera) {
  82920. return -1;
  82921. }
  82922. return 0;
  82923. });
  82924. // Render sub meshes
  82925. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  82926. for (index = 0; index < sortedArray.length; index++) {
  82927. renderSubMesh(sortedArray[index]);
  82928. }
  82929. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82930. }
  82931. };
  82932. };
  82933. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  82934. var transform = scene.getTransformMatrix();
  82935. var meshPosition;
  82936. if (this.useCustomMeshPosition) {
  82937. meshPosition = this.customMeshPosition;
  82938. }
  82939. else if (this.attachedNode) {
  82940. meshPosition = this.attachedNode.position;
  82941. }
  82942. else {
  82943. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  82944. }
  82945. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  82946. this._screenCoordinates.x = pos.x / this._viewPort.width;
  82947. this._screenCoordinates.y = pos.y / this._viewPort.height;
  82948. if (this.invert)
  82949. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  82950. };
  82951. // Static methods
  82952. /**
  82953. * Creates a default mesh for the Volumeric Light Scattering post-process
  82954. * @param {string} The mesh name
  82955. * @param {BABYLON.Scene} The scene where to create the mesh
  82956. * @return {BABYLON.Mesh} the default mesh
  82957. */
  82958. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  82959. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  82960. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  82961. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  82962. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  82963. mesh.material = material;
  82964. return mesh;
  82965. };
  82966. __decorate([
  82967. BABYLON.serializeAsVector3()
  82968. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  82969. __decorate([
  82970. BABYLON.serialize()
  82971. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  82972. __decorate([
  82973. BABYLON.serialize()
  82974. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  82975. __decorate([
  82976. BABYLON.serializeAsMeshReference()
  82977. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  82978. __decorate([
  82979. BABYLON.serialize()
  82980. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  82981. __decorate([
  82982. BABYLON.serialize()
  82983. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  82984. __decorate([
  82985. BABYLON.serialize()
  82986. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  82987. __decorate([
  82988. BABYLON.serialize()
  82989. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  82990. __decorate([
  82991. BABYLON.serialize()
  82992. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  82993. return VolumetricLightScatteringPostProcess;
  82994. }(BABYLON.PostProcess));
  82995. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  82996. })(BABYLON || (BABYLON = {}));
  82997. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  82998. //
  82999. // This post-process allows the modification of rendered colors by using
  83000. // a 'look-up table' (LUT). This effect is also called Color Grading.
  83001. //
  83002. // The object needs to be provided an url to a texture containing the color
  83003. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  83004. // Use an image editing software to tweak the LUT to match your needs.
  83005. //
  83006. // For an example of a color LUT, see here:
  83007. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  83008. // For explanations on color grading, see here:
  83009. // http://udn.epicgames.com/Three/ColorGrading.html
  83010. //
  83011. var BABYLON;
  83012. (function (BABYLON) {
  83013. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  83014. __extends(ColorCorrectionPostProcess, _super);
  83015. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  83016. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  83017. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83018. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  83019. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83020. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83021. _this.onApply = function (effect) {
  83022. effect.setTexture("colorTable", _this._colorTableTexture);
  83023. };
  83024. return _this;
  83025. }
  83026. return ColorCorrectionPostProcess;
  83027. }(BABYLON.PostProcess));
  83028. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  83029. })(BABYLON || (BABYLON = {}));
  83030. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  83031. var BABYLON;
  83032. (function (BABYLON) {
  83033. /** Defines operator used for tonemapping */
  83034. var TonemappingOperator;
  83035. (function (TonemappingOperator) {
  83036. /** Hable */
  83037. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  83038. /** Reinhard */
  83039. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  83040. /** HejiDawson */
  83041. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  83042. /** Photographic */
  83043. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  83044. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  83045. ;
  83046. /**
  83047. * Defines a post process to apply tone mapping
  83048. */
  83049. var TonemapPostProcess = /** @class */ (function (_super) {
  83050. __extends(TonemapPostProcess, _super);
  83051. /**
  83052. * Creates a new TonemapPostProcess
  83053. * @param name defines the name of the postprocess
  83054. * @param _operator defines the operator to use
  83055. * @param exposureAdjustment defines the required exposure adjustement
  83056. * @param camera defines the camera to use (can be null)
  83057. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  83058. * @param engine defines the hosting engine (can be ignore if camera is set)
  83059. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  83060. */
  83061. function TonemapPostProcess(name, _operator,
  83062. /** Defines the required exposure adjustement */
  83063. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  83064. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83065. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83066. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  83067. _this._operator = _operator;
  83068. _this.exposureAdjustment = exposureAdjustment;
  83069. var defines = "#define ";
  83070. if (_this._operator === TonemappingOperator.Hable)
  83071. defines += "HABLE_TONEMAPPING";
  83072. else if (_this._operator === TonemappingOperator.Reinhard)
  83073. defines += "REINHARD_TONEMAPPING";
  83074. else if (_this._operator === TonemappingOperator.HejiDawson)
  83075. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  83076. else if (_this._operator === TonemappingOperator.Photographic)
  83077. defines += "PHOTOGRAPHIC_TONEMAPPING";
  83078. //sadly a second call to create the effect.
  83079. _this.updateEffect(defines);
  83080. _this.onApply = function (effect) {
  83081. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  83082. };
  83083. return _this;
  83084. }
  83085. return TonemapPostProcess;
  83086. }(BABYLON.PostProcess));
  83087. BABYLON.TonemapPostProcess = TonemapPostProcess;
  83088. })(BABYLON || (BABYLON = {}));
  83089. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  83090. var BABYLON;
  83091. (function (BABYLON) {
  83092. var DisplayPassPostProcess = /** @class */ (function (_super) {
  83093. __extends(DisplayPassPostProcess, _super);
  83094. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  83095. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  83096. }
  83097. return DisplayPassPostProcess;
  83098. }(BABYLON.PostProcess));
  83099. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  83100. })(BABYLON || (BABYLON = {}));
  83101. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  83102. var BABYLON;
  83103. (function (BABYLON) {
  83104. var HighlightsPostProcess = /** @class */ (function (_super) {
  83105. __extends(HighlightsPostProcess, _super);
  83106. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  83107. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83108. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83109. }
  83110. return HighlightsPostProcess;
  83111. }(BABYLON.PostProcess));
  83112. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  83113. })(BABYLON || (BABYLON = {}));
  83114. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  83115. var BABYLON;
  83116. (function (BABYLON) {
  83117. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  83118. __extends(ImageProcessingPostProcess, _super);
  83119. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  83120. if (camera === void 0) { camera = null; }
  83121. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83122. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  83123. _this._fromLinearSpace = true;
  83124. /**
  83125. * Defines cache preventing GC.
  83126. */
  83127. _this._defines = {
  83128. IMAGEPROCESSING: false,
  83129. VIGNETTE: false,
  83130. VIGNETTEBLENDMODEMULTIPLY: false,
  83131. VIGNETTEBLENDMODEOPAQUE: false,
  83132. TONEMAPPING: false,
  83133. TONEMAPPING_ACES: false,
  83134. CONTRAST: false,
  83135. COLORCURVES: false,
  83136. COLORGRADING: false,
  83137. COLORGRADING3D: false,
  83138. FROMLINEARSPACE: false,
  83139. SAMPLER3DGREENDEPTH: false,
  83140. SAMPLER3DBGRMAP: false,
  83141. IMAGEPROCESSINGPOSTPROCESS: false,
  83142. EXPOSURE: false,
  83143. };
  83144. // Setup the configuration as forced by the constructor. This would then not force the
  83145. // scene materials output in linear space and let untouched the default forward pass.
  83146. if (imageProcessingConfiguration) {
  83147. imageProcessingConfiguration.applyByPostProcess = true;
  83148. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  83149. // This will cause the shader to be compiled
  83150. _this.fromLinearSpace = false;
  83151. }
  83152. // Setup the default processing configuration to the scene.
  83153. else {
  83154. _this._attachImageProcessingConfiguration(null, true);
  83155. _this.imageProcessingConfiguration.applyByPostProcess = true;
  83156. }
  83157. _this.onApply = function (effect) {
  83158. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  83159. };
  83160. return _this;
  83161. }
  83162. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  83163. /**
  83164. * Gets the image processing configuration used either in this material.
  83165. */
  83166. get: function () {
  83167. return this._imageProcessingConfiguration;
  83168. },
  83169. /**
  83170. * Sets the Default image processing configuration used either in the this material.
  83171. *
  83172. * If sets to null, the scene one is in use.
  83173. */
  83174. set: function (value) {
  83175. this._attachImageProcessingConfiguration(value);
  83176. },
  83177. enumerable: true,
  83178. configurable: true
  83179. });
  83180. /**
  83181. * Attaches a new image processing configuration to the PBR Material.
  83182. * @param configuration
  83183. */
  83184. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  83185. var _this = this;
  83186. if (doNotBuild === void 0) { doNotBuild = false; }
  83187. if (configuration === this._imageProcessingConfiguration) {
  83188. return;
  83189. }
  83190. // Detaches observer.
  83191. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83192. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83193. }
  83194. // Pick the scene configuration if needed.
  83195. if (!configuration) {
  83196. var scene = null;
  83197. var engine = this.getEngine();
  83198. var camera = this.getCamera();
  83199. if (camera) {
  83200. scene = camera.getScene();
  83201. }
  83202. else if (engine && engine.scenes) {
  83203. var scenes = engine.scenes;
  83204. scene = scenes[scenes.length - 1];
  83205. }
  83206. else {
  83207. scene = BABYLON.Engine.LastCreatedScene;
  83208. }
  83209. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  83210. }
  83211. else {
  83212. this._imageProcessingConfiguration = configuration;
  83213. }
  83214. // Attaches observer.
  83215. if (this._imageProcessingConfiguration) {
  83216. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  83217. _this._updateParameters();
  83218. });
  83219. }
  83220. // Ensure the effect will be rebuilt.
  83221. if (!doNotBuild) {
  83222. this._updateParameters();
  83223. }
  83224. };
  83225. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  83226. /**
  83227. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  83228. */
  83229. get: function () {
  83230. return this.imageProcessingConfiguration.colorCurves;
  83231. },
  83232. /**
  83233. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  83234. */
  83235. set: function (value) {
  83236. this.imageProcessingConfiguration.colorCurves = value;
  83237. },
  83238. enumerable: true,
  83239. configurable: true
  83240. });
  83241. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  83242. /**
  83243. * Gets wether the color curves effect is enabled.
  83244. */
  83245. get: function () {
  83246. return this.imageProcessingConfiguration.colorCurvesEnabled;
  83247. },
  83248. /**
  83249. * Sets wether the color curves effect is enabled.
  83250. */
  83251. set: function (value) {
  83252. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  83253. },
  83254. enumerable: true,
  83255. configurable: true
  83256. });
  83257. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  83258. /**
  83259. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  83260. */
  83261. get: function () {
  83262. return this.imageProcessingConfiguration.colorGradingTexture;
  83263. },
  83264. /**
  83265. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  83266. */
  83267. set: function (value) {
  83268. this.imageProcessingConfiguration.colorGradingTexture = value;
  83269. },
  83270. enumerable: true,
  83271. configurable: true
  83272. });
  83273. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  83274. /**
  83275. * Gets wether the color grading effect is enabled.
  83276. */
  83277. get: function () {
  83278. return this.imageProcessingConfiguration.colorGradingEnabled;
  83279. },
  83280. /**
  83281. * Gets wether the color grading effect is enabled.
  83282. */
  83283. set: function (value) {
  83284. this.imageProcessingConfiguration.colorGradingEnabled = value;
  83285. },
  83286. enumerable: true,
  83287. configurable: true
  83288. });
  83289. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  83290. /**
  83291. * Gets exposure used in the effect.
  83292. */
  83293. get: function () {
  83294. return this.imageProcessingConfiguration.exposure;
  83295. },
  83296. /**
  83297. * Sets exposure used in the effect.
  83298. */
  83299. set: function (value) {
  83300. this.imageProcessingConfiguration.exposure = value;
  83301. },
  83302. enumerable: true,
  83303. configurable: true
  83304. });
  83305. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  83306. /**
  83307. * Gets wether tonemapping is enabled or not.
  83308. */
  83309. get: function () {
  83310. return this._imageProcessingConfiguration.toneMappingEnabled;
  83311. },
  83312. /**
  83313. * Sets wether tonemapping is enabled or not
  83314. */
  83315. set: function (value) {
  83316. this._imageProcessingConfiguration.toneMappingEnabled = value;
  83317. },
  83318. enumerable: true,
  83319. configurable: true
  83320. });
  83321. ;
  83322. ;
  83323. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  83324. /**
  83325. * Gets contrast used in the effect.
  83326. */
  83327. get: function () {
  83328. return this.imageProcessingConfiguration.contrast;
  83329. },
  83330. /**
  83331. * Sets contrast used in the effect.
  83332. */
  83333. set: function (value) {
  83334. this.imageProcessingConfiguration.contrast = value;
  83335. },
  83336. enumerable: true,
  83337. configurable: true
  83338. });
  83339. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  83340. /**
  83341. * Gets Vignette stretch size.
  83342. */
  83343. get: function () {
  83344. return this.imageProcessingConfiguration.vignetteStretch;
  83345. },
  83346. /**
  83347. * Sets Vignette stretch size.
  83348. */
  83349. set: function (value) {
  83350. this.imageProcessingConfiguration.vignetteStretch = value;
  83351. },
  83352. enumerable: true,
  83353. configurable: true
  83354. });
  83355. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  83356. /**
  83357. * Gets Vignette centre X Offset.
  83358. */
  83359. get: function () {
  83360. return this.imageProcessingConfiguration.vignetteCentreX;
  83361. },
  83362. /**
  83363. * Sets Vignette centre X Offset.
  83364. */
  83365. set: function (value) {
  83366. this.imageProcessingConfiguration.vignetteCentreX = value;
  83367. },
  83368. enumerable: true,
  83369. configurable: true
  83370. });
  83371. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  83372. /**
  83373. * Gets Vignette centre Y Offset.
  83374. */
  83375. get: function () {
  83376. return this.imageProcessingConfiguration.vignetteCentreY;
  83377. },
  83378. /**
  83379. * Sets Vignette centre Y Offset.
  83380. */
  83381. set: function (value) {
  83382. this.imageProcessingConfiguration.vignetteCentreY = value;
  83383. },
  83384. enumerable: true,
  83385. configurable: true
  83386. });
  83387. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  83388. /**
  83389. * Gets Vignette weight or intensity of the vignette effect.
  83390. */
  83391. get: function () {
  83392. return this.imageProcessingConfiguration.vignetteWeight;
  83393. },
  83394. /**
  83395. * Sets Vignette weight or intensity of the vignette effect.
  83396. */
  83397. set: function (value) {
  83398. this.imageProcessingConfiguration.vignetteWeight = value;
  83399. },
  83400. enumerable: true,
  83401. configurable: true
  83402. });
  83403. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  83404. /**
  83405. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  83406. * if vignetteEnabled is set to true.
  83407. */
  83408. get: function () {
  83409. return this.imageProcessingConfiguration.vignetteColor;
  83410. },
  83411. /**
  83412. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  83413. * if vignetteEnabled is set to true.
  83414. */
  83415. set: function (value) {
  83416. this.imageProcessingConfiguration.vignetteColor = value;
  83417. },
  83418. enumerable: true,
  83419. configurable: true
  83420. });
  83421. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  83422. /**
  83423. * Gets Camera field of view used by the Vignette effect.
  83424. */
  83425. get: function () {
  83426. return this.imageProcessingConfiguration.vignetteCameraFov;
  83427. },
  83428. /**
  83429. * Sets Camera field of view used by the Vignette effect.
  83430. */
  83431. set: function (value) {
  83432. this.imageProcessingConfiguration.vignetteCameraFov = value;
  83433. },
  83434. enumerable: true,
  83435. configurable: true
  83436. });
  83437. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  83438. /**
  83439. * Gets the vignette blend mode allowing different kind of effect.
  83440. */
  83441. get: function () {
  83442. return this.imageProcessingConfiguration.vignetteBlendMode;
  83443. },
  83444. /**
  83445. * Sets the vignette blend mode allowing different kind of effect.
  83446. */
  83447. set: function (value) {
  83448. this.imageProcessingConfiguration.vignetteBlendMode = value;
  83449. },
  83450. enumerable: true,
  83451. configurable: true
  83452. });
  83453. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  83454. /**
  83455. * Gets wether the vignette effect is enabled.
  83456. */
  83457. get: function () {
  83458. return this.imageProcessingConfiguration.vignetteEnabled;
  83459. },
  83460. /**
  83461. * Sets wether the vignette effect is enabled.
  83462. */
  83463. set: function (value) {
  83464. this.imageProcessingConfiguration.vignetteEnabled = value;
  83465. },
  83466. enumerable: true,
  83467. configurable: true
  83468. });
  83469. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  83470. /**
  83471. * Gets wether the input of the processing is in Gamma or Linear Space.
  83472. */
  83473. get: function () {
  83474. return this._fromLinearSpace;
  83475. },
  83476. /**
  83477. * Sets wether the input of the processing is in Gamma or Linear Space.
  83478. */
  83479. set: function (value) {
  83480. if (this._fromLinearSpace === value) {
  83481. return;
  83482. }
  83483. this._fromLinearSpace = value;
  83484. this._updateParameters();
  83485. },
  83486. enumerable: true,
  83487. configurable: true
  83488. });
  83489. ImageProcessingPostProcess.prototype.getClassName = function () {
  83490. return "ImageProcessingPostProcess";
  83491. };
  83492. ImageProcessingPostProcess.prototype._updateParameters = function () {
  83493. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  83494. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  83495. var defines = "";
  83496. for (var define in this._defines) {
  83497. if (this._defines[define]) {
  83498. defines += "#define " + define + ";\r\n";
  83499. }
  83500. }
  83501. var samplers = ["textureSampler"];
  83502. var uniforms = ["scale"];
  83503. if (BABYLON.ImageProcessingConfiguration) {
  83504. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  83505. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  83506. }
  83507. this.updateEffect(defines, uniforms, samplers);
  83508. };
  83509. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  83510. _super.prototype.dispose.call(this, camera);
  83511. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83512. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83513. }
  83514. if (this._imageProcessingConfiguration) {
  83515. this.imageProcessingConfiguration.applyByPostProcess = false;
  83516. }
  83517. };
  83518. __decorate([
  83519. BABYLON.serialize()
  83520. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  83521. return ImageProcessingPostProcess;
  83522. }(BABYLON.PostProcess));
  83523. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  83524. })(BABYLON || (BABYLON = {}));
  83525. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  83526. var BABYLON;
  83527. (function (BABYLON) {
  83528. /**
  83529. * Class used to store bone information
  83530. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  83531. */
  83532. var Bone = /** @class */ (function (_super) {
  83533. __extends(Bone, _super);
  83534. /**
  83535. * Create a new bone
  83536. * @param name defines the bone name
  83537. * @param skeleton defines the parent skeleton
  83538. * @param parentBone defines the parent (can be null if the bone is the root)
  83539. * @param localMatrix defines the local matrix
  83540. * @param restPose defines the rest pose matrix
  83541. * @param baseMatrix defines the base matrix
  83542. * @param index defines index of the bone in the hiearchy
  83543. */
  83544. function Bone(
  83545. /**
  83546. * defines the bone name
  83547. */
  83548. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  83549. if (parentBone === void 0) { parentBone = null; }
  83550. if (localMatrix === void 0) { localMatrix = null; }
  83551. if (restPose === void 0) { restPose = null; }
  83552. if (baseMatrix === void 0) { baseMatrix = null; }
  83553. if (index === void 0) { index = null; }
  83554. var _this = _super.call(this, name, skeleton.getScene()) || this;
  83555. _this.name = name;
  83556. /**
  83557. * Gets the list of child bones
  83558. */
  83559. _this.children = new Array();
  83560. /** Gets the animations associated with this bone */
  83561. _this.animations = new Array();
  83562. /**
  83563. * @hidden Internal only
  83564. * Set this value to map this bone to a different index in the transform matrices
  83565. * Set this value to -1 to exclude the bone from the transform matrices
  83566. */
  83567. _this._index = null;
  83568. _this._absoluteTransform = new BABYLON.Matrix();
  83569. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  83570. _this._scalingDeterminant = 1;
  83571. _this._worldTransform = new BABYLON.Matrix();
  83572. _this._needToDecompose = true;
  83573. _this._needToCompose = false;
  83574. _this._skeleton = skeleton;
  83575. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  83576. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  83577. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  83578. _this._index = index;
  83579. skeleton.bones.push(_this);
  83580. _this.setParent(parentBone, false);
  83581. if (baseMatrix || localMatrix) {
  83582. _this._updateDifferenceMatrix();
  83583. }
  83584. return _this;
  83585. }
  83586. Object.defineProperty(Bone.prototype, "_matrix", {
  83587. /** @hidden */
  83588. get: function () {
  83589. this._compose();
  83590. return this._localMatrix;
  83591. },
  83592. /** @hidden */
  83593. set: function (value) {
  83594. this._localMatrix.copyFrom(value);
  83595. this._needToDecompose = true;
  83596. },
  83597. enumerable: true,
  83598. configurable: true
  83599. });
  83600. // Members
  83601. /**
  83602. * Gets the parent skeleton
  83603. * @returns a skeleton
  83604. */
  83605. Bone.prototype.getSkeleton = function () {
  83606. return this._skeleton;
  83607. };
  83608. /**
  83609. * Gets parent bone
  83610. * @returns a bone or null if the bone is the root of the bone hierarchy
  83611. */
  83612. Bone.prototype.getParent = function () {
  83613. return this._parent;
  83614. };
  83615. /**
  83616. * Sets the parent bone
  83617. * @param parent defines the parent (can be null if the bone is the root)
  83618. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  83619. */
  83620. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  83621. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  83622. if (this._parent === parent) {
  83623. return;
  83624. }
  83625. if (this._parent) {
  83626. var index = this._parent.children.indexOf(this);
  83627. if (index !== -1) {
  83628. this._parent.children.splice(index, 1);
  83629. }
  83630. }
  83631. this._parent = parent;
  83632. if (this._parent) {
  83633. this._parent.children.push(this);
  83634. }
  83635. if (updateDifferenceMatrix) {
  83636. this._updateDifferenceMatrix();
  83637. }
  83638. this.markAsDirty();
  83639. };
  83640. /**
  83641. * Gets the local matrix
  83642. * @returns a matrix
  83643. */
  83644. Bone.prototype.getLocalMatrix = function () {
  83645. this._compose();
  83646. return this._localMatrix;
  83647. };
  83648. /**
  83649. * Gets the base matrix (initial matrix which remains unchanged)
  83650. * @returns a matrix
  83651. */
  83652. Bone.prototype.getBaseMatrix = function () {
  83653. return this._baseMatrix;
  83654. };
  83655. /**
  83656. * Gets the rest pose matrix
  83657. * @returns a matrix
  83658. */
  83659. Bone.prototype.getRestPose = function () {
  83660. return this._restPose;
  83661. };
  83662. /**
  83663. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  83664. */
  83665. Bone.prototype.getWorldMatrix = function () {
  83666. return this._worldTransform;
  83667. };
  83668. /**
  83669. * Sets the local matrix to rest pose matrix
  83670. */
  83671. Bone.prototype.returnToRest = function () {
  83672. this.updateMatrix(this._restPose.clone());
  83673. };
  83674. /**
  83675. * Gets the inverse of the absolute transform matrix.
  83676. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  83677. * @returns a matrix
  83678. */
  83679. Bone.prototype.getInvertedAbsoluteTransform = function () {
  83680. return this._invertedAbsoluteTransform;
  83681. };
  83682. /**
  83683. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  83684. * @returns a matrix
  83685. */
  83686. Bone.prototype.getAbsoluteTransform = function () {
  83687. return this._absoluteTransform;
  83688. };
  83689. Object.defineProperty(Bone.prototype, "position", {
  83690. // Properties (matches AbstractMesh properties)
  83691. /** Gets or sets current position (in local space) */
  83692. get: function () {
  83693. this._decompose();
  83694. return this._localPosition;
  83695. },
  83696. set: function (newPosition) {
  83697. this._decompose();
  83698. this._localPosition.copyFrom(newPosition);
  83699. this._markAsDirtyAndCompose();
  83700. },
  83701. enumerable: true,
  83702. configurable: true
  83703. });
  83704. Object.defineProperty(Bone.prototype, "rotation", {
  83705. /** Gets or sets current rotation (in local space) */
  83706. get: function () {
  83707. return this.getRotation();
  83708. },
  83709. set: function (newRotation) {
  83710. this.setRotation(newRotation);
  83711. },
  83712. enumerable: true,
  83713. configurable: true
  83714. });
  83715. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  83716. /** Gets or sets current rotation quaternion (in local space) */
  83717. get: function () {
  83718. this._decompose();
  83719. return this._localRotation;
  83720. },
  83721. set: function (newRotation) {
  83722. this.setRotationQuaternion(newRotation);
  83723. },
  83724. enumerable: true,
  83725. configurable: true
  83726. });
  83727. Object.defineProperty(Bone.prototype, "scaling", {
  83728. /** Gets or sets current scaling (in local space) */
  83729. get: function () {
  83730. return this.getScale();
  83731. },
  83732. set: function (newScaling) {
  83733. this.setScale(newScaling);
  83734. },
  83735. enumerable: true,
  83736. configurable: true
  83737. });
  83738. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  83739. /**
  83740. * Gets the animation properties override
  83741. */
  83742. get: function () {
  83743. return this._skeleton.animationPropertiesOverride;
  83744. },
  83745. enumerable: true,
  83746. configurable: true
  83747. });
  83748. // Methods
  83749. Bone.prototype._decompose = function () {
  83750. if (!this._needToDecompose) {
  83751. return;
  83752. }
  83753. this._needToDecompose = false;
  83754. if (!this._localScaling) {
  83755. this._localScaling = BABYLON.Vector3.Zero();
  83756. this._localRotation = BABYLON.Quaternion.Zero();
  83757. this._localPosition = BABYLON.Vector3.Zero();
  83758. }
  83759. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  83760. };
  83761. Bone.prototype._compose = function () {
  83762. if (!this._needToCompose) {
  83763. return;
  83764. }
  83765. this._needToCompose = false;
  83766. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  83767. };
  83768. /**
  83769. * Update the base and local matrices
  83770. * @param matrix defines the new base or local matrix
  83771. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  83772. * @param updateLocalMatrix defines if the local matrix should be updated
  83773. */
  83774. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  83775. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  83776. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  83777. this._baseMatrix.copyFrom(matrix);
  83778. if (updateDifferenceMatrix) {
  83779. this._updateDifferenceMatrix();
  83780. }
  83781. if (updateLocalMatrix) {
  83782. this._localMatrix.copyFrom(matrix);
  83783. this._markAsDirtyAndDecompose();
  83784. }
  83785. else {
  83786. this.markAsDirty();
  83787. }
  83788. };
  83789. /** @hidden */
  83790. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  83791. if (updateChildren === void 0) { updateChildren = true; }
  83792. if (!rootMatrix) {
  83793. rootMatrix = this._baseMatrix;
  83794. }
  83795. if (this._parent) {
  83796. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  83797. }
  83798. else {
  83799. this._absoluteTransform.copyFrom(rootMatrix);
  83800. }
  83801. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  83802. if (updateChildren) {
  83803. for (var index = 0; index < this.children.length; index++) {
  83804. this.children[index]._updateDifferenceMatrix();
  83805. }
  83806. }
  83807. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  83808. };
  83809. /**
  83810. * Flag the bone as dirty (Forcing it to update everything)
  83811. */
  83812. Bone.prototype.markAsDirty = function () {
  83813. this._currentRenderId++;
  83814. this._childRenderId++;
  83815. this._skeleton._markAsDirty();
  83816. };
  83817. Bone.prototype._markAsDirtyAndCompose = function () {
  83818. this.markAsDirty();
  83819. this._needToCompose = true;
  83820. };
  83821. Bone.prototype._markAsDirtyAndDecompose = function () {
  83822. this.markAsDirty();
  83823. this._needToDecompose = true;
  83824. };
  83825. /**
  83826. * Copy an animation range from another bone
  83827. * @param source defines the source bone
  83828. * @param rangeName defines the range name to copy
  83829. * @param frameOffset defines the frame offset
  83830. * @param rescaleAsRequired defines if rescaling must be applied if required
  83831. * @param skelDimensionsRatio defines the scaling ratio
  83832. * @returns true if operation was successful
  83833. */
  83834. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  83835. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  83836. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  83837. // all animation may be coming from a library skeleton, so may need to create animation
  83838. if (this.animations.length === 0) {
  83839. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  83840. this.animations[0].setKeys([]);
  83841. }
  83842. // get animation info / verify there is such a range from the source bone
  83843. var sourceRange = source.animations[0].getRange(rangeName);
  83844. if (!sourceRange) {
  83845. return false;
  83846. }
  83847. var from = sourceRange.from;
  83848. var to = sourceRange.to;
  83849. var sourceKeys = source.animations[0].getKeys();
  83850. // rescaling prep
  83851. var sourceBoneLength = source.length;
  83852. var sourceParent = source.getParent();
  83853. var parent = this.getParent();
  83854. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  83855. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  83856. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  83857. var destKeys = this.animations[0].getKeys();
  83858. // loop vars declaration
  83859. var orig;
  83860. var origTranslation;
  83861. var mat;
  83862. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  83863. orig = sourceKeys[key];
  83864. if (orig.frame >= from && orig.frame <= to) {
  83865. if (rescaleAsRequired) {
  83866. mat = orig.value.clone();
  83867. // scale based on parent ratio, when bone has parent
  83868. if (parentScalingReqd) {
  83869. origTranslation = mat.getTranslation();
  83870. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  83871. // scale based on skeleton dimension ratio when root bone, and value is passed
  83872. }
  83873. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  83874. origTranslation = mat.getTranslation();
  83875. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  83876. // use original when root bone, and no data for skelDimensionsRatio
  83877. }
  83878. else {
  83879. mat = orig.value;
  83880. }
  83881. }
  83882. else {
  83883. mat = orig.value;
  83884. }
  83885. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  83886. }
  83887. }
  83888. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  83889. return true;
  83890. };
  83891. /**
  83892. * Translate the bone in local or world space
  83893. * @param vec The amount to translate the bone
  83894. * @param space The space that the translation is in
  83895. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83896. */
  83897. Bone.prototype.translate = function (vec, space, mesh) {
  83898. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83899. var lm = this.getLocalMatrix();
  83900. if (space == BABYLON.Space.LOCAL) {
  83901. lm.m[12] += vec.x;
  83902. lm.m[13] += vec.y;
  83903. lm.m[14] += vec.z;
  83904. }
  83905. else {
  83906. var wm = null;
  83907. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83908. if (mesh) {
  83909. wm = mesh.getWorldMatrix();
  83910. }
  83911. this._skeleton.computeAbsoluteTransforms();
  83912. var tmat = Bone._tmpMats[0];
  83913. var tvec = Bone._tmpVecs[0];
  83914. if (this._parent) {
  83915. if (mesh && wm) {
  83916. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83917. tmat.multiplyToRef(wm, tmat);
  83918. }
  83919. else {
  83920. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83921. }
  83922. }
  83923. tmat.m[12] = 0;
  83924. tmat.m[13] = 0;
  83925. tmat.m[14] = 0;
  83926. tmat.invert();
  83927. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  83928. lm.m[12] += tvec.x;
  83929. lm.m[13] += tvec.y;
  83930. lm.m[14] += tvec.z;
  83931. }
  83932. this._markAsDirtyAndDecompose();
  83933. };
  83934. /**
  83935. * Set the postion of the bone in local or world space
  83936. * @param position The position to set the bone
  83937. * @param space The space that the position is in
  83938. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83939. */
  83940. Bone.prototype.setPosition = function (position, space, mesh) {
  83941. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83942. var lm = this.getLocalMatrix();
  83943. if (space == BABYLON.Space.LOCAL) {
  83944. lm.m[12] = position.x;
  83945. lm.m[13] = position.y;
  83946. lm.m[14] = position.z;
  83947. }
  83948. else {
  83949. var wm = null;
  83950. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83951. if (mesh) {
  83952. wm = mesh.getWorldMatrix();
  83953. }
  83954. this._skeleton.computeAbsoluteTransforms();
  83955. var tmat = Bone._tmpMats[0];
  83956. var vec = Bone._tmpVecs[0];
  83957. if (this._parent) {
  83958. if (mesh && wm) {
  83959. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83960. tmat.multiplyToRef(wm, tmat);
  83961. }
  83962. else {
  83963. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83964. }
  83965. }
  83966. tmat.invert();
  83967. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  83968. lm.m[12] = vec.x;
  83969. lm.m[13] = vec.y;
  83970. lm.m[14] = vec.z;
  83971. }
  83972. this._markAsDirtyAndDecompose();
  83973. };
  83974. /**
  83975. * Set the absolute position of the bone (world space)
  83976. * @param position The position to set the bone
  83977. * @param mesh The mesh that this bone is attached to
  83978. */
  83979. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  83980. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  83981. };
  83982. /**
  83983. * Scale the bone on the x, y and z axes (in local space)
  83984. * @param x The amount to scale the bone on the x axis
  83985. * @param y The amount to scale the bone on the y axis
  83986. * @param z The amount to scale the bone on the z axis
  83987. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  83988. */
  83989. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  83990. if (scaleChildren === void 0) { scaleChildren = false; }
  83991. var locMat = this.getLocalMatrix();
  83992. // Apply new scaling on top of current local matrix
  83993. var scaleMat = Bone._tmpMats[0];
  83994. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  83995. scaleMat.multiplyToRef(locMat, locMat);
  83996. // Invert scaling matrix and apply the inverse to all children
  83997. scaleMat.invert();
  83998. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  83999. var child = _a[_i];
  84000. var cm = child.getLocalMatrix();
  84001. cm.multiplyToRef(scaleMat, cm);
  84002. cm.m[12] *= x;
  84003. cm.m[13] *= y;
  84004. cm.m[14] *= z;
  84005. child._markAsDirtyAndDecompose();
  84006. }
  84007. this._markAsDirtyAndDecompose();
  84008. if (scaleChildren) {
  84009. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  84010. var child = _c[_b];
  84011. child.scale(x, y, z, scaleChildren);
  84012. }
  84013. }
  84014. };
  84015. /**
  84016. * Set the bone scaling in local space
  84017. * @param scale defines the scaling vector
  84018. */
  84019. Bone.prototype.setScale = function (scale) {
  84020. this._decompose();
  84021. this._localScaling.copyFrom(scale);
  84022. this._markAsDirtyAndCompose();
  84023. };
  84024. /**
  84025. * Gets the current scaling in local space
  84026. * @returns the current scaling vector
  84027. */
  84028. Bone.prototype.getScale = function () {
  84029. this._decompose();
  84030. return this._localScaling;
  84031. };
  84032. /**
  84033. * Gets the current scaling in local space and stores it in a target vector
  84034. * @param result defines the target vector
  84035. */
  84036. Bone.prototype.getScaleToRef = function (result) {
  84037. this._decompose();
  84038. result.copyFrom(this._localScaling);
  84039. };
  84040. /**
  84041. * Set the yaw, pitch, and roll of the bone in local or world space
  84042. * @param yaw The rotation of the bone on the y axis
  84043. * @param pitch The rotation of the bone on the x axis
  84044. * @param roll The rotation of the bone on the z axis
  84045. * @param space The space that the axes of rotation are in
  84046. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84047. */
  84048. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  84049. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84050. if (space === BABYLON.Space.LOCAL) {
  84051. var quat = Bone._tmpQuat;
  84052. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  84053. this.setRotationQuaternion(quat, space, mesh);
  84054. return;
  84055. }
  84056. var rotMatInv = Bone._tmpMats[0];
  84057. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84058. return;
  84059. }
  84060. var rotMat = Bone._tmpMats[1];
  84061. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  84062. rotMatInv.multiplyToRef(rotMat, rotMat);
  84063. this._rotateWithMatrix(rotMat, space, mesh);
  84064. };
  84065. /**
  84066. * Add a rotation to the bone on an axis in local or world space
  84067. * @param axis The axis to rotate the bone on
  84068. * @param amount The amount to rotate the bone
  84069. * @param space The space that the axis is in
  84070. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84071. */
  84072. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  84073. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84074. var rmat = Bone._tmpMats[0];
  84075. rmat.m[12] = 0;
  84076. rmat.m[13] = 0;
  84077. rmat.m[14] = 0;
  84078. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  84079. this._rotateWithMatrix(rmat, space, mesh);
  84080. };
  84081. /**
  84082. * Set the rotation of the bone to a particular axis angle in local or world space
  84083. * @param axis The axis to rotate the bone on
  84084. * @param angle The angle that the bone should be rotated to
  84085. * @param space The space that the axis is in
  84086. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84087. */
  84088. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  84089. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84090. if (space === BABYLON.Space.LOCAL) {
  84091. var quat = Bone._tmpQuat;
  84092. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  84093. this.setRotationQuaternion(quat, space, mesh);
  84094. return;
  84095. }
  84096. var rotMatInv = Bone._tmpMats[0];
  84097. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84098. return;
  84099. }
  84100. var rotMat = Bone._tmpMats[1];
  84101. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  84102. rotMatInv.multiplyToRef(rotMat, rotMat);
  84103. this._rotateWithMatrix(rotMat, space, mesh);
  84104. };
  84105. /**
  84106. * Set the euler rotation of the bone in local of world space
  84107. * @param rotation The euler rotation that the bone should be set to
  84108. * @param space The space that the rotation is in
  84109. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84110. */
  84111. Bone.prototype.setRotation = function (rotation, space, mesh) {
  84112. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84113. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  84114. };
  84115. /**
  84116. * Set the quaternion rotation of the bone in local of world space
  84117. * @param quat The quaternion rotation that the bone should be set to
  84118. * @param space The space that the rotation is in
  84119. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84120. */
  84121. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  84122. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84123. if (space === BABYLON.Space.LOCAL) {
  84124. this._decompose();
  84125. this._localRotation.copyFrom(quat);
  84126. this._markAsDirtyAndCompose();
  84127. return;
  84128. }
  84129. var rotMatInv = Bone._tmpMats[0];
  84130. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84131. return;
  84132. }
  84133. var rotMat = Bone._tmpMats[1];
  84134. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  84135. rotMatInv.multiplyToRef(rotMat, rotMat);
  84136. this._rotateWithMatrix(rotMat, space, mesh);
  84137. };
  84138. /**
  84139. * Set the rotation matrix of the bone in local of world space
  84140. * @param rotMat The rotation matrix that the bone should be set to
  84141. * @param space The space that the rotation is in
  84142. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84143. */
  84144. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  84145. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84146. if (space === BABYLON.Space.LOCAL) {
  84147. var quat = Bone._tmpQuat;
  84148. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  84149. this.setRotationQuaternion(quat, space, mesh);
  84150. return;
  84151. }
  84152. var rotMatInv = Bone._tmpMats[0];
  84153. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84154. return;
  84155. }
  84156. var rotMat2 = Bone._tmpMats[1];
  84157. rotMat2.copyFrom(rotMat);
  84158. rotMatInv.multiplyToRef(rotMat, rotMat2);
  84159. this._rotateWithMatrix(rotMat2, space, mesh);
  84160. };
  84161. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  84162. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84163. var lmat = this.getLocalMatrix();
  84164. var lx = lmat.m[12];
  84165. var ly = lmat.m[13];
  84166. var lz = lmat.m[14];
  84167. var parent = this.getParent();
  84168. var parentScale = Bone._tmpMats[3];
  84169. var parentScaleInv = Bone._tmpMats[4];
  84170. if (parent && space == BABYLON.Space.WORLD) {
  84171. if (mesh) {
  84172. parentScale.copyFrom(mesh.getWorldMatrix());
  84173. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  84174. }
  84175. else {
  84176. parentScale.copyFrom(parent.getAbsoluteTransform());
  84177. }
  84178. parentScaleInv.copyFrom(parentScale);
  84179. parentScaleInv.invert();
  84180. lmat.multiplyToRef(parentScale, lmat);
  84181. lmat.multiplyToRef(rmat, lmat);
  84182. lmat.multiplyToRef(parentScaleInv, lmat);
  84183. }
  84184. else {
  84185. if (space == BABYLON.Space.WORLD && mesh) {
  84186. parentScale.copyFrom(mesh.getWorldMatrix());
  84187. parentScaleInv.copyFrom(parentScale);
  84188. parentScaleInv.invert();
  84189. lmat.multiplyToRef(parentScale, lmat);
  84190. lmat.multiplyToRef(rmat, lmat);
  84191. lmat.multiplyToRef(parentScaleInv, lmat);
  84192. }
  84193. else {
  84194. lmat.multiplyToRef(rmat, lmat);
  84195. }
  84196. }
  84197. lmat.m[12] = lx;
  84198. lmat.m[13] = ly;
  84199. lmat.m[14] = lz;
  84200. this.computeAbsoluteTransforms();
  84201. this._markAsDirtyAndDecompose();
  84202. };
  84203. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  84204. var scaleMatrix = Bone._tmpMats[2];
  84205. rotMatInv.copyFrom(this.getAbsoluteTransform());
  84206. if (mesh) {
  84207. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  84208. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  84209. }
  84210. rotMatInv.invert();
  84211. if (isNaN(rotMatInv.m[0])) {
  84212. // Matrix failed to invert.
  84213. // This can happen if scale is zero for example.
  84214. return false;
  84215. }
  84216. scaleMatrix.m[0] *= this._scalingDeterminant;
  84217. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  84218. return true;
  84219. };
  84220. /**
  84221. * Get the position of the bone in local or world space
  84222. * @param space The space that the returned position is in
  84223. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84224. * @returns The position of the bone
  84225. */
  84226. Bone.prototype.getPosition = function (space, mesh) {
  84227. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84228. if (mesh === void 0) { mesh = null; }
  84229. var pos = BABYLON.Vector3.Zero();
  84230. this.getPositionToRef(space, mesh, pos);
  84231. return pos;
  84232. };
  84233. /**
  84234. * Copy the position of the bone to a vector3 in local or world space
  84235. * @param space The space that the returned position is in
  84236. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84237. * @param result The vector3 to copy the position to
  84238. */
  84239. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  84240. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84241. if (space == BABYLON.Space.LOCAL) {
  84242. var lm = this.getLocalMatrix();
  84243. result.x = lm.m[12];
  84244. result.y = lm.m[13];
  84245. result.z = lm.m[14];
  84246. }
  84247. else {
  84248. var wm = null;
  84249. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84250. if (mesh) {
  84251. wm = mesh.getWorldMatrix();
  84252. }
  84253. this._skeleton.computeAbsoluteTransforms();
  84254. var tmat = Bone._tmpMats[0];
  84255. if (mesh && wm) {
  84256. tmat.copyFrom(this.getAbsoluteTransform());
  84257. tmat.multiplyToRef(wm, tmat);
  84258. }
  84259. else {
  84260. tmat = this.getAbsoluteTransform();
  84261. }
  84262. result.x = tmat.m[12];
  84263. result.y = tmat.m[13];
  84264. result.z = tmat.m[14];
  84265. }
  84266. };
  84267. /**
  84268. * Get the absolute position of the bone (world space)
  84269. * @param mesh The mesh that this bone is attached to
  84270. * @returns The absolute position of the bone
  84271. */
  84272. Bone.prototype.getAbsolutePosition = function (mesh) {
  84273. if (mesh === void 0) { mesh = null; }
  84274. var pos = BABYLON.Vector3.Zero();
  84275. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  84276. return pos;
  84277. };
  84278. /**
  84279. * Copy the absolute position of the bone (world space) to the result param
  84280. * @param mesh The mesh that this bone is attached to
  84281. * @param result The vector3 to copy the absolute position to
  84282. */
  84283. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  84284. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  84285. };
  84286. /**
  84287. * Compute the absolute transforms of this bone and its children
  84288. */
  84289. Bone.prototype.computeAbsoluteTransforms = function () {
  84290. this._compose();
  84291. if (this._parent) {
  84292. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  84293. }
  84294. else {
  84295. this._absoluteTransform.copyFrom(this._localMatrix);
  84296. var poseMatrix = this._skeleton.getPoseMatrix();
  84297. if (poseMatrix) {
  84298. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  84299. }
  84300. }
  84301. var children = this.children;
  84302. var len = children.length;
  84303. for (var i = 0; i < len; i++) {
  84304. children[i].computeAbsoluteTransforms();
  84305. }
  84306. };
  84307. /**
  84308. * Get the world direction from an axis that is in the local space of the bone
  84309. * @param localAxis The local direction that is used to compute the world direction
  84310. * @param mesh The mesh that this bone is attached to
  84311. * @returns The world direction
  84312. */
  84313. Bone.prototype.getDirection = function (localAxis, mesh) {
  84314. if (mesh === void 0) { mesh = null; }
  84315. var result = BABYLON.Vector3.Zero();
  84316. this.getDirectionToRef(localAxis, mesh, result);
  84317. return result;
  84318. };
  84319. /**
  84320. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  84321. * @param localAxis The local direction that is used to compute the world direction
  84322. * @param mesh The mesh that this bone is attached to
  84323. * @param result The vector3 that the world direction will be copied to
  84324. */
  84325. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  84326. if (mesh === void 0) { mesh = null; }
  84327. var wm = null;
  84328. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84329. if (mesh) {
  84330. wm = mesh.getWorldMatrix();
  84331. }
  84332. this._skeleton.computeAbsoluteTransforms();
  84333. var mat = Bone._tmpMats[0];
  84334. mat.copyFrom(this.getAbsoluteTransform());
  84335. if (mesh && wm) {
  84336. mat.multiplyToRef(wm, mat);
  84337. }
  84338. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  84339. result.normalize();
  84340. };
  84341. /**
  84342. * Get the euler rotation of the bone in local or world space
  84343. * @param space The space that the rotation should be in
  84344. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84345. * @returns The euler rotation
  84346. */
  84347. Bone.prototype.getRotation = function (space, mesh) {
  84348. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84349. if (mesh === void 0) { mesh = null; }
  84350. var result = BABYLON.Vector3.Zero();
  84351. this.getRotationToRef(space, mesh, result);
  84352. return result;
  84353. };
  84354. /**
  84355. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  84356. * @param space The space that the rotation should be in
  84357. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84358. * @param result The vector3 that the rotation should be copied to
  84359. */
  84360. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  84361. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84362. if (mesh === void 0) { mesh = null; }
  84363. var quat = Bone._tmpQuat;
  84364. this.getRotationQuaternionToRef(space, mesh, quat);
  84365. quat.toEulerAnglesToRef(result);
  84366. };
  84367. /**
  84368. * Get the quaternion rotation of the bone in either local or world space
  84369. * @param space The space that the rotation should be in
  84370. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84371. * @returns The quaternion rotation
  84372. */
  84373. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  84374. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84375. if (mesh === void 0) { mesh = null; }
  84376. var result = BABYLON.Quaternion.Identity();
  84377. this.getRotationQuaternionToRef(space, mesh, result);
  84378. return result;
  84379. };
  84380. /**
  84381. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  84382. * @param space The space that the rotation should be in
  84383. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84384. * @param result The quaternion that the rotation should be copied to
  84385. */
  84386. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  84387. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84388. if (mesh === void 0) { mesh = null; }
  84389. if (space == BABYLON.Space.LOCAL) {
  84390. this._decompose();
  84391. result.copyFrom(this._localRotation);
  84392. }
  84393. else {
  84394. var mat = Bone._tmpMats[0];
  84395. var amat = this.getAbsoluteTransform();
  84396. if (mesh) {
  84397. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  84398. }
  84399. else {
  84400. mat.copyFrom(amat);
  84401. }
  84402. mat.m[0] *= this._scalingDeterminant;
  84403. mat.m[1] *= this._scalingDeterminant;
  84404. mat.m[2] *= this._scalingDeterminant;
  84405. mat.decompose(undefined, result, undefined);
  84406. }
  84407. };
  84408. /**
  84409. * Get the rotation matrix of the bone in local or world space
  84410. * @param space The space that the rotation should be in
  84411. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84412. * @returns The rotation matrix
  84413. */
  84414. Bone.prototype.getRotationMatrix = function (space, mesh) {
  84415. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84416. var result = BABYLON.Matrix.Identity();
  84417. this.getRotationMatrixToRef(space, mesh, result);
  84418. return result;
  84419. };
  84420. /**
  84421. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  84422. * @param space The space that the rotation should be in
  84423. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84424. * @param result The quaternion that the rotation should be copied to
  84425. */
  84426. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  84427. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84428. if (space == BABYLON.Space.LOCAL) {
  84429. this.getLocalMatrix().getRotationMatrixToRef(result);
  84430. }
  84431. else {
  84432. var mat = Bone._tmpMats[0];
  84433. var amat = this.getAbsoluteTransform();
  84434. if (mesh) {
  84435. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  84436. }
  84437. else {
  84438. mat.copyFrom(amat);
  84439. }
  84440. mat.m[0] *= this._scalingDeterminant;
  84441. mat.m[1] *= this._scalingDeterminant;
  84442. mat.m[2] *= this._scalingDeterminant;
  84443. mat.getRotationMatrixToRef(result);
  84444. }
  84445. };
  84446. /**
  84447. * Get the world position of a point that is in the local space of the bone
  84448. * @param position The local position
  84449. * @param mesh The mesh that this bone is attached to
  84450. * @returns The world position
  84451. */
  84452. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  84453. if (mesh === void 0) { mesh = null; }
  84454. var result = BABYLON.Vector3.Zero();
  84455. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  84456. return result;
  84457. };
  84458. /**
  84459. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  84460. * @param position The local position
  84461. * @param mesh The mesh that this bone is attached to
  84462. * @param result The vector3 that the world position should be copied to
  84463. */
  84464. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  84465. if (mesh === void 0) { mesh = null; }
  84466. var wm = null;
  84467. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84468. if (mesh) {
  84469. wm = mesh.getWorldMatrix();
  84470. }
  84471. this._skeleton.computeAbsoluteTransforms();
  84472. var tmat = Bone._tmpMats[0];
  84473. if (mesh && wm) {
  84474. tmat.copyFrom(this.getAbsoluteTransform());
  84475. tmat.multiplyToRef(wm, tmat);
  84476. }
  84477. else {
  84478. tmat = this.getAbsoluteTransform();
  84479. }
  84480. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  84481. };
  84482. /**
  84483. * Get the local position of a point that is in world space
  84484. * @param position The world position
  84485. * @param mesh The mesh that this bone is attached to
  84486. * @returns The local position
  84487. */
  84488. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  84489. if (mesh === void 0) { mesh = null; }
  84490. var result = BABYLON.Vector3.Zero();
  84491. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  84492. return result;
  84493. };
  84494. /**
  84495. * Get the local position of a point that is in world space and copy it to the result param
  84496. * @param position The world position
  84497. * @param mesh The mesh that this bone is attached to
  84498. * @param result The vector3 that the local position should be copied to
  84499. */
  84500. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  84501. if (mesh === void 0) { mesh = null; }
  84502. var wm = null;
  84503. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84504. if (mesh) {
  84505. wm = mesh.getWorldMatrix();
  84506. }
  84507. this._skeleton.computeAbsoluteTransforms();
  84508. var tmat = Bone._tmpMats[0];
  84509. tmat.copyFrom(this.getAbsoluteTransform());
  84510. if (mesh && wm) {
  84511. tmat.multiplyToRef(wm, tmat);
  84512. }
  84513. tmat.invert();
  84514. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  84515. };
  84516. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84517. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  84518. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  84519. return Bone;
  84520. }(BABYLON.Node));
  84521. BABYLON.Bone = Bone;
  84522. })(BABYLON || (BABYLON = {}));
  84523. //# sourceMappingURL=babylon.bone.js.map
  84524. var BABYLON;
  84525. (function (BABYLON) {
  84526. /**
  84527. * Class used to apply inverse kinematics to bones
  84528. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  84529. */
  84530. var BoneIKController = /** @class */ (function () {
  84531. /**
  84532. * Creates a new BoneIKController
  84533. * @param mesh defines the mesh to control
  84534. * @param bone defines the bone to control
  84535. * @param options defines options to set up the controller
  84536. */
  84537. function BoneIKController(mesh, bone, options) {
  84538. /**
  84539. * Gets or sets the target position
  84540. */
  84541. this.targetPosition = BABYLON.Vector3.Zero();
  84542. /**
  84543. * Gets or sets the pole target position
  84544. */
  84545. this.poleTargetPosition = BABYLON.Vector3.Zero();
  84546. /**
  84547. * Gets or sets the pole target local offset
  84548. */
  84549. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  84550. /**
  84551. * Gets or sets the pole angle
  84552. */
  84553. this.poleAngle = 0;
  84554. /**
  84555. * 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)
  84556. */
  84557. this.slerpAmount = 1;
  84558. this._bone1Quat = BABYLON.Quaternion.Identity();
  84559. this._bone1Mat = BABYLON.Matrix.Identity();
  84560. this._bone2Ang = Math.PI;
  84561. this._maxAngle = Math.PI;
  84562. this._rightHandedSystem = false;
  84563. this._bendAxis = BABYLON.Vector3.Right();
  84564. this._slerping = false;
  84565. this._adjustRoll = 0;
  84566. this._bone2 = bone;
  84567. this._bone1 = bone.getParent();
  84568. if (!this._bone1) {
  84569. return;
  84570. }
  84571. this.mesh = mesh;
  84572. var bonePos = bone.getPosition();
  84573. if (bone.getAbsoluteTransform().determinant() > 0) {
  84574. this._rightHandedSystem = true;
  84575. this._bendAxis.x = 0;
  84576. this._bendAxis.y = 0;
  84577. this._bendAxis.z = -1;
  84578. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  84579. this._adjustRoll = Math.PI * .5;
  84580. this._bendAxis.z = 1;
  84581. }
  84582. }
  84583. if (this._bone1.length) {
  84584. var boneScale1 = this._bone1.getScale();
  84585. var boneScale2 = this._bone2.getScale();
  84586. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  84587. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  84588. }
  84589. else if (this._bone1.children[0]) {
  84590. mesh.computeWorldMatrix(true);
  84591. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  84592. var pos2 = this._bone2.getAbsolutePosition(mesh);
  84593. var pos3 = this._bone1.getAbsolutePosition(mesh);
  84594. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  84595. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  84596. }
  84597. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  84598. this.maxAngle = Math.PI;
  84599. if (options) {
  84600. if (options.targetMesh) {
  84601. this.targetMesh = options.targetMesh;
  84602. this.targetMesh.computeWorldMatrix(true);
  84603. }
  84604. if (options.poleTargetMesh) {
  84605. this.poleTargetMesh = options.poleTargetMesh;
  84606. this.poleTargetMesh.computeWorldMatrix(true);
  84607. }
  84608. else if (options.poleTargetBone) {
  84609. this.poleTargetBone = options.poleTargetBone;
  84610. }
  84611. else if (this._bone1.getParent()) {
  84612. this.poleTargetBone = this._bone1.getParent();
  84613. }
  84614. if (options.poleTargetLocalOffset) {
  84615. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  84616. }
  84617. if (options.poleAngle) {
  84618. this.poleAngle = options.poleAngle;
  84619. }
  84620. if (options.bendAxis) {
  84621. this._bendAxis.copyFrom(options.bendAxis);
  84622. }
  84623. if (options.maxAngle) {
  84624. this.maxAngle = options.maxAngle;
  84625. }
  84626. if (options.slerpAmount) {
  84627. this.slerpAmount = options.slerpAmount;
  84628. }
  84629. }
  84630. }
  84631. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  84632. /**
  84633. * Gets or sets maximum allowed angle
  84634. */
  84635. get: function () {
  84636. return this._maxAngle;
  84637. },
  84638. set: function (value) {
  84639. this._setMaxAngle(value);
  84640. },
  84641. enumerable: true,
  84642. configurable: true
  84643. });
  84644. BoneIKController.prototype._setMaxAngle = function (ang) {
  84645. if (ang < 0) {
  84646. ang = 0;
  84647. }
  84648. if (ang > Math.PI || ang == undefined) {
  84649. ang = Math.PI;
  84650. }
  84651. this._maxAngle = ang;
  84652. var a = this._bone1Length;
  84653. var b = this._bone2Length;
  84654. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  84655. };
  84656. /**
  84657. * Force the controller to update the bones
  84658. */
  84659. BoneIKController.prototype.update = function () {
  84660. var bone1 = this._bone1;
  84661. if (!bone1) {
  84662. return;
  84663. }
  84664. var target = this.targetPosition;
  84665. var poleTarget = this.poleTargetPosition;
  84666. var mat1 = BoneIKController._tmpMats[0];
  84667. var mat2 = BoneIKController._tmpMats[1];
  84668. if (this.targetMesh) {
  84669. target.copyFrom(this.targetMesh.getAbsolutePosition());
  84670. }
  84671. if (this.poleTargetBone) {
  84672. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  84673. }
  84674. else if (this.poleTargetMesh) {
  84675. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  84676. }
  84677. var bonePos = BoneIKController._tmpVecs[0];
  84678. var zaxis = BoneIKController._tmpVecs[1];
  84679. var xaxis = BoneIKController._tmpVecs[2];
  84680. var yaxis = BoneIKController._tmpVecs[3];
  84681. var upAxis = BoneIKController._tmpVecs[4];
  84682. var _tmpQuat = BoneIKController._tmpQuat;
  84683. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  84684. poleTarget.subtractToRef(bonePos, upAxis);
  84685. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  84686. upAxis.y = 1;
  84687. }
  84688. else {
  84689. upAxis.normalize();
  84690. }
  84691. target.subtractToRef(bonePos, yaxis);
  84692. yaxis.normalize();
  84693. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  84694. zaxis.normalize();
  84695. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  84696. xaxis.normalize();
  84697. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  84698. var a = this._bone1Length;
  84699. var b = this._bone2Length;
  84700. var c = BABYLON.Vector3.Distance(bonePos, target);
  84701. if (this._maxReach > 0) {
  84702. c = Math.min(this._maxReach, c);
  84703. }
  84704. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  84705. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  84706. if (acosa > 1) {
  84707. acosa = 1;
  84708. }
  84709. if (acosb > 1) {
  84710. acosb = 1;
  84711. }
  84712. if (acosa < -1) {
  84713. acosa = -1;
  84714. }
  84715. if (acosb < -1) {
  84716. acosb = -1;
  84717. }
  84718. var angA = Math.acos(acosa);
  84719. var angB = Math.acos(acosb);
  84720. var angC = -angA - angB;
  84721. if (this._rightHandedSystem) {
  84722. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  84723. mat2.multiplyToRef(mat1, mat1);
  84724. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  84725. mat2.multiplyToRef(mat1, mat1);
  84726. }
  84727. else {
  84728. var _tmpVec = BoneIKController._tmpVecs[5];
  84729. _tmpVec.copyFrom(this._bendAxis);
  84730. _tmpVec.x *= -1;
  84731. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  84732. mat2.multiplyToRef(mat1, mat1);
  84733. }
  84734. if (this.poleAngle) {
  84735. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  84736. mat1.multiplyToRef(mat2, mat1);
  84737. }
  84738. if (this._bone1) {
  84739. if (this.slerpAmount < 1) {
  84740. if (!this._slerping) {
  84741. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  84742. }
  84743. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  84744. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  84745. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  84746. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  84747. this._slerping = true;
  84748. }
  84749. else {
  84750. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  84751. this._bone1Mat.copyFrom(mat1);
  84752. this._slerping = false;
  84753. }
  84754. }
  84755. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  84756. this._bone2Ang = angC;
  84757. };
  84758. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84759. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  84760. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  84761. return BoneIKController;
  84762. }());
  84763. BABYLON.BoneIKController = BoneIKController;
  84764. })(BABYLON || (BABYLON = {}));
  84765. //# sourceMappingURL=babylon.boneIKController.js.map
  84766. var BABYLON;
  84767. (function (BABYLON) {
  84768. /**
  84769. * Class used to make a bone look toward a point in space
  84770. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  84771. */
  84772. var BoneLookController = /** @class */ (function () {
  84773. /**
  84774. * Create a BoneLookController
  84775. * @param mesh the mesh that the bone belongs to
  84776. * @param bone the bone that will be looking to the target
  84777. * @param target the target Vector3 to look at
  84778. * @param settings optional settings:
  84779. * * maxYaw: the maximum angle the bone will yaw to
  84780. * * minYaw: the minimum angle the bone will yaw to
  84781. * * maxPitch: the maximum angle the bone will pitch to
  84782. * * minPitch: the minimum angle the bone will yaw to
  84783. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  84784. * * upAxis: the up axis of the coordinate system
  84785. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  84786. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  84787. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  84788. * * adjustYaw: used to make an adjustment to the yaw of the bone
  84789. * * adjustPitch: used to make an adjustment to the pitch of the bone
  84790. * * adjustRoll: used to make an adjustment to the roll of the bone
  84791. **/
  84792. function BoneLookController(mesh, bone, target, options) {
  84793. /**
  84794. * The up axis of the coordinate system that is used when the bone is rotated
  84795. */
  84796. this.upAxis = BABYLON.Vector3.Up();
  84797. /**
  84798. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  84799. */
  84800. this.upAxisSpace = BABYLON.Space.LOCAL;
  84801. /**
  84802. * Used to make an adjustment to the yaw of the bone
  84803. */
  84804. this.adjustYaw = 0;
  84805. /**
  84806. * Used to make an adjustment to the pitch of the bone
  84807. */
  84808. this.adjustPitch = 0;
  84809. /**
  84810. * Used to make an adjustment to the roll of the bone
  84811. */
  84812. this.adjustRoll = 0;
  84813. /**
  84814. * 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)
  84815. */
  84816. this.slerpAmount = 1;
  84817. this._boneQuat = BABYLON.Quaternion.Identity();
  84818. this._slerping = false;
  84819. this._firstFrameSkipped = false;
  84820. this._fowardAxis = BABYLON.Vector3.Forward();
  84821. this.mesh = mesh;
  84822. this.bone = bone;
  84823. this.target = target;
  84824. if (options) {
  84825. if (options.adjustYaw) {
  84826. this.adjustYaw = options.adjustYaw;
  84827. }
  84828. if (options.adjustPitch) {
  84829. this.adjustPitch = options.adjustPitch;
  84830. }
  84831. if (options.adjustRoll) {
  84832. this.adjustRoll = options.adjustRoll;
  84833. }
  84834. if (options.maxYaw != null) {
  84835. this.maxYaw = options.maxYaw;
  84836. }
  84837. else {
  84838. this.maxYaw = Math.PI;
  84839. }
  84840. if (options.minYaw != null) {
  84841. this.minYaw = options.minYaw;
  84842. }
  84843. else {
  84844. this.minYaw = -Math.PI;
  84845. }
  84846. if (options.maxPitch != null) {
  84847. this.maxPitch = options.maxPitch;
  84848. }
  84849. else {
  84850. this.maxPitch = Math.PI;
  84851. }
  84852. if (options.minPitch != null) {
  84853. this.minPitch = options.minPitch;
  84854. }
  84855. else {
  84856. this.minPitch = -Math.PI;
  84857. }
  84858. if (options.slerpAmount != null) {
  84859. this.slerpAmount = options.slerpAmount;
  84860. }
  84861. if (options.upAxis != null) {
  84862. this.upAxis = options.upAxis;
  84863. }
  84864. if (options.upAxisSpace != null) {
  84865. this.upAxisSpace = options.upAxisSpace;
  84866. }
  84867. if (options.yawAxis != null || options.pitchAxis != null) {
  84868. var newYawAxis = BABYLON.Axis.Y;
  84869. var newPitchAxis = BABYLON.Axis.X;
  84870. if (options.yawAxis != null) {
  84871. newYawAxis = options.yawAxis.clone();
  84872. newYawAxis.normalize();
  84873. }
  84874. if (options.pitchAxis != null) {
  84875. newPitchAxis = options.pitchAxis.clone();
  84876. newPitchAxis.normalize();
  84877. }
  84878. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  84879. this._transformYawPitch = BABYLON.Matrix.Identity();
  84880. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  84881. this._transformYawPitchInv = this._transformYawPitch.clone();
  84882. this._transformYawPitch.invert();
  84883. }
  84884. }
  84885. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  84886. this.upAxisSpace = BABYLON.Space.LOCAL;
  84887. }
  84888. }
  84889. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  84890. /**
  84891. * Gets or sets the minimum yaw angle that the bone can look to
  84892. */
  84893. get: function () {
  84894. return this._minYaw;
  84895. },
  84896. set: function (value) {
  84897. this._minYaw = value;
  84898. this._minYawSin = Math.sin(value);
  84899. this._minYawCos = Math.cos(value);
  84900. if (this._maxYaw != null) {
  84901. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  84902. this._yawRange = this._maxYaw - this._minYaw;
  84903. }
  84904. },
  84905. enumerable: true,
  84906. configurable: true
  84907. });
  84908. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  84909. /**
  84910. * Gets or sets the maximum yaw angle that the bone can look to
  84911. */
  84912. get: function () {
  84913. return this._maxYaw;
  84914. },
  84915. set: function (value) {
  84916. this._maxYaw = value;
  84917. this._maxYawSin = Math.sin(value);
  84918. this._maxYawCos = Math.cos(value);
  84919. if (this._minYaw != null) {
  84920. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  84921. this._yawRange = this._maxYaw - this._minYaw;
  84922. }
  84923. },
  84924. enumerable: true,
  84925. configurable: true
  84926. });
  84927. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  84928. /**
  84929. * Gets or sets the minimum pitch angle that the bone can look to
  84930. */
  84931. get: function () {
  84932. return this._minPitch;
  84933. },
  84934. set: function (value) {
  84935. this._minPitch = value;
  84936. this._minPitchTan = Math.tan(value);
  84937. },
  84938. enumerable: true,
  84939. configurable: true
  84940. });
  84941. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  84942. /**
  84943. * Gets or sets the maximum pitch angle that the bone can look to
  84944. */
  84945. get: function () {
  84946. return this._maxPitch;
  84947. },
  84948. set: function (value) {
  84949. this._maxPitch = value;
  84950. this._maxPitchTan = Math.tan(value);
  84951. },
  84952. enumerable: true,
  84953. configurable: true
  84954. });
  84955. /**
  84956. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  84957. */
  84958. BoneLookController.prototype.update = function () {
  84959. //skip the first frame when slerping so that the mesh rotation is correct
  84960. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  84961. this._firstFrameSkipped = true;
  84962. return;
  84963. }
  84964. var bone = this.bone;
  84965. var bonePos = BoneLookController._tmpVecs[0];
  84966. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  84967. var target = this.target;
  84968. var _tmpMat1 = BoneLookController._tmpMats[0];
  84969. var _tmpMat2 = BoneLookController._tmpMats[1];
  84970. var mesh = this.mesh;
  84971. var parentBone = bone.getParent();
  84972. var upAxis = BoneLookController._tmpVecs[1];
  84973. upAxis.copyFrom(this.upAxis);
  84974. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  84975. if (this._transformYawPitch) {
  84976. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  84977. }
  84978. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  84979. }
  84980. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  84981. mesh.getDirectionToRef(upAxis, upAxis);
  84982. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  84983. upAxis.normalize();
  84984. }
  84985. }
  84986. var checkYaw = false;
  84987. var checkPitch = false;
  84988. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  84989. checkYaw = true;
  84990. }
  84991. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  84992. checkPitch = true;
  84993. }
  84994. if (checkYaw || checkPitch) {
  84995. var spaceMat = BoneLookController._tmpMats[2];
  84996. var spaceMatInv = BoneLookController._tmpMats[3];
  84997. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  84998. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  84999. }
  85000. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  85001. spaceMat.copyFrom(mesh.getWorldMatrix());
  85002. }
  85003. else {
  85004. var forwardAxis = BoneLookController._tmpVecs[2];
  85005. forwardAxis.copyFrom(this._fowardAxis);
  85006. if (this._transformYawPitch) {
  85007. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  85008. }
  85009. if (parentBone) {
  85010. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  85011. }
  85012. else {
  85013. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  85014. }
  85015. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  85016. rightAxis.normalize();
  85017. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  85018. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  85019. }
  85020. spaceMat.invertToRef(spaceMatInv);
  85021. var xzlen = null;
  85022. if (checkPitch) {
  85023. var localTarget = BoneLookController._tmpVecs[3];
  85024. target.subtractToRef(bonePos, localTarget);
  85025. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  85026. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85027. var pitch = Math.atan2(localTarget.y, xzlen);
  85028. var newPitch = pitch;
  85029. if (pitch > this._maxPitch) {
  85030. localTarget.y = this._maxPitchTan * xzlen;
  85031. newPitch = this._maxPitch;
  85032. }
  85033. else if (pitch < this._minPitch) {
  85034. localTarget.y = this._minPitchTan * xzlen;
  85035. newPitch = this._minPitch;
  85036. }
  85037. if (pitch != newPitch) {
  85038. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  85039. localTarget.addInPlace(bonePos);
  85040. target = localTarget;
  85041. }
  85042. }
  85043. if (checkYaw) {
  85044. var localTarget = BoneLookController._tmpVecs[4];
  85045. target.subtractToRef(bonePos, localTarget);
  85046. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  85047. var yaw = Math.atan2(localTarget.x, localTarget.z);
  85048. var newYaw = yaw;
  85049. if (yaw > this._maxYaw || yaw < this._minYaw) {
  85050. if (xzlen == null) {
  85051. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85052. }
  85053. if (this._yawRange > Math.PI) {
  85054. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  85055. localTarget.z = this._maxYawCos * xzlen;
  85056. localTarget.x = this._maxYawSin * xzlen;
  85057. newYaw = this._maxYaw;
  85058. }
  85059. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  85060. localTarget.z = this._minYawCos * xzlen;
  85061. localTarget.x = this._minYawSin * xzlen;
  85062. newYaw = this._minYaw;
  85063. }
  85064. }
  85065. else {
  85066. if (yaw > this._maxYaw) {
  85067. localTarget.z = this._maxYawCos * xzlen;
  85068. localTarget.x = this._maxYawSin * xzlen;
  85069. newYaw = this._maxYaw;
  85070. }
  85071. else if (yaw < this._minYaw) {
  85072. localTarget.z = this._minYawCos * xzlen;
  85073. localTarget.x = this._minYawSin * xzlen;
  85074. newYaw = this._minYaw;
  85075. }
  85076. }
  85077. }
  85078. if (this._slerping && this._yawRange > Math.PI) {
  85079. //are we going to be crossing into the min/max region?
  85080. var boneFwd = BoneLookController._tmpVecs[8];
  85081. boneFwd.copyFrom(BABYLON.Axis.Z);
  85082. if (this._transformYawPitch) {
  85083. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  85084. }
  85085. var boneRotMat = BoneLookController._tmpMats[4];
  85086. this._boneQuat.toRotationMatrix(boneRotMat);
  85087. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  85088. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  85089. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  85090. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  85091. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  85092. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  85093. if (angBtwTar > angBtwMidYaw) {
  85094. if (xzlen == null) {
  85095. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85096. }
  85097. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  85098. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  85099. if (angBtwMin < angBtwMax) {
  85100. newYaw = boneYaw + Math.PI * .75;
  85101. localTarget.z = Math.cos(newYaw) * xzlen;
  85102. localTarget.x = Math.sin(newYaw) * xzlen;
  85103. }
  85104. else {
  85105. newYaw = boneYaw - Math.PI * .75;
  85106. localTarget.z = Math.cos(newYaw) * xzlen;
  85107. localTarget.x = Math.sin(newYaw) * xzlen;
  85108. }
  85109. }
  85110. }
  85111. if (yaw != newYaw) {
  85112. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  85113. localTarget.addInPlace(bonePos);
  85114. target = localTarget;
  85115. }
  85116. }
  85117. }
  85118. var zaxis = BoneLookController._tmpVecs[5];
  85119. var xaxis = BoneLookController._tmpVecs[6];
  85120. var yaxis = BoneLookController._tmpVecs[7];
  85121. var _tmpQuat = BoneLookController._tmpQuat;
  85122. target.subtractToRef(bonePos, zaxis);
  85123. zaxis.normalize();
  85124. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  85125. xaxis.normalize();
  85126. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  85127. yaxis.normalize();
  85128. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  85129. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  85130. return;
  85131. }
  85132. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  85133. return;
  85134. }
  85135. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  85136. return;
  85137. }
  85138. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  85139. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  85140. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  85141. }
  85142. if (this.slerpAmount < 1) {
  85143. if (!this._slerping) {
  85144. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  85145. }
  85146. if (this._transformYawPitch) {
  85147. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  85148. }
  85149. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  85150. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  85151. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  85152. this._slerping = true;
  85153. }
  85154. else {
  85155. if (this._transformYawPitch) {
  85156. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  85157. }
  85158. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  85159. this._slerping = false;
  85160. }
  85161. };
  85162. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  85163. var angDiff = ang2 - ang1;
  85164. angDiff %= Math.PI * 2;
  85165. if (angDiff > Math.PI) {
  85166. angDiff -= Math.PI * 2;
  85167. }
  85168. else if (angDiff < -Math.PI) {
  85169. angDiff += Math.PI * 2;
  85170. }
  85171. return angDiff;
  85172. };
  85173. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  85174. ang1 %= (2 * Math.PI);
  85175. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  85176. ang2 %= (2 * Math.PI);
  85177. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  85178. var ab = 0;
  85179. if (ang1 < ang2) {
  85180. ab = ang2 - ang1;
  85181. }
  85182. else {
  85183. ab = ang1 - ang2;
  85184. }
  85185. if (ab > Math.PI) {
  85186. ab = Math.PI * 2 - ab;
  85187. }
  85188. return ab;
  85189. };
  85190. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  85191. ang %= (2 * Math.PI);
  85192. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  85193. ang1 %= (2 * Math.PI);
  85194. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  85195. ang2 %= (2 * Math.PI);
  85196. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  85197. if (ang1 < ang2) {
  85198. if (ang > ang1 && ang < ang2) {
  85199. return true;
  85200. }
  85201. }
  85202. else {
  85203. if (ang > ang2 && ang < ang1) {
  85204. return true;
  85205. }
  85206. }
  85207. return false;
  85208. };
  85209. 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()];
  85210. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  85211. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85212. return BoneLookController;
  85213. }());
  85214. BABYLON.BoneLookController = BoneLookController;
  85215. })(BABYLON || (BABYLON = {}));
  85216. //# sourceMappingURL=babylon.boneLookController.js.map
  85217. var BABYLON;
  85218. (function (BABYLON) {
  85219. /**
  85220. * Class used to handle skinning animations
  85221. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  85222. */
  85223. var Skeleton = /** @class */ (function () {
  85224. /**
  85225. * Creates a new skeleton
  85226. * @param name defines the skeleton name
  85227. * @param id defines the skeleton Id
  85228. * @param scene defines the hosting scene
  85229. */
  85230. function Skeleton(
  85231. /** defines the skeleton name */
  85232. name,
  85233. /** defines the skeleton Id */
  85234. id, scene) {
  85235. this.name = name;
  85236. this.id = id;
  85237. /**
  85238. * Gets the list of child bones
  85239. */
  85240. this.bones = new Array();
  85241. /**
  85242. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  85243. */
  85244. this.needInitialSkinMatrix = false;
  85245. this._isDirty = true;
  85246. this._meshesWithPoseMatrix = new Array();
  85247. this._identity = BABYLON.Matrix.Identity();
  85248. this._ranges = {};
  85249. this._lastAbsoluteTransformsUpdateId = -1;
  85250. /**
  85251. * Specifies if the skeleton should be serialized
  85252. */
  85253. this.doNotSerialize = false;
  85254. this._animationPropertiesOverride = null;
  85255. // Events
  85256. /**
  85257. * An observable triggered before computing the skeleton's matrices
  85258. */
  85259. this.onBeforeComputeObservable = new BABYLON.Observable();
  85260. this.bones = [];
  85261. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85262. scene.skeletons.push(this);
  85263. //make sure it will recalculate the matrix next time prepare is called.
  85264. this._isDirty = true;
  85265. }
  85266. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  85267. /**
  85268. * Gets or sets the animation properties override
  85269. */
  85270. get: function () {
  85271. if (!this._animationPropertiesOverride) {
  85272. return this._scene.animationPropertiesOverride;
  85273. }
  85274. return this._animationPropertiesOverride;
  85275. },
  85276. set: function (value) {
  85277. this._animationPropertiesOverride = value;
  85278. },
  85279. enumerable: true,
  85280. configurable: true
  85281. });
  85282. // Members
  85283. /**
  85284. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  85285. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  85286. * @returns a Float32Array containing matrices data
  85287. */
  85288. Skeleton.prototype.getTransformMatrices = function (mesh) {
  85289. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  85290. return mesh._bonesTransformMatrices;
  85291. }
  85292. if (!this._transformMatrices) {
  85293. this.prepare();
  85294. }
  85295. return this._transformMatrices;
  85296. };
  85297. /**
  85298. * Gets the current hosting scene
  85299. * @returns a scene object
  85300. */
  85301. Skeleton.prototype.getScene = function () {
  85302. return this._scene;
  85303. };
  85304. // Methods
  85305. /**
  85306. * Gets a string representing the current skeleton data
  85307. * @param fullDetails defines a boolean indicating if we want a verbose version
  85308. * @returns a string representing the current skeleton data
  85309. */
  85310. Skeleton.prototype.toString = function (fullDetails) {
  85311. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  85312. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  85313. if (fullDetails) {
  85314. ret += ", Ranges: {";
  85315. var first = true;
  85316. for (var name_1 in this._ranges) {
  85317. if (first) {
  85318. ret += ", ";
  85319. first = false;
  85320. }
  85321. ret += name_1;
  85322. }
  85323. ret += "}";
  85324. }
  85325. return ret;
  85326. };
  85327. /**
  85328. * Get bone's index searching by name
  85329. * @param name defines bone's name to search for
  85330. * @return the indice of the bone. Returns -1 if not found
  85331. */
  85332. Skeleton.prototype.getBoneIndexByName = function (name) {
  85333. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  85334. if (this.bones[boneIndex].name === name) {
  85335. return boneIndex;
  85336. }
  85337. }
  85338. return -1;
  85339. };
  85340. /**
  85341. * Creater a new animation range
  85342. * @param name defines the name of the range
  85343. * @param from defines the start key
  85344. * @param to defines the end key
  85345. */
  85346. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  85347. // check name not already in use
  85348. if (!this._ranges[name]) {
  85349. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  85350. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85351. if (this.bones[i].animations[0]) {
  85352. this.bones[i].animations[0].createRange(name, from, to);
  85353. }
  85354. }
  85355. }
  85356. };
  85357. /**
  85358. * Delete a specific animation range
  85359. * @param name defines the name of the range
  85360. * @param deleteFrames defines if frames must be removed as well
  85361. */
  85362. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  85363. if (deleteFrames === void 0) { deleteFrames = true; }
  85364. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85365. if (this.bones[i].animations[0]) {
  85366. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  85367. }
  85368. }
  85369. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  85370. };
  85371. /**
  85372. * Gets a specific animation range
  85373. * @param name defines the name of the range to look for
  85374. * @returns the requested animation range or null if not found
  85375. */
  85376. Skeleton.prototype.getAnimationRange = function (name) {
  85377. return this._ranges[name];
  85378. };
  85379. /**
  85380. * Gets the list of all animation ranges defined on this skeleton
  85381. * @returns an array
  85382. */
  85383. Skeleton.prototype.getAnimationRanges = function () {
  85384. var animationRanges = [];
  85385. var name;
  85386. var i = 0;
  85387. for (name in this._ranges) {
  85388. animationRanges[i] = this._ranges[name];
  85389. i++;
  85390. }
  85391. return animationRanges;
  85392. };
  85393. /**
  85394. * Copy animation range from a source skeleton.
  85395. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  85396. * @param source defines the source skeleton
  85397. * @param name defines the name of the range to copy
  85398. * @param rescaleAsRequired defines if rescaling must be applied if required
  85399. * @returns true if operation was successful
  85400. */
  85401. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  85402. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  85403. if (this._ranges[name] || !source.getAnimationRange(name)) {
  85404. return false;
  85405. }
  85406. var ret = true;
  85407. var frameOffset = this._getHighestAnimationFrame() + 1;
  85408. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  85409. var boneDict = {};
  85410. var sourceBones = source.bones;
  85411. var nBones;
  85412. var i;
  85413. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  85414. boneDict[sourceBones[i].name] = sourceBones[i];
  85415. }
  85416. if (this.bones.length !== sourceBones.length) {
  85417. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  85418. ret = false;
  85419. }
  85420. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  85421. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  85422. var boneName = this.bones[i].name;
  85423. var sourceBone = boneDict[boneName];
  85424. if (sourceBone) {
  85425. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  85426. }
  85427. else {
  85428. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  85429. ret = false;
  85430. }
  85431. }
  85432. // do not call createAnimationRange(), since it also is done to bones, which was already done
  85433. var range = source.getAnimationRange(name);
  85434. if (range) {
  85435. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  85436. }
  85437. return ret;
  85438. };
  85439. /**
  85440. * Forces the skeleton to go to rest pose
  85441. */
  85442. Skeleton.prototype.returnToRest = function () {
  85443. for (var index = 0; index < this.bones.length; index++) {
  85444. this.bones[index].returnToRest();
  85445. }
  85446. };
  85447. Skeleton.prototype._getHighestAnimationFrame = function () {
  85448. var ret = 0;
  85449. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85450. if (this.bones[i].animations[0]) {
  85451. var highest = this.bones[i].animations[0].getHighestFrame();
  85452. if (ret < highest) {
  85453. ret = highest;
  85454. }
  85455. }
  85456. }
  85457. return ret;
  85458. };
  85459. /**
  85460. * Begin a specific animation range
  85461. * @param name defines the name of the range to start
  85462. * @param loop defines if looping must be turned on (false by default)
  85463. * @param speedRatio defines the speed ratio to apply (1 by default)
  85464. * @param onAnimationEnd defines a callback which will be called when animation will end
  85465. * @returns a new animatable
  85466. */
  85467. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  85468. var range = this.getAnimationRange(name);
  85469. if (!range) {
  85470. return null;
  85471. }
  85472. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  85473. };
  85474. /** @hidden */
  85475. Skeleton.prototype._markAsDirty = function () {
  85476. this._isDirty = true;
  85477. };
  85478. /** @hidden */
  85479. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  85480. this._meshesWithPoseMatrix.push(mesh);
  85481. };
  85482. /** @hidden */
  85483. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  85484. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  85485. if (index > -1) {
  85486. this._meshesWithPoseMatrix.splice(index, 1);
  85487. }
  85488. };
  85489. /** @hidden */
  85490. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  85491. this.onBeforeComputeObservable.notifyObservers(this);
  85492. for (var index = 0; index < this.bones.length; index++) {
  85493. var bone = this.bones[index];
  85494. var parentBone = bone.getParent();
  85495. if (parentBone) {
  85496. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  85497. }
  85498. else {
  85499. if (initialSkinMatrix) {
  85500. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  85501. }
  85502. else {
  85503. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  85504. }
  85505. }
  85506. if (bone._index !== -1) {
  85507. var mappedIndex = bone._index === null ? index : bone._index;
  85508. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  85509. }
  85510. }
  85511. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  85512. };
  85513. /**
  85514. * Build all resources required to render a skeleton
  85515. */
  85516. Skeleton.prototype.prepare = function () {
  85517. if (!this._isDirty) {
  85518. return;
  85519. }
  85520. if (this.needInitialSkinMatrix) {
  85521. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  85522. var mesh = this._meshesWithPoseMatrix[index];
  85523. var poseMatrix = mesh.getPoseMatrix();
  85524. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  85525. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  85526. }
  85527. if (this._synchronizedWithMesh !== mesh) {
  85528. this._synchronizedWithMesh = mesh;
  85529. // Prepare bones
  85530. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  85531. var bone = this.bones[boneIndex];
  85532. if (!bone.getParent()) {
  85533. var matrix = bone.getBaseMatrix();
  85534. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  85535. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  85536. }
  85537. }
  85538. }
  85539. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  85540. }
  85541. }
  85542. else {
  85543. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  85544. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  85545. }
  85546. this._computeTransformMatrices(this._transformMatrices, null);
  85547. }
  85548. this._isDirty = false;
  85549. this._scene._activeBones.addCount(this.bones.length, false);
  85550. };
  85551. /**
  85552. * Gets the list of animatables currently running for this skeleton
  85553. * @returns an array of animatables
  85554. */
  85555. Skeleton.prototype.getAnimatables = function () {
  85556. if (!this._animatables || this._animatables.length !== this.bones.length) {
  85557. this._animatables = [];
  85558. for (var index = 0; index < this.bones.length; index++) {
  85559. this._animatables.push(this.bones[index]);
  85560. }
  85561. }
  85562. return this._animatables;
  85563. };
  85564. /**
  85565. * Clone the current skeleton
  85566. * @param name defines the name of the new skeleton
  85567. * @param id defines the id of the enw skeleton
  85568. * @returns the new skeleton
  85569. */
  85570. Skeleton.prototype.clone = function (name, id) {
  85571. var result = new Skeleton(name, id || name, this._scene);
  85572. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  85573. for (var index = 0; index < this.bones.length; index++) {
  85574. var source = this.bones[index];
  85575. var parentBone = null;
  85576. var parent_1 = source.getParent();
  85577. if (parent_1) {
  85578. var parentIndex = this.bones.indexOf(parent_1);
  85579. parentBone = result.bones[parentIndex];
  85580. }
  85581. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  85582. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  85583. }
  85584. if (this._ranges) {
  85585. result._ranges = {};
  85586. for (var rangeName in this._ranges) {
  85587. var range = this._ranges[rangeName];
  85588. if (range) {
  85589. result._ranges[rangeName] = range.clone();
  85590. }
  85591. }
  85592. }
  85593. this._isDirty = true;
  85594. return result;
  85595. };
  85596. /**
  85597. * Enable animation blending for this skeleton
  85598. * @param blendingSpeed defines the blending speed to apply
  85599. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  85600. */
  85601. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  85602. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  85603. this.bones.forEach(function (bone) {
  85604. bone.animations.forEach(function (animation) {
  85605. animation.enableBlending = true;
  85606. animation.blendingSpeed = blendingSpeed;
  85607. });
  85608. });
  85609. };
  85610. /**
  85611. * Releases all resources associated with the current skeleton
  85612. */
  85613. Skeleton.prototype.dispose = function () {
  85614. this._meshesWithPoseMatrix = [];
  85615. // Animations
  85616. this.getScene().stopAnimation(this);
  85617. // Remove from scene
  85618. this.getScene().removeSkeleton(this);
  85619. };
  85620. /**
  85621. * Serialize the skeleton in a JSON object
  85622. * @returns a JSON object
  85623. */
  85624. Skeleton.prototype.serialize = function () {
  85625. var serializationObject = {};
  85626. serializationObject.name = this.name;
  85627. serializationObject.id = this.id;
  85628. if (this.dimensionsAtRest) {
  85629. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  85630. }
  85631. serializationObject.bones = [];
  85632. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  85633. for (var index = 0; index < this.bones.length; index++) {
  85634. var bone = this.bones[index];
  85635. var parent_2 = bone.getParent();
  85636. var serializedBone = {
  85637. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  85638. name: bone.name,
  85639. matrix: bone.getBaseMatrix().toArray(),
  85640. rest: bone.getRestPose().toArray()
  85641. };
  85642. serializationObject.bones.push(serializedBone);
  85643. if (bone.length) {
  85644. serializedBone.length = bone.length;
  85645. }
  85646. if (bone.metadata) {
  85647. serializedBone.metadata = bone.metadata;
  85648. }
  85649. if (bone.animations && bone.animations.length > 0) {
  85650. serializedBone.animation = bone.animations[0].serialize();
  85651. }
  85652. serializationObject.ranges = [];
  85653. for (var name in this._ranges) {
  85654. var source = this._ranges[name];
  85655. if (!source) {
  85656. continue;
  85657. }
  85658. var range = {};
  85659. range.name = name;
  85660. range.from = source.from;
  85661. range.to = source.to;
  85662. serializationObject.ranges.push(range);
  85663. }
  85664. }
  85665. return serializationObject;
  85666. };
  85667. /**
  85668. * Creates a new skeleton from serialized data
  85669. * @param parsedSkeleton defines the serialized data
  85670. * @param scene defines the hosting scene
  85671. * @returns a new skeleton
  85672. */
  85673. Skeleton.Parse = function (parsedSkeleton, scene) {
  85674. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  85675. if (parsedSkeleton.dimensionsAtRest) {
  85676. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  85677. }
  85678. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  85679. var index;
  85680. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  85681. var parsedBone = parsedSkeleton.bones[index];
  85682. var parentBone = null;
  85683. if (parsedBone.parentBoneIndex > -1) {
  85684. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  85685. }
  85686. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  85687. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  85688. if (parsedBone.length) {
  85689. bone.length = parsedBone.length;
  85690. }
  85691. if (parsedBone.metadata) {
  85692. bone.metadata = parsedBone.metadata;
  85693. }
  85694. if (parsedBone.animation) {
  85695. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  85696. }
  85697. }
  85698. // placed after bones, so createAnimationRange can cascade down
  85699. if (parsedSkeleton.ranges) {
  85700. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  85701. var data = parsedSkeleton.ranges[index];
  85702. skeleton.createAnimationRange(data.name, data.from, data.to);
  85703. }
  85704. }
  85705. return skeleton;
  85706. };
  85707. /**
  85708. * Compute all node absolute transforms
  85709. * @param forceUpdate defines if computation must be done even if cache is up to date
  85710. */
  85711. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  85712. if (forceUpdate === void 0) { forceUpdate = false; }
  85713. var renderId = this._scene.getRenderId();
  85714. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  85715. this.bones[0].computeAbsoluteTransforms();
  85716. this._lastAbsoluteTransformsUpdateId = renderId;
  85717. }
  85718. };
  85719. /**
  85720. * Gets the root pose matrix
  85721. * @returns a matrix
  85722. */
  85723. Skeleton.prototype.getPoseMatrix = function () {
  85724. var poseMatrix = null;
  85725. if (this._meshesWithPoseMatrix.length > 0) {
  85726. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  85727. }
  85728. return poseMatrix;
  85729. };
  85730. /**
  85731. * Sorts bones per internal index
  85732. */
  85733. Skeleton.prototype.sortBones = function () {
  85734. var bones = new Array();
  85735. var visited = new Array(this.bones.length);
  85736. for (var index = 0; index < this.bones.length; index++) {
  85737. this._sortBones(index, bones, visited);
  85738. }
  85739. this.bones = bones;
  85740. };
  85741. Skeleton.prototype._sortBones = function (index, bones, visited) {
  85742. if (visited[index]) {
  85743. return;
  85744. }
  85745. visited[index] = true;
  85746. var bone = this.bones[index];
  85747. if (bone._index === undefined) {
  85748. bone._index = index;
  85749. }
  85750. var parentBone = bone.getParent();
  85751. if (parentBone) {
  85752. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  85753. }
  85754. bones.push(bone);
  85755. };
  85756. return Skeleton;
  85757. }());
  85758. BABYLON.Skeleton = Skeleton;
  85759. })(BABYLON || (BABYLON = {}));
  85760. //# sourceMappingURL=babylon.skeleton.js.map
  85761. var BABYLON;
  85762. (function (BABYLON) {
  85763. ;
  85764. /**
  85765. * This groups tools to convert HDR texture to native colors array.
  85766. */
  85767. var HDRTools = /** @class */ (function () {
  85768. function HDRTools() {
  85769. }
  85770. HDRTools.Ldexp = function (mantissa, exponent) {
  85771. if (exponent > 1023) {
  85772. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  85773. }
  85774. if (exponent < -1074) {
  85775. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  85776. }
  85777. return mantissa * Math.pow(2, exponent);
  85778. };
  85779. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  85780. if (exponent > 0) { /*nonzero pixel*/
  85781. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  85782. float32array[index + 0] = red * exponent;
  85783. float32array[index + 1] = green * exponent;
  85784. float32array[index + 2] = blue * exponent;
  85785. }
  85786. else {
  85787. float32array[index + 0] = 0;
  85788. float32array[index + 1] = 0;
  85789. float32array[index + 2] = 0;
  85790. }
  85791. };
  85792. HDRTools.readStringLine = function (uint8array, startIndex) {
  85793. var line = "";
  85794. var character = "";
  85795. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  85796. character = String.fromCharCode(uint8array[i]);
  85797. if (character == "\n") {
  85798. break;
  85799. }
  85800. line += character;
  85801. }
  85802. return line;
  85803. };
  85804. /**
  85805. * Reads header information from an RGBE texture stored in a native array.
  85806. * More information on this format are available here:
  85807. * https://en.wikipedia.org/wiki/RGBE_image_format
  85808. *
  85809. * @param uint8array The binary file stored in native array.
  85810. * @return The header information.
  85811. */
  85812. HDRTools.RGBE_ReadHeader = function (uint8array) {
  85813. var height = 0;
  85814. var width = 0;
  85815. var line = this.readStringLine(uint8array, 0);
  85816. if (line[0] != '#' || line[1] != '?') {
  85817. throw "Bad HDR Format.";
  85818. }
  85819. var endOfHeader = false;
  85820. var findFormat = false;
  85821. var lineIndex = 0;
  85822. do {
  85823. lineIndex += (line.length + 1);
  85824. line = this.readStringLine(uint8array, lineIndex);
  85825. if (line == "FORMAT=32-bit_rle_rgbe") {
  85826. findFormat = true;
  85827. }
  85828. else if (line.length == 0) {
  85829. endOfHeader = true;
  85830. }
  85831. } while (!endOfHeader);
  85832. if (!findFormat) {
  85833. throw "HDR Bad header format, unsupported FORMAT";
  85834. }
  85835. lineIndex += (line.length + 1);
  85836. line = this.readStringLine(uint8array, lineIndex);
  85837. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  85838. var match = sizeRegexp.exec(line);
  85839. // TODO. Support +Y and -X if needed.
  85840. if (!match || match.length < 3) {
  85841. throw "HDR Bad header format, no size";
  85842. }
  85843. width = parseInt(match[2]);
  85844. height = parseInt(match[1]);
  85845. if (width < 8 || width > 0x7fff) {
  85846. throw "HDR Bad header format, unsupported size";
  85847. }
  85848. lineIndex += (line.length + 1);
  85849. return {
  85850. height: height,
  85851. width: width,
  85852. dataPosition: lineIndex
  85853. };
  85854. };
  85855. /**
  85856. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  85857. * This RGBE texture needs to store the information as a panorama.
  85858. *
  85859. * More information on this format are available here:
  85860. * https://en.wikipedia.org/wiki/RGBE_image_format
  85861. *
  85862. * @param buffer The binary file stored in an array buffer.
  85863. * @param size The expected size of the extracted cubemap.
  85864. * @return The Cube Map information.
  85865. */
  85866. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  85867. var uint8array = new Uint8Array(buffer);
  85868. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  85869. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  85870. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  85871. return cubeMapData;
  85872. };
  85873. /**
  85874. * Returns the pixels data extracted from an RGBE texture.
  85875. * This pixels will be stored left to right up to down in the R G B order in one array.
  85876. *
  85877. * More information on this format are available here:
  85878. * https://en.wikipedia.org/wiki/RGBE_image_format
  85879. *
  85880. * @param uint8array The binary file stored in an array buffer.
  85881. * @param hdrInfo The header information of the file.
  85882. * @return The pixels data in RGB right to left up to down order.
  85883. */
  85884. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  85885. // Keep for multi format supports.
  85886. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  85887. };
  85888. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  85889. var num_scanlines = hdrInfo.height;
  85890. var scanline_width = hdrInfo.width;
  85891. var a, b, c, d, count;
  85892. var dataIndex = hdrInfo.dataPosition;
  85893. var index = 0, endIndex = 0, i = 0;
  85894. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  85895. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  85896. // 3 channels of 4 bytes per pixel in float.
  85897. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  85898. var resultArray = new Float32Array(resultBuffer);
  85899. // read in each successive scanline
  85900. while (num_scanlines > 0) {
  85901. a = uint8array[dataIndex++];
  85902. b = uint8array[dataIndex++];
  85903. c = uint8array[dataIndex++];
  85904. d = uint8array[dataIndex++];
  85905. if (a != 2 || b != 2 || (c & 0x80)) {
  85906. // this file is not run length encoded
  85907. throw "HDR Bad header format, not RLE";
  85908. }
  85909. if (((c << 8) | d) != scanline_width) {
  85910. throw "HDR Bad header format, wrong scan line width";
  85911. }
  85912. index = 0;
  85913. // read each of the four channels for the scanline into the buffer
  85914. for (i = 0; i < 4; i++) {
  85915. endIndex = (i + 1) * scanline_width;
  85916. while (index < endIndex) {
  85917. a = uint8array[dataIndex++];
  85918. b = uint8array[dataIndex++];
  85919. if (a > 128) {
  85920. // a run of the same value
  85921. count = a - 128;
  85922. if ((count == 0) || (count > endIndex - index)) {
  85923. throw "HDR Bad Format, bad scanline data (run)";
  85924. }
  85925. while (count-- > 0) {
  85926. scanLineArray[index++] = b;
  85927. }
  85928. }
  85929. else {
  85930. // a non-run
  85931. count = a;
  85932. if ((count == 0) || (count > endIndex - index)) {
  85933. throw "HDR Bad Format, bad scanline data (non-run)";
  85934. }
  85935. scanLineArray[index++] = b;
  85936. if (--count > 0) {
  85937. for (var j = 0; j < count; j++) {
  85938. scanLineArray[index++] = uint8array[dataIndex++];
  85939. }
  85940. }
  85941. }
  85942. }
  85943. }
  85944. // now convert data from buffer into floats
  85945. for (i = 0; i < scanline_width; i++) {
  85946. a = scanLineArray[i];
  85947. b = scanLineArray[i + scanline_width];
  85948. c = scanLineArray[i + 2 * scanline_width];
  85949. d = scanLineArray[i + 3 * scanline_width];
  85950. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  85951. }
  85952. num_scanlines--;
  85953. }
  85954. return resultArray;
  85955. };
  85956. return HDRTools;
  85957. }());
  85958. BABYLON.HDRTools = HDRTools;
  85959. })(BABYLON || (BABYLON = {}));
  85960. //# sourceMappingURL=babylon.hdr.js.map
  85961. var BABYLON;
  85962. (function (BABYLON) {
  85963. /**
  85964. * This represents a texture coming from an HDR input.
  85965. *
  85966. * The only supported format is currently panorama picture stored in RGBE format.
  85967. * Example of such files can be found on HDRLib: http://hdrlib.com/
  85968. */
  85969. var HDRCubeTexture = /** @class */ (function (_super) {
  85970. __extends(HDRCubeTexture, _super);
  85971. /**
  85972. * Instantiates an HDRTexture from the following parameters.
  85973. *
  85974. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  85975. * @param scene The scene the texture will be used in
  85976. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  85977. * @param noMipmap Forces to not generate the mipmap if true
  85978. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  85979. * @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)
  85980. * @param reserved Reserved flag for internal use.
  85981. */
  85982. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  85983. if (noMipmap === void 0) { noMipmap = false; }
  85984. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85985. if (gammaSpace === void 0) { gammaSpace = false; }
  85986. if (reserved === void 0) { reserved = false; }
  85987. if (onLoad === void 0) { onLoad = null; }
  85988. if (onError === void 0) { onError = null; }
  85989. var _this = _super.call(this, scene) || this;
  85990. _this._generateHarmonics = true;
  85991. _this._onLoad = null;
  85992. _this._onError = null;
  85993. /**
  85994. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  85995. */
  85996. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  85997. _this._isBlocking = true;
  85998. _this._rotationY = 0;
  85999. /**
  86000. * Gets or sets the center of the bounding box associated with the cube texture
  86001. * It must define where the camera used to render the texture was set
  86002. */
  86003. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  86004. if (!url) {
  86005. return _this;
  86006. }
  86007. _this.name = url;
  86008. _this.url = url;
  86009. _this.hasAlpha = false;
  86010. _this.isCube = true;
  86011. _this._textureMatrix = BABYLON.Matrix.Identity();
  86012. _this._onLoad = onLoad;
  86013. _this._onError = onError;
  86014. _this.gammaSpace = gammaSpace;
  86015. _this._noMipmap = noMipmap;
  86016. _this._size = size;
  86017. _this._texture = _this._getFromCache(url, _this._noMipmap);
  86018. if (!_this._texture) {
  86019. if (!scene.useDelayedTextureLoading) {
  86020. _this.loadTexture();
  86021. }
  86022. else {
  86023. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  86024. }
  86025. }
  86026. return _this;
  86027. }
  86028. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  86029. /**
  86030. * Gets wether or not the texture is blocking during loading.
  86031. */
  86032. get: function () {
  86033. return this._isBlocking;
  86034. },
  86035. /**
  86036. * Sets wether or not the texture is blocking during loading.
  86037. */
  86038. set: function (value) {
  86039. this._isBlocking = value;
  86040. },
  86041. enumerable: true,
  86042. configurable: true
  86043. });
  86044. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  86045. /**
  86046. * Gets texture matrix rotation angle around Y axis radians.
  86047. */
  86048. get: function () {
  86049. return this._rotationY;
  86050. },
  86051. /**
  86052. * Sets texture matrix rotation angle around Y axis in radians.
  86053. */
  86054. set: function (value) {
  86055. this._rotationY = value;
  86056. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  86057. },
  86058. enumerable: true,
  86059. configurable: true
  86060. });
  86061. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  86062. get: function () {
  86063. return this._boundingBoxSize;
  86064. },
  86065. /**
  86066. * Gets or sets the size of the bounding box associated with the cube texture
  86067. * When defined, the cubemap will switch to local mode
  86068. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  86069. * @example https://www.babylonjs-playground.com/#RNASML
  86070. */
  86071. set: function (value) {
  86072. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  86073. return;
  86074. }
  86075. this._boundingBoxSize = value;
  86076. var scene = this.getScene();
  86077. if (scene) {
  86078. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  86079. }
  86080. },
  86081. enumerable: true,
  86082. configurable: true
  86083. });
  86084. /**
  86085. * Occurs when the file is raw .hdr file.
  86086. */
  86087. HDRCubeTexture.prototype.loadTexture = function () {
  86088. var _this = this;
  86089. var callback = function (buffer) {
  86090. _this.lodGenerationOffset = 0.0;
  86091. _this.lodGenerationScale = 0.8;
  86092. var scene = _this.getScene();
  86093. if (!scene) {
  86094. return null;
  86095. }
  86096. // Extract the raw linear data.
  86097. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  86098. // Generate harmonics if needed.
  86099. if (_this._generateHarmonics) {
  86100. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  86101. _this.sphericalPolynomial = sphericalPolynomial;
  86102. }
  86103. var results = [];
  86104. var byteArray = null;
  86105. // Push each faces.
  86106. for (var j = 0; j < 6; j++) {
  86107. // Create uintarray fallback.
  86108. if (!scene.getEngine().getCaps().textureFloat) {
  86109. // 3 channels of 1 bytes per pixel in bytes.
  86110. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  86111. byteArray = new Uint8Array(byteBuffer);
  86112. }
  86113. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  86114. // If special cases.
  86115. if (_this.gammaSpace || byteArray) {
  86116. for (var i = 0; i < _this._size * _this._size; i++) {
  86117. // Put in gamma space if requested.
  86118. if (_this.gammaSpace) {
  86119. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  86120. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  86121. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  86122. }
  86123. // Convert to int texture for fallback.
  86124. if (byteArray) {
  86125. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  86126. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  86127. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  86128. // May use luminance instead if the result is not accurate.
  86129. var max = Math.max(Math.max(r, g), b);
  86130. if (max > 255) {
  86131. var scale = 255 / max;
  86132. r *= scale;
  86133. g *= scale;
  86134. b *= scale;
  86135. }
  86136. byteArray[(i * 3) + 0] = r;
  86137. byteArray[(i * 3) + 1] = g;
  86138. byteArray[(i * 3) + 2] = b;
  86139. }
  86140. }
  86141. }
  86142. if (byteArray) {
  86143. results.push(byteArray);
  86144. }
  86145. else {
  86146. results.push(dataFace);
  86147. }
  86148. }
  86149. return results;
  86150. };
  86151. var scene = this.getScene();
  86152. if (scene) {
  86153. 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);
  86154. }
  86155. };
  86156. HDRCubeTexture.prototype.clone = function () {
  86157. var scene = this.getScene();
  86158. if (!scene) {
  86159. return this;
  86160. }
  86161. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  86162. // Base texture
  86163. newTexture.level = this.level;
  86164. newTexture.wrapU = this.wrapU;
  86165. newTexture.wrapV = this.wrapV;
  86166. newTexture.coordinatesIndex = this.coordinatesIndex;
  86167. newTexture.coordinatesMode = this.coordinatesMode;
  86168. return newTexture;
  86169. };
  86170. // Methods
  86171. HDRCubeTexture.prototype.delayLoad = function () {
  86172. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  86173. return;
  86174. }
  86175. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  86176. this._texture = this._getFromCache(this.url, this._noMipmap);
  86177. if (!this._texture) {
  86178. this.loadTexture();
  86179. }
  86180. };
  86181. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  86182. return this._textureMatrix;
  86183. };
  86184. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  86185. this._textureMatrix = value;
  86186. };
  86187. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  86188. var texture = null;
  86189. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  86190. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  86191. texture.name = parsedTexture.name;
  86192. texture.hasAlpha = parsedTexture.hasAlpha;
  86193. texture.level = parsedTexture.level;
  86194. texture.coordinatesMode = parsedTexture.coordinatesMode;
  86195. texture.isBlocking = parsedTexture.isBlocking;
  86196. }
  86197. if (texture) {
  86198. if (parsedTexture.boundingBoxPosition) {
  86199. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  86200. }
  86201. if (parsedTexture.boundingBoxSize) {
  86202. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  86203. }
  86204. if (parsedTexture.rotationY) {
  86205. texture.rotationY = parsedTexture.rotationY;
  86206. }
  86207. }
  86208. return texture;
  86209. };
  86210. HDRCubeTexture.prototype.serialize = function () {
  86211. if (!this.name) {
  86212. return null;
  86213. }
  86214. var serializationObject = {};
  86215. serializationObject.name = this.name;
  86216. serializationObject.hasAlpha = this.hasAlpha;
  86217. serializationObject.isCube = true;
  86218. serializationObject.level = this.level;
  86219. serializationObject.size = this._size;
  86220. serializationObject.coordinatesMode = this.coordinatesMode;
  86221. serializationObject.useInGammaSpace = this.gammaSpace;
  86222. serializationObject.generateHarmonics = this._generateHarmonics;
  86223. serializationObject.customType = "BABYLON.HDRCubeTexture";
  86224. serializationObject.noMipmap = this._noMipmap;
  86225. serializationObject.isBlocking = this._isBlocking;
  86226. serializationObject.rotationY = this._rotationY;
  86227. return serializationObject;
  86228. };
  86229. HDRCubeTexture._facesMapping = [
  86230. "right",
  86231. "left",
  86232. "up",
  86233. "down",
  86234. "front",
  86235. "back"
  86236. ];
  86237. return HDRCubeTexture;
  86238. }(BABYLON.BaseTexture));
  86239. BABYLON.HDRCubeTexture = HDRCubeTexture;
  86240. })(BABYLON || (BABYLON = {}));
  86241. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  86242. var BABYLON;
  86243. (function (BABYLON) {
  86244. /**
  86245. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  86246. */
  86247. var PanoramaToCubeMapTools = /** @class */ (function () {
  86248. function PanoramaToCubeMapTools() {
  86249. }
  86250. /**
  86251. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  86252. *
  86253. * @param float32Array The source data.
  86254. * @param inputWidth The width of the input panorama.
  86255. * @param inputhHeight The height of the input panorama.
  86256. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  86257. * @return The cubemap data
  86258. */
  86259. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  86260. if (!float32Array) {
  86261. throw "ConvertPanoramaToCubemap: input cannot be null";
  86262. }
  86263. if (float32Array.length != inputWidth * inputHeight * 3) {
  86264. throw "ConvertPanoramaToCubemap: input size is wrong";
  86265. }
  86266. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  86267. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  86268. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  86269. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  86270. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  86271. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  86272. return {
  86273. front: textureFront,
  86274. back: textureBack,
  86275. left: textureLeft,
  86276. right: textureRight,
  86277. up: textureUp,
  86278. down: textureDown,
  86279. size: size,
  86280. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86281. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  86282. gammaSpace: false,
  86283. };
  86284. };
  86285. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  86286. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  86287. var textureArray = new Float32Array(buffer);
  86288. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  86289. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  86290. var dy = 1 / texSize;
  86291. var fy = 0;
  86292. for (var y = 0; y < texSize; y++) {
  86293. var xv1 = faceData[0];
  86294. var xv2 = faceData[2];
  86295. for (var x = 0; x < texSize; x++) {
  86296. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  86297. v.normalize();
  86298. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  86299. // 3 channels per pixels
  86300. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  86301. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  86302. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  86303. xv1 = xv1.add(rotDX1);
  86304. xv2 = xv2.add(rotDX2);
  86305. }
  86306. fy += dy;
  86307. }
  86308. return textureArray;
  86309. };
  86310. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  86311. var theta = Math.atan2(vDir.z, vDir.x);
  86312. var phi = Math.acos(vDir.y);
  86313. while (theta < -Math.PI)
  86314. theta += 2 * Math.PI;
  86315. while (theta > Math.PI)
  86316. theta -= 2 * Math.PI;
  86317. var dx = theta / Math.PI;
  86318. var dy = phi / Math.PI;
  86319. // recenter.
  86320. dx = dx * 0.5 + 0.5;
  86321. var px = Math.round(dx * inputWidth);
  86322. if (px < 0)
  86323. px = 0;
  86324. else if (px >= inputWidth)
  86325. px = inputWidth - 1;
  86326. var py = Math.round(dy * inputHeight);
  86327. if (py < 0)
  86328. py = 0;
  86329. else if (py >= inputHeight)
  86330. py = inputHeight - 1;
  86331. var inputY = (inputHeight - py - 1);
  86332. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  86333. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  86334. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  86335. return {
  86336. r: r,
  86337. g: g,
  86338. b: b
  86339. };
  86340. };
  86341. PanoramaToCubeMapTools.FACE_FRONT = [
  86342. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86343. new BABYLON.Vector3(1.0, -1.0, -1.0),
  86344. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  86345. new BABYLON.Vector3(1.0, 1.0, -1.0)
  86346. ];
  86347. PanoramaToCubeMapTools.FACE_BACK = [
  86348. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86349. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86350. new BABYLON.Vector3(1.0, 1.0, 1.0),
  86351. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  86352. ];
  86353. PanoramaToCubeMapTools.FACE_RIGHT = [
  86354. new BABYLON.Vector3(1.0, -1.0, -1.0),
  86355. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86356. new BABYLON.Vector3(1.0, 1.0, -1.0),
  86357. new BABYLON.Vector3(1.0, 1.0, 1.0)
  86358. ];
  86359. PanoramaToCubeMapTools.FACE_LEFT = [
  86360. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86361. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86362. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  86363. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  86364. ];
  86365. PanoramaToCubeMapTools.FACE_DOWN = [
  86366. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  86367. new BABYLON.Vector3(1.0, 1.0, -1.0),
  86368. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  86369. new BABYLON.Vector3(1.0, 1.0, 1.0)
  86370. ];
  86371. PanoramaToCubeMapTools.FACE_UP = [
  86372. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86373. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86374. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86375. new BABYLON.Vector3(1.0, -1.0, -1.0)
  86376. ];
  86377. return PanoramaToCubeMapTools;
  86378. }());
  86379. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  86380. })(BABYLON || (BABYLON = {}));
  86381. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  86382. var BABYLON;
  86383. (function (BABYLON) {
  86384. var IndexedVector2 = /** @class */ (function (_super) {
  86385. __extends(IndexedVector2, _super);
  86386. function IndexedVector2(original, index) {
  86387. var _this = _super.call(this, original.x, original.y) || this;
  86388. _this.index = index;
  86389. return _this;
  86390. }
  86391. return IndexedVector2;
  86392. }(BABYLON.Vector2));
  86393. var PolygonPoints = /** @class */ (function () {
  86394. function PolygonPoints() {
  86395. this.elements = new Array();
  86396. }
  86397. PolygonPoints.prototype.add = function (originalPoints) {
  86398. var _this = this;
  86399. var result = new Array();
  86400. originalPoints.forEach(function (point) {
  86401. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  86402. var newPoint = new IndexedVector2(point, _this.elements.length);
  86403. result.push(newPoint);
  86404. _this.elements.push(newPoint);
  86405. }
  86406. });
  86407. return result;
  86408. };
  86409. PolygonPoints.prototype.computeBounds = function () {
  86410. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  86411. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  86412. this.elements.forEach(function (point) {
  86413. // x
  86414. if (point.x < lmin.x) {
  86415. lmin.x = point.x;
  86416. }
  86417. else if (point.x > lmax.x) {
  86418. lmax.x = point.x;
  86419. }
  86420. // y
  86421. if (point.y < lmin.y) {
  86422. lmin.y = point.y;
  86423. }
  86424. else if (point.y > lmax.y) {
  86425. lmax.y = point.y;
  86426. }
  86427. });
  86428. return {
  86429. min: lmin,
  86430. max: lmax,
  86431. width: lmax.x - lmin.x,
  86432. height: lmax.y - lmin.y
  86433. };
  86434. };
  86435. return PolygonPoints;
  86436. }());
  86437. var Polygon = /** @class */ (function () {
  86438. function Polygon() {
  86439. }
  86440. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  86441. return [
  86442. new BABYLON.Vector2(xmin, ymin),
  86443. new BABYLON.Vector2(xmax, ymin),
  86444. new BABYLON.Vector2(xmax, ymax),
  86445. new BABYLON.Vector2(xmin, ymax)
  86446. ];
  86447. };
  86448. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  86449. if (cx === void 0) { cx = 0; }
  86450. if (cy === void 0) { cy = 0; }
  86451. if (numberOfSides === void 0) { numberOfSides = 32; }
  86452. var result = new Array();
  86453. var angle = 0;
  86454. var increment = (Math.PI * 2) / numberOfSides;
  86455. for (var i = 0; i < numberOfSides; i++) {
  86456. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  86457. angle -= increment;
  86458. }
  86459. return result;
  86460. };
  86461. Polygon.Parse = function (input) {
  86462. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  86463. var i, result = [];
  86464. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  86465. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  86466. }
  86467. return result;
  86468. };
  86469. Polygon.StartingAt = function (x, y) {
  86470. return BABYLON.Path2.StartingAt(x, y);
  86471. };
  86472. return Polygon;
  86473. }());
  86474. BABYLON.Polygon = Polygon;
  86475. var PolygonMeshBuilder = /** @class */ (function () {
  86476. function PolygonMeshBuilder(name, contours, scene) {
  86477. this._points = new PolygonPoints();
  86478. this._outlinepoints = new PolygonPoints();
  86479. this._holes = new Array();
  86480. this._epoints = new Array();
  86481. this._eholes = new Array();
  86482. this._name = name;
  86483. this._scene = scene;
  86484. var points;
  86485. if (contours instanceof BABYLON.Path2) {
  86486. points = contours.getPoints();
  86487. }
  86488. else {
  86489. points = contours;
  86490. }
  86491. this._addToepoint(points);
  86492. this._points.add(points);
  86493. this._outlinepoints.add(points);
  86494. if (typeof earcut === 'undefined') {
  86495. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  86496. }
  86497. }
  86498. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  86499. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  86500. var p = points_1[_i];
  86501. this._epoints.push(p.x, p.y);
  86502. }
  86503. };
  86504. PolygonMeshBuilder.prototype.addHole = function (hole) {
  86505. this._points.add(hole);
  86506. var holepoints = new PolygonPoints();
  86507. holepoints.add(hole);
  86508. this._holes.push(holepoints);
  86509. this._eholes.push(this._epoints.length / 2);
  86510. this._addToepoint(hole);
  86511. return this;
  86512. };
  86513. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  86514. var _this = this;
  86515. if (updatable === void 0) { updatable = false; }
  86516. if (depth === void 0) { depth = 0; }
  86517. var result = new BABYLON.Mesh(this._name, this._scene);
  86518. var normals = new Array();
  86519. var positions = new Array();
  86520. var uvs = new Array();
  86521. var bounds = this._points.computeBounds();
  86522. this._points.elements.forEach(function (p) {
  86523. normals.push(0, 1.0, 0);
  86524. positions.push(p.x, 0, p.y);
  86525. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  86526. });
  86527. var indices = new Array();
  86528. var res = earcut(this._epoints, this._eholes, 2);
  86529. for (var i = 0; i < res.length; i++) {
  86530. indices.push(res[i]);
  86531. }
  86532. if (depth > 0) {
  86533. var positionscount = (positions.length / 3); //get the current pointcount
  86534. this._points.elements.forEach(function (p) {
  86535. normals.push(0, -1.0, 0);
  86536. positions.push(p.x, -depth, p.y);
  86537. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  86538. });
  86539. var totalCount = indices.length;
  86540. for (var i = 0; i < totalCount; i += 3) {
  86541. var i0 = indices[i + 0];
  86542. var i1 = indices[i + 1];
  86543. var i2 = indices[i + 2];
  86544. indices.push(i2 + positionscount);
  86545. indices.push(i1 + positionscount);
  86546. indices.push(i0 + positionscount);
  86547. }
  86548. //Add the sides
  86549. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  86550. this._holes.forEach(function (hole) {
  86551. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  86552. });
  86553. }
  86554. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  86555. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  86556. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  86557. result.setIndices(indices);
  86558. return result;
  86559. };
  86560. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  86561. var StartIndex = positions.length / 3;
  86562. var ulength = 0;
  86563. for (var i = 0; i < points.elements.length; i++) {
  86564. var p = points.elements[i];
  86565. var p1;
  86566. if ((i + 1) > points.elements.length - 1) {
  86567. p1 = points.elements[0];
  86568. }
  86569. else {
  86570. p1 = points.elements[i + 1];
  86571. }
  86572. positions.push(p.x, 0, p.y);
  86573. positions.push(p.x, -depth, p.y);
  86574. positions.push(p1.x, 0, p1.y);
  86575. positions.push(p1.x, -depth, p1.y);
  86576. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  86577. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  86578. var v3 = v2.subtract(v1);
  86579. var v4 = new BABYLON.Vector3(0, 1, 0);
  86580. var vn = BABYLON.Vector3.Cross(v3, v4);
  86581. vn = vn.normalize();
  86582. uvs.push(ulength / bounds.width, 0);
  86583. uvs.push(ulength / bounds.width, 1);
  86584. ulength += v3.length();
  86585. uvs.push((ulength / bounds.width), 0);
  86586. uvs.push((ulength / bounds.width), 1);
  86587. if (!flip) {
  86588. normals.push(-vn.x, -vn.y, -vn.z);
  86589. normals.push(-vn.x, -vn.y, -vn.z);
  86590. normals.push(-vn.x, -vn.y, -vn.z);
  86591. normals.push(-vn.x, -vn.y, -vn.z);
  86592. indices.push(StartIndex);
  86593. indices.push(StartIndex + 1);
  86594. indices.push(StartIndex + 2);
  86595. indices.push(StartIndex + 1);
  86596. indices.push(StartIndex + 3);
  86597. indices.push(StartIndex + 2);
  86598. }
  86599. else {
  86600. normals.push(vn.x, vn.y, vn.z);
  86601. normals.push(vn.x, vn.y, vn.z);
  86602. normals.push(vn.x, vn.y, vn.z);
  86603. normals.push(vn.x, vn.y, vn.z);
  86604. indices.push(StartIndex);
  86605. indices.push(StartIndex + 2);
  86606. indices.push(StartIndex + 1);
  86607. indices.push(StartIndex + 1);
  86608. indices.push(StartIndex + 2);
  86609. indices.push(StartIndex + 3);
  86610. }
  86611. StartIndex += 4;
  86612. }
  86613. ;
  86614. };
  86615. return PolygonMeshBuilder;
  86616. }());
  86617. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  86618. })(BABYLON || (BABYLON = {}));
  86619. //# sourceMappingURL=babylon.polygonMesh.js.map
  86620. var BABYLON;
  86621. (function (BABYLON) {
  86622. // Unique ID when we import meshes from Babylon to CSG
  86623. var currentCSGMeshId = 0;
  86624. // # class Vertex
  86625. // Represents a vertex of a polygon. Use your own vertex class instead of this
  86626. // one to provide additional features like texture coordinates and vertex
  86627. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  86628. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  86629. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  86630. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  86631. // is not used anywhere else.
  86632. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  86633. var Vertex = /** @class */ (function () {
  86634. function Vertex(pos, normal, uv) {
  86635. this.pos = pos;
  86636. this.normal = normal;
  86637. this.uv = uv;
  86638. }
  86639. Vertex.prototype.clone = function () {
  86640. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  86641. };
  86642. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  86643. // orientation of a polygon is flipped.
  86644. Vertex.prototype.flip = function () {
  86645. this.normal = this.normal.scale(-1);
  86646. };
  86647. // Create a new vertex between this vertex and `other` by linearly
  86648. // interpolating all properties using a parameter of `t`. Subclasses should
  86649. // override this to interpolate additional properties.
  86650. Vertex.prototype.interpolate = function (other, t) {
  86651. 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));
  86652. };
  86653. return Vertex;
  86654. }());
  86655. // # class Plane
  86656. // Represents a plane in 3D space.
  86657. var Plane = /** @class */ (function () {
  86658. function Plane(normal, w) {
  86659. this.normal = normal;
  86660. this.w = w;
  86661. }
  86662. Plane.FromPoints = function (a, b, c) {
  86663. var v0 = c.subtract(a);
  86664. var v1 = b.subtract(a);
  86665. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  86666. return null;
  86667. }
  86668. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  86669. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  86670. };
  86671. Plane.prototype.clone = function () {
  86672. return new Plane(this.normal.clone(), this.w);
  86673. };
  86674. Plane.prototype.flip = function () {
  86675. this.normal.scaleInPlace(-1);
  86676. this.w = -this.w;
  86677. };
  86678. // Split `polygon` by this plane if needed, then put the polygon or polygon
  86679. // fragments in the appropriate lists. Coplanar polygons go into either
  86680. // `coplanarFront` or `coplanarBack` depending on their orientation with
  86681. // respect to this plane. Polygons in front or in back of this plane go into
  86682. // either `front` or `back`.
  86683. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  86684. var COPLANAR = 0;
  86685. var FRONT = 1;
  86686. var BACK = 2;
  86687. var SPANNING = 3;
  86688. // Classify each point as well as the entire polygon into one of the above
  86689. // four classes.
  86690. var polygonType = 0;
  86691. var types = [];
  86692. var i;
  86693. var t;
  86694. for (i = 0; i < polygon.vertices.length; i++) {
  86695. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  86696. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  86697. polygonType |= type;
  86698. types.push(type);
  86699. }
  86700. // Put the polygon in the correct list, splitting it when necessary.
  86701. switch (polygonType) {
  86702. case COPLANAR:
  86703. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  86704. break;
  86705. case FRONT:
  86706. front.push(polygon);
  86707. break;
  86708. case BACK:
  86709. back.push(polygon);
  86710. break;
  86711. case SPANNING:
  86712. var f = [], b = [];
  86713. for (i = 0; i < polygon.vertices.length; i++) {
  86714. var j = (i + 1) % polygon.vertices.length;
  86715. var ti = types[i], tj = types[j];
  86716. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  86717. if (ti !== BACK)
  86718. f.push(vi);
  86719. if (ti !== FRONT)
  86720. b.push(ti !== BACK ? vi.clone() : vi);
  86721. if ((ti | tj) === SPANNING) {
  86722. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  86723. var v = vi.interpolate(vj, t);
  86724. f.push(v);
  86725. b.push(v.clone());
  86726. }
  86727. }
  86728. var poly;
  86729. if (f.length >= 3) {
  86730. poly = new Polygon(f, polygon.shared);
  86731. if (poly.plane)
  86732. front.push(poly);
  86733. }
  86734. if (b.length >= 3) {
  86735. poly = new Polygon(b, polygon.shared);
  86736. if (poly.plane)
  86737. back.push(poly);
  86738. }
  86739. break;
  86740. }
  86741. };
  86742. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  86743. // point is on the plane.
  86744. Plane.EPSILON = 1e-5;
  86745. return Plane;
  86746. }());
  86747. // # class Polygon
  86748. // Represents a convex polygon. The vertices used to initialize a polygon must
  86749. // be coplanar and form a convex loop.
  86750. //
  86751. // Each convex polygon has a `shared` property, which is shared between all
  86752. // polygons that are clones of each other or were split from the same polygon.
  86753. // This can be used to define per-polygon properties (such as surface color).
  86754. var Polygon = /** @class */ (function () {
  86755. function Polygon(vertices, shared) {
  86756. this.vertices = vertices;
  86757. this.shared = shared;
  86758. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  86759. }
  86760. Polygon.prototype.clone = function () {
  86761. var vertices = this.vertices.map(function (v) { return v.clone(); });
  86762. return new Polygon(vertices, this.shared);
  86763. };
  86764. Polygon.prototype.flip = function () {
  86765. this.vertices.reverse().map(function (v) { v.flip(); });
  86766. this.plane.flip();
  86767. };
  86768. return Polygon;
  86769. }());
  86770. // # class Node
  86771. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  86772. // by picking a polygon to split along. That polygon (and all other coplanar
  86773. // polygons) are added directly to that node and the other polygons are added to
  86774. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  86775. // no distinction between internal and leaf nodes.
  86776. var Node = /** @class */ (function () {
  86777. function Node(polygons) {
  86778. this.plane = null;
  86779. this.front = null;
  86780. this.back = null;
  86781. this.polygons = new Array();
  86782. if (polygons) {
  86783. this.build(polygons);
  86784. }
  86785. }
  86786. Node.prototype.clone = function () {
  86787. var node = new Node();
  86788. node.plane = this.plane && this.plane.clone();
  86789. node.front = this.front && this.front.clone();
  86790. node.back = this.back && this.back.clone();
  86791. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  86792. return node;
  86793. };
  86794. // Convert solid space to empty space and empty space to solid space.
  86795. Node.prototype.invert = function () {
  86796. for (var i = 0; i < this.polygons.length; i++) {
  86797. this.polygons[i].flip();
  86798. }
  86799. if (this.plane) {
  86800. this.plane.flip();
  86801. }
  86802. if (this.front) {
  86803. this.front.invert();
  86804. }
  86805. if (this.back) {
  86806. this.back.invert();
  86807. }
  86808. var temp = this.front;
  86809. this.front = this.back;
  86810. this.back = temp;
  86811. };
  86812. // Recursively remove all polygons in `polygons` that are inside this BSP
  86813. // tree.
  86814. Node.prototype.clipPolygons = function (polygons) {
  86815. if (!this.plane)
  86816. return polygons.slice();
  86817. var front = new Array(), back = new Array();
  86818. for (var i = 0; i < polygons.length; i++) {
  86819. this.plane.splitPolygon(polygons[i], front, back, front, back);
  86820. }
  86821. if (this.front) {
  86822. front = this.front.clipPolygons(front);
  86823. }
  86824. if (this.back) {
  86825. back = this.back.clipPolygons(back);
  86826. }
  86827. else {
  86828. back = [];
  86829. }
  86830. return front.concat(back);
  86831. };
  86832. // Remove all polygons in this BSP tree that are inside the other BSP tree
  86833. // `bsp`.
  86834. Node.prototype.clipTo = function (bsp) {
  86835. this.polygons = bsp.clipPolygons(this.polygons);
  86836. if (this.front)
  86837. this.front.clipTo(bsp);
  86838. if (this.back)
  86839. this.back.clipTo(bsp);
  86840. };
  86841. // Return a list of all polygons in this BSP tree.
  86842. Node.prototype.allPolygons = function () {
  86843. var polygons = this.polygons.slice();
  86844. if (this.front)
  86845. polygons = polygons.concat(this.front.allPolygons());
  86846. if (this.back)
  86847. polygons = polygons.concat(this.back.allPolygons());
  86848. return polygons;
  86849. };
  86850. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  86851. // new polygons are filtered down to the bottom of the tree and become new
  86852. // nodes there. Each set of polygons is partitioned using the first polygon
  86853. // (no heuristic is used to pick a good split).
  86854. Node.prototype.build = function (polygons) {
  86855. if (!polygons.length)
  86856. return;
  86857. if (!this.plane)
  86858. this.plane = polygons[0].plane.clone();
  86859. var front = new Array(), back = new Array();
  86860. for (var i = 0; i < polygons.length; i++) {
  86861. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  86862. }
  86863. if (front.length) {
  86864. if (!this.front)
  86865. this.front = new Node();
  86866. this.front.build(front);
  86867. }
  86868. if (back.length) {
  86869. if (!this.back)
  86870. this.back = new Node();
  86871. this.back.build(back);
  86872. }
  86873. };
  86874. return Node;
  86875. }());
  86876. var CSG = /** @class */ (function () {
  86877. function CSG() {
  86878. this.polygons = new Array();
  86879. }
  86880. // Convert BABYLON.Mesh to BABYLON.CSG
  86881. CSG.FromMesh = function (mesh) {
  86882. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  86883. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  86884. if (mesh instanceof BABYLON.Mesh) {
  86885. mesh.computeWorldMatrix(true);
  86886. matrix = mesh.getWorldMatrix();
  86887. meshPosition = mesh.position.clone();
  86888. meshRotation = mesh.rotation.clone();
  86889. if (mesh.rotationQuaternion) {
  86890. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  86891. }
  86892. meshScaling = mesh.scaling.clone();
  86893. }
  86894. else {
  86895. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  86896. }
  86897. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  86898. var subMeshes = mesh.subMeshes;
  86899. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  86900. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  86901. vertices = [];
  86902. for (var j = 0; j < 3; j++) {
  86903. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  86904. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  86905. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  86906. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  86907. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  86908. vertex = new Vertex(position, normal, uv);
  86909. vertices.push(vertex);
  86910. }
  86911. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  86912. // To handle the case of degenerated triangle
  86913. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  86914. if (polygon.plane)
  86915. polygons.push(polygon);
  86916. }
  86917. }
  86918. var csg = CSG.FromPolygons(polygons);
  86919. csg.matrix = matrix;
  86920. csg.position = meshPosition;
  86921. csg.rotation = meshRotation;
  86922. csg.scaling = meshScaling;
  86923. csg.rotationQuaternion = meshRotationQuaternion;
  86924. currentCSGMeshId++;
  86925. return csg;
  86926. };
  86927. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  86928. CSG.FromPolygons = function (polygons) {
  86929. var csg = new CSG();
  86930. csg.polygons = polygons;
  86931. return csg;
  86932. };
  86933. CSG.prototype.clone = function () {
  86934. var csg = new CSG();
  86935. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  86936. csg.copyTransformAttributes(this);
  86937. return csg;
  86938. };
  86939. CSG.prototype.union = function (csg) {
  86940. var a = new Node(this.clone().polygons);
  86941. var b = new Node(csg.clone().polygons);
  86942. a.clipTo(b);
  86943. b.clipTo(a);
  86944. b.invert();
  86945. b.clipTo(a);
  86946. b.invert();
  86947. a.build(b.allPolygons());
  86948. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86949. };
  86950. CSG.prototype.unionInPlace = function (csg) {
  86951. var a = new Node(this.polygons);
  86952. var b = new Node(csg.polygons);
  86953. a.clipTo(b);
  86954. b.clipTo(a);
  86955. b.invert();
  86956. b.clipTo(a);
  86957. b.invert();
  86958. a.build(b.allPolygons());
  86959. this.polygons = a.allPolygons();
  86960. };
  86961. CSG.prototype.subtract = function (csg) {
  86962. var a = new Node(this.clone().polygons);
  86963. var b = new Node(csg.clone().polygons);
  86964. a.invert();
  86965. a.clipTo(b);
  86966. b.clipTo(a);
  86967. b.invert();
  86968. b.clipTo(a);
  86969. b.invert();
  86970. a.build(b.allPolygons());
  86971. a.invert();
  86972. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86973. };
  86974. CSG.prototype.subtractInPlace = function (csg) {
  86975. var a = new Node(this.polygons);
  86976. var b = new Node(csg.polygons);
  86977. a.invert();
  86978. a.clipTo(b);
  86979. b.clipTo(a);
  86980. b.invert();
  86981. b.clipTo(a);
  86982. b.invert();
  86983. a.build(b.allPolygons());
  86984. a.invert();
  86985. this.polygons = a.allPolygons();
  86986. };
  86987. CSG.prototype.intersect = function (csg) {
  86988. var a = new Node(this.clone().polygons);
  86989. var b = new Node(csg.clone().polygons);
  86990. a.invert();
  86991. b.clipTo(a);
  86992. b.invert();
  86993. a.clipTo(b);
  86994. b.clipTo(a);
  86995. a.build(b.allPolygons());
  86996. a.invert();
  86997. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86998. };
  86999. CSG.prototype.intersectInPlace = function (csg) {
  87000. var a = new Node(this.polygons);
  87001. var b = new Node(csg.polygons);
  87002. a.invert();
  87003. b.clipTo(a);
  87004. b.invert();
  87005. a.clipTo(b);
  87006. b.clipTo(a);
  87007. a.build(b.allPolygons());
  87008. a.invert();
  87009. this.polygons = a.allPolygons();
  87010. };
  87011. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  87012. // not modified.
  87013. CSG.prototype.inverse = function () {
  87014. var csg = this.clone();
  87015. csg.inverseInPlace();
  87016. return csg;
  87017. };
  87018. CSG.prototype.inverseInPlace = function () {
  87019. this.polygons.map(function (p) { p.flip(); });
  87020. };
  87021. // This is used to keep meshes transformations so they can be restored
  87022. // when we build back a Babylon Mesh
  87023. // NB : All CSG operations are performed in world coordinates
  87024. CSG.prototype.copyTransformAttributes = function (csg) {
  87025. this.matrix = csg.matrix;
  87026. this.position = csg.position;
  87027. this.rotation = csg.rotation;
  87028. this.scaling = csg.scaling;
  87029. this.rotationQuaternion = csg.rotationQuaternion;
  87030. return this;
  87031. };
  87032. // Build Raw mesh from CSG
  87033. // Coordinates here are in world space
  87034. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  87035. var matrix = this.matrix.clone();
  87036. matrix.invert();
  87037. 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;
  87038. if (keepSubMeshes) {
  87039. // Sort Polygons, since subMeshes are indices range
  87040. polygons.sort(function (a, b) {
  87041. if (a.shared.meshId === b.shared.meshId) {
  87042. return a.shared.subMeshId - b.shared.subMeshId;
  87043. }
  87044. else {
  87045. return a.shared.meshId - b.shared.meshId;
  87046. }
  87047. });
  87048. }
  87049. for (var i = 0, il = polygons.length; i < il; i++) {
  87050. polygon = polygons[i];
  87051. // Building SubMeshes
  87052. if (!subMesh_dict[polygon.shared.meshId]) {
  87053. subMesh_dict[polygon.shared.meshId] = {};
  87054. }
  87055. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  87056. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  87057. indexStart: +Infinity,
  87058. indexEnd: -Infinity,
  87059. materialIndex: polygon.shared.materialIndex
  87060. };
  87061. }
  87062. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  87063. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  87064. polygonIndices[0] = 0;
  87065. polygonIndices[1] = j - 1;
  87066. polygonIndices[2] = j;
  87067. for (var k = 0; k < 3; k++) {
  87068. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  87069. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  87070. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  87071. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  87072. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  87073. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  87074. // Check if 2 points can be merged
  87075. if (!(typeof vertex_idx !== 'undefined' &&
  87076. normals[vertex_idx * 3] === localNormal.x &&
  87077. normals[vertex_idx * 3 + 1] === localNormal.y &&
  87078. normals[vertex_idx * 3 + 2] === localNormal.z &&
  87079. uvs[vertex_idx * 2] === uv.x &&
  87080. uvs[vertex_idx * 2 + 1] === uv.y)) {
  87081. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  87082. uvs.push(uv.x, uv.y);
  87083. normals.push(normal.x, normal.y, normal.z);
  87084. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  87085. }
  87086. indices.push(vertex_idx);
  87087. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  87088. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  87089. currentIndex++;
  87090. }
  87091. }
  87092. }
  87093. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  87094. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  87095. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  87096. mesh.setIndices(indices, null);
  87097. if (keepSubMeshes) {
  87098. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  87099. var materialIndexOffset = 0, materialMaxIndex;
  87100. mesh.subMeshes = new Array();
  87101. for (var m in subMesh_dict) {
  87102. materialMaxIndex = -1;
  87103. for (var sm in subMesh_dict[m]) {
  87104. subMesh_obj = subMesh_dict[m][sm];
  87105. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  87106. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  87107. }
  87108. materialIndexOffset += ++materialMaxIndex;
  87109. }
  87110. }
  87111. return mesh;
  87112. };
  87113. // Build Mesh from CSG taking material and transforms into account
  87114. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  87115. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  87116. mesh.material = material;
  87117. mesh.position.copyFrom(this.position);
  87118. mesh.rotation.copyFrom(this.rotation);
  87119. if (this.rotationQuaternion) {
  87120. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  87121. }
  87122. mesh.scaling.copyFrom(this.scaling);
  87123. mesh.computeWorldMatrix(true);
  87124. return mesh;
  87125. };
  87126. return CSG;
  87127. }());
  87128. BABYLON.CSG = CSG;
  87129. })(BABYLON || (BABYLON = {}));
  87130. //# sourceMappingURL=babylon.csg.js.map
  87131. var BABYLON;
  87132. (function (BABYLON) {
  87133. var LensFlare = /** @class */ (function () {
  87134. function LensFlare(size, position, color, imgUrl, system) {
  87135. this.size = size;
  87136. this.position = position;
  87137. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  87138. this.color = color || new BABYLON.Color3(1, 1, 1);
  87139. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  87140. this._system = system;
  87141. system.lensFlares.push(this);
  87142. }
  87143. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  87144. return new LensFlare(size, position, color, imgUrl, system);
  87145. };
  87146. LensFlare.prototype.dispose = function () {
  87147. if (this.texture) {
  87148. this.texture.dispose();
  87149. }
  87150. // Remove from scene
  87151. var index = this._system.lensFlares.indexOf(this);
  87152. this._system.lensFlares.splice(index, 1);
  87153. };
  87154. ;
  87155. return LensFlare;
  87156. }());
  87157. BABYLON.LensFlare = LensFlare;
  87158. })(BABYLON || (BABYLON = {}));
  87159. //# sourceMappingURL=babylon.lensFlare.js.map
  87160. var BABYLON;
  87161. (function (BABYLON) {
  87162. // Adds the parser to the scene parsers.
  87163. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  87164. // Lens flares
  87165. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  87166. if (!container.lensFlareSystems) {
  87167. container.lensFlareSystems = new Array();
  87168. }
  87169. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  87170. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  87171. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  87172. container.lensFlareSystems.push(lf);
  87173. }
  87174. }
  87175. });
  87176. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  87177. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  87178. if (this.lensFlareSystems[index].name === name) {
  87179. return this.lensFlareSystems[index];
  87180. }
  87181. }
  87182. return null;
  87183. };
  87184. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  87185. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  87186. if (this.lensFlareSystems[index].id === id) {
  87187. return this.lensFlareSystems[index];
  87188. }
  87189. }
  87190. return null;
  87191. };
  87192. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  87193. var index = this.lensFlareSystems.indexOf(toRemove);
  87194. if (index !== -1) {
  87195. this.lensFlareSystems.splice(index, 1);
  87196. }
  87197. return index;
  87198. };
  87199. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  87200. this.lensFlareSystems.push(newLensFlareSystem);
  87201. };
  87202. /**
  87203. * Defines the lens flare scene component responsible to manage any lens flares
  87204. * in a given scene.
  87205. */
  87206. var LensFlareSystemSceneComponent = /** @class */ (function () {
  87207. /**
  87208. * Creates a new instance of the component for the given scene
  87209. * @param scene Defines the scene to register the component in
  87210. */
  87211. function LensFlareSystemSceneComponent(scene) {
  87212. /**
  87213. * The component name helpfull to identify the component in the list of scene components.
  87214. */
  87215. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  87216. this.scene = scene;
  87217. scene.lensFlareSystems = new Array();
  87218. }
  87219. /**
  87220. * Registers the component in a given scene
  87221. */
  87222. LensFlareSystemSceneComponent.prototype.register = function () {
  87223. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  87224. };
  87225. /**
  87226. * Rebuilds the elements related to this component in case of
  87227. * context lost for instance.
  87228. */
  87229. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  87230. // Nothing to do for lens flare
  87231. };
  87232. /**
  87233. * Adds all the element from the container to the scene
  87234. * @param container the container holding the elements
  87235. */
  87236. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  87237. var _this = this;
  87238. if (!container.lensFlareSystems) {
  87239. return;
  87240. }
  87241. container.lensFlareSystems.forEach(function (o) {
  87242. _this.scene.addLensFlareSystem(o);
  87243. });
  87244. };
  87245. /**
  87246. * Removes all the elements in the container from the scene
  87247. * @param container contains the elements to remove
  87248. */
  87249. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  87250. var _this = this;
  87251. if (!container.lensFlareSystems) {
  87252. return;
  87253. }
  87254. container.lensFlareSystems.forEach(function (o) {
  87255. _this.scene.removeLensFlareSystem(o);
  87256. });
  87257. };
  87258. /**
  87259. * Serializes the component data to the specified json object
  87260. * @param serializationObject The object to serialize to
  87261. */
  87262. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  87263. // Lens flares
  87264. serializationObject.lensFlareSystems = [];
  87265. var lensFlareSystems = this.scene.lensFlareSystems;
  87266. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  87267. var lensFlareSystem = lensFlareSystems_1[_i];
  87268. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  87269. }
  87270. };
  87271. /**
  87272. * Disposes the component and the associated ressources.
  87273. */
  87274. LensFlareSystemSceneComponent.prototype.dispose = function () {
  87275. var lensFlareSystems = this.scene.lensFlareSystems;
  87276. while (lensFlareSystems.length) {
  87277. lensFlareSystems[0].dispose();
  87278. }
  87279. };
  87280. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  87281. // Lens flares
  87282. if (this.scene.lensFlaresEnabled) {
  87283. var lensFlareSystems = this.scene.lensFlareSystems;
  87284. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  87285. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  87286. var lensFlareSystem = lensFlareSystems_2[_i];
  87287. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  87288. lensFlareSystem.render();
  87289. }
  87290. }
  87291. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  87292. }
  87293. };
  87294. return LensFlareSystemSceneComponent;
  87295. }());
  87296. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  87297. })(BABYLON || (BABYLON = {}));
  87298. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  87299. var BABYLON;
  87300. (function (BABYLON) {
  87301. var LensFlareSystem = /** @class */ (function () {
  87302. function LensFlareSystem(name, emitter, scene) {
  87303. this.name = name;
  87304. this.lensFlares = new Array();
  87305. this.borderLimit = 300;
  87306. this.viewportBorder = 0;
  87307. this.layerMask = 0x0FFFFFFF;
  87308. this._vertexBuffers = {};
  87309. this._isEnabled = true;
  87310. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87311. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  87312. if (!component) {
  87313. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  87314. scene._addComponent(component);
  87315. }
  87316. this._emitter = emitter;
  87317. this.id = name;
  87318. scene.lensFlareSystems.push(this);
  87319. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  87320. var engine = scene.getEngine();
  87321. // VBO
  87322. var vertices = [];
  87323. vertices.push(1, 1);
  87324. vertices.push(-1, 1);
  87325. vertices.push(-1, -1);
  87326. vertices.push(1, -1);
  87327. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87328. // Indices
  87329. var indices = [];
  87330. indices.push(0);
  87331. indices.push(1);
  87332. indices.push(2);
  87333. indices.push(0);
  87334. indices.push(2);
  87335. indices.push(3);
  87336. this._indexBuffer = engine.createIndexBuffer(indices);
  87337. // Effects
  87338. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  87339. }
  87340. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  87341. get: function () {
  87342. return this._isEnabled;
  87343. },
  87344. set: function (value) {
  87345. this._isEnabled = value;
  87346. },
  87347. enumerable: true,
  87348. configurable: true
  87349. });
  87350. LensFlareSystem.prototype.getScene = function () {
  87351. return this._scene;
  87352. };
  87353. LensFlareSystem.prototype.getEmitter = function () {
  87354. return this._emitter;
  87355. };
  87356. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  87357. this._emitter = newEmitter;
  87358. };
  87359. LensFlareSystem.prototype.getEmitterPosition = function () {
  87360. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  87361. };
  87362. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  87363. var position = this.getEmitterPosition();
  87364. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  87365. this._positionX = position.x;
  87366. this._positionY = position.y;
  87367. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  87368. if (this.viewportBorder > 0) {
  87369. globalViewport.x -= this.viewportBorder;
  87370. globalViewport.y -= this.viewportBorder;
  87371. globalViewport.width += this.viewportBorder * 2;
  87372. globalViewport.height += this.viewportBorder * 2;
  87373. position.x += this.viewportBorder;
  87374. position.y += this.viewportBorder;
  87375. this._positionX += this.viewportBorder;
  87376. this._positionY += this.viewportBorder;
  87377. }
  87378. if (position.z > 0) {
  87379. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  87380. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  87381. return true;
  87382. }
  87383. return true;
  87384. }
  87385. return false;
  87386. };
  87387. /** @hidden */
  87388. LensFlareSystem.prototype._isVisible = function () {
  87389. if (!this._isEnabled || !this._scene.activeCamera) {
  87390. return false;
  87391. }
  87392. var emitterPosition = this.getEmitterPosition();
  87393. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  87394. var distance = direction.length();
  87395. direction.normalize();
  87396. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  87397. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  87398. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  87399. };
  87400. LensFlareSystem.prototype.render = function () {
  87401. if (!this._effect.isReady() || !this._scene.activeCamera)
  87402. return false;
  87403. var engine = this._scene.getEngine();
  87404. var viewport = this._scene.activeCamera.viewport;
  87405. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  87406. // Position
  87407. if (!this.computeEffectivePosition(globalViewport)) {
  87408. return false;
  87409. }
  87410. // Visibility
  87411. if (!this._isVisible()) {
  87412. return false;
  87413. }
  87414. // Intensity
  87415. var awayX;
  87416. var awayY;
  87417. if (this._positionX < this.borderLimit + globalViewport.x) {
  87418. awayX = this.borderLimit + globalViewport.x - this._positionX;
  87419. }
  87420. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  87421. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  87422. }
  87423. else {
  87424. awayX = 0;
  87425. }
  87426. if (this._positionY < this.borderLimit + globalViewport.y) {
  87427. awayY = this.borderLimit + globalViewport.y - this._positionY;
  87428. }
  87429. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  87430. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  87431. }
  87432. else {
  87433. awayY = 0;
  87434. }
  87435. var away = (awayX > awayY) ? awayX : awayY;
  87436. away -= this.viewportBorder;
  87437. if (away > this.borderLimit) {
  87438. away = this.borderLimit;
  87439. }
  87440. var intensity = 1.0 - (away / this.borderLimit);
  87441. if (intensity < 0) {
  87442. return false;
  87443. }
  87444. if (intensity > 1.0) {
  87445. intensity = 1.0;
  87446. }
  87447. if (this.viewportBorder > 0) {
  87448. globalViewport.x += this.viewportBorder;
  87449. globalViewport.y += this.viewportBorder;
  87450. globalViewport.width -= this.viewportBorder * 2;
  87451. globalViewport.height -= this.viewportBorder * 2;
  87452. this._positionX -= this.viewportBorder;
  87453. this._positionY -= this.viewportBorder;
  87454. }
  87455. // Position
  87456. var centerX = globalViewport.x + globalViewport.width / 2;
  87457. var centerY = globalViewport.y + globalViewport.height / 2;
  87458. var distX = centerX - this._positionX;
  87459. var distY = centerY - this._positionY;
  87460. // Effects
  87461. engine.enableEffect(this._effect);
  87462. engine.setState(false);
  87463. engine.setDepthBuffer(false);
  87464. // VBOs
  87465. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  87466. // Flares
  87467. for (var index = 0; index < this.lensFlares.length; index++) {
  87468. var flare = this.lensFlares[index];
  87469. engine.setAlphaMode(flare.alphaMode);
  87470. var x = centerX - (distX * flare.position);
  87471. var y = centerY - (distY * flare.position);
  87472. var cw = flare.size;
  87473. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  87474. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  87475. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  87476. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  87477. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  87478. // Texture
  87479. this._effect.setTexture("textureSampler", flare.texture);
  87480. // Color
  87481. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  87482. // Draw order
  87483. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87484. }
  87485. engine.setDepthBuffer(true);
  87486. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  87487. return true;
  87488. };
  87489. LensFlareSystem.prototype.dispose = function () {
  87490. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87491. if (vertexBuffer) {
  87492. vertexBuffer.dispose();
  87493. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87494. }
  87495. if (this._indexBuffer) {
  87496. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87497. this._indexBuffer = null;
  87498. }
  87499. while (this.lensFlares.length) {
  87500. this.lensFlares[0].dispose();
  87501. }
  87502. // Remove from scene
  87503. var index = this._scene.lensFlareSystems.indexOf(this);
  87504. this._scene.lensFlareSystems.splice(index, 1);
  87505. };
  87506. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  87507. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  87508. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  87509. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  87510. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  87511. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  87512. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  87513. var parsedFlare = parsedLensFlareSystem.flares[index];
  87514. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  87515. }
  87516. return lensFlareSystem;
  87517. };
  87518. LensFlareSystem.prototype.serialize = function () {
  87519. var serializationObject = {};
  87520. serializationObject.id = this.id;
  87521. serializationObject.name = this.name;
  87522. serializationObject.emitterId = this.getEmitter().id;
  87523. serializationObject.borderLimit = this.borderLimit;
  87524. serializationObject.flares = [];
  87525. for (var index = 0; index < this.lensFlares.length; index++) {
  87526. var flare = this.lensFlares[index];
  87527. serializationObject.flares.push({
  87528. size: flare.size,
  87529. position: flare.position,
  87530. color: flare.color.asArray(),
  87531. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  87532. });
  87533. }
  87534. return serializationObject;
  87535. };
  87536. return LensFlareSystem;
  87537. }());
  87538. BABYLON.LensFlareSystem = LensFlareSystem;
  87539. })(BABYLON || (BABYLON = {}));
  87540. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  87541. var BABYLON;
  87542. (function (BABYLON) {
  87543. /**
  87544. * This is a holder class for the physics joint created by the physics plugin.
  87545. * It holds a set of functions to control the underlying joint.
  87546. */
  87547. var PhysicsJoint = /** @class */ (function () {
  87548. function PhysicsJoint(type, jointData) {
  87549. this.type = type;
  87550. this.jointData = jointData;
  87551. jointData.nativeParams = jointData.nativeParams || {};
  87552. }
  87553. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  87554. get: function () {
  87555. return this._physicsJoint;
  87556. },
  87557. set: function (newJoint) {
  87558. if (this._physicsJoint) {
  87559. //remove from the wolrd
  87560. }
  87561. this._physicsJoint = newJoint;
  87562. },
  87563. enumerable: true,
  87564. configurable: true
  87565. });
  87566. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  87567. set: function (physicsPlugin) {
  87568. this._physicsPlugin = physicsPlugin;
  87569. },
  87570. enumerable: true,
  87571. configurable: true
  87572. });
  87573. /**
  87574. * Execute a function that is physics-plugin specific.
  87575. * @param {Function} func the function that will be executed.
  87576. * It accepts two parameters: the physics world and the physics joint.
  87577. */
  87578. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  87579. func(this._physicsPlugin.world, this._physicsJoint);
  87580. };
  87581. //TODO check if the native joints are the same
  87582. //Joint Types
  87583. PhysicsJoint.DistanceJoint = 0;
  87584. PhysicsJoint.HingeJoint = 1;
  87585. PhysicsJoint.BallAndSocketJoint = 2;
  87586. PhysicsJoint.WheelJoint = 3;
  87587. PhysicsJoint.SliderJoint = 4;
  87588. //OIMO
  87589. PhysicsJoint.PrismaticJoint = 5;
  87590. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  87591. PhysicsJoint.UniversalJoint = 6;
  87592. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  87593. //Cannon
  87594. //Similar to a Ball-Joint. Different in params
  87595. PhysicsJoint.PointToPointJoint = 8;
  87596. //Cannon only at the moment
  87597. PhysicsJoint.SpringJoint = 9;
  87598. PhysicsJoint.LockJoint = 10;
  87599. return PhysicsJoint;
  87600. }());
  87601. BABYLON.PhysicsJoint = PhysicsJoint;
  87602. /**
  87603. * A class representing a physics distance joint.
  87604. */
  87605. var DistanceJoint = /** @class */ (function (_super) {
  87606. __extends(DistanceJoint, _super);
  87607. function DistanceJoint(jointData) {
  87608. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  87609. }
  87610. /**
  87611. * Update the predefined distance.
  87612. */
  87613. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  87614. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  87615. };
  87616. return DistanceJoint;
  87617. }(PhysicsJoint));
  87618. BABYLON.DistanceJoint = DistanceJoint;
  87619. var MotorEnabledJoint = /** @class */ (function (_super) {
  87620. __extends(MotorEnabledJoint, _super);
  87621. function MotorEnabledJoint(type, jointData) {
  87622. return _super.call(this, type, jointData) || this;
  87623. }
  87624. /**
  87625. * Set the motor values.
  87626. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87627. * @param {number} force the force to apply
  87628. * @param {number} maxForce max force for this motor.
  87629. */
  87630. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  87631. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  87632. };
  87633. /**
  87634. * Set the motor's limits.
  87635. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87636. */
  87637. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  87638. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  87639. };
  87640. return MotorEnabledJoint;
  87641. }(PhysicsJoint));
  87642. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  87643. /**
  87644. * This class represents a single hinge physics joint
  87645. */
  87646. var HingeJoint = /** @class */ (function (_super) {
  87647. __extends(HingeJoint, _super);
  87648. function HingeJoint(jointData) {
  87649. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  87650. }
  87651. /**
  87652. * Set the motor values.
  87653. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87654. * @param {number} force the force to apply
  87655. * @param {number} maxForce max force for this motor.
  87656. */
  87657. HingeJoint.prototype.setMotor = function (force, maxForce) {
  87658. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  87659. };
  87660. /**
  87661. * Set the motor's limits.
  87662. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87663. */
  87664. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  87665. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  87666. };
  87667. return HingeJoint;
  87668. }(MotorEnabledJoint));
  87669. BABYLON.HingeJoint = HingeJoint;
  87670. /**
  87671. * This class represents a dual hinge physics joint (same as wheel joint)
  87672. */
  87673. var Hinge2Joint = /** @class */ (function (_super) {
  87674. __extends(Hinge2Joint, _super);
  87675. function Hinge2Joint(jointData) {
  87676. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  87677. }
  87678. /**
  87679. * Set the motor values.
  87680. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87681. * @param {number} force the force to apply
  87682. * @param {number} maxForce max force for this motor.
  87683. * @param {motorIndex} the motor's index, 0 or 1.
  87684. */
  87685. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  87686. if (motorIndex === void 0) { motorIndex = 0; }
  87687. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  87688. };
  87689. /**
  87690. * Set the motor limits.
  87691. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87692. * @param {number} upperLimit the upper limit
  87693. * @param {number} lowerLimit lower limit
  87694. * @param {motorIndex} the motor's index, 0 or 1.
  87695. */
  87696. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  87697. if (motorIndex === void 0) { motorIndex = 0; }
  87698. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  87699. };
  87700. return Hinge2Joint;
  87701. }(MotorEnabledJoint));
  87702. BABYLON.Hinge2Joint = Hinge2Joint;
  87703. })(BABYLON || (BABYLON = {}));
  87704. //# sourceMappingURL=babylon.physicsJoint.js.map
  87705. var BABYLON;
  87706. (function (BABYLON) {
  87707. var PhysicsImpostor = /** @class */ (function () {
  87708. function PhysicsImpostor(object, type, _options, _scene) {
  87709. if (_options === void 0) { _options = { mass: 0 }; }
  87710. var _this = this;
  87711. this.object = object;
  87712. this.type = type;
  87713. this._options = _options;
  87714. this._scene = _scene;
  87715. this._bodyUpdateRequired = false;
  87716. this._onBeforePhysicsStepCallbacks = new Array();
  87717. this._onAfterPhysicsStepCallbacks = new Array();
  87718. this._onPhysicsCollideCallbacks = [];
  87719. this._deltaPosition = BABYLON.Vector3.Zero();
  87720. this._isDisposed = false;
  87721. //temp variables for parent rotation calculations
  87722. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  87723. this._tmpQuat = new BABYLON.Quaternion();
  87724. this._tmpQuat2 = new BABYLON.Quaternion();
  87725. /**
  87726. * this function is executed by the physics engine.
  87727. */
  87728. this.beforeStep = function () {
  87729. if (!_this._physicsEngine) {
  87730. return;
  87731. }
  87732. _this.object.translate(_this._deltaPosition, -1);
  87733. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  87734. _this.object.computeWorldMatrix(false);
  87735. if (_this.object.parent && _this.object.rotationQuaternion) {
  87736. _this.getParentsRotation();
  87737. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  87738. }
  87739. else {
  87740. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  87741. }
  87742. if (!_this._options.disableBidirectionalTransformation) {
  87743. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  87744. }
  87745. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  87746. func(_this);
  87747. });
  87748. };
  87749. /**
  87750. * this function is executed by the physics engine.
  87751. */
  87752. this.afterStep = function () {
  87753. if (!_this._physicsEngine) {
  87754. return;
  87755. }
  87756. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  87757. func(_this);
  87758. });
  87759. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  87760. // object has now its world rotation. needs to be converted to local.
  87761. if (_this.object.parent && _this.object.rotationQuaternion) {
  87762. _this.getParentsRotation();
  87763. _this._tmpQuat.conjugateInPlace();
  87764. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  87765. }
  87766. // take the position set and make it the absolute position of this object.
  87767. _this.object.setAbsolutePosition(_this.object.position);
  87768. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  87769. _this.object.translate(_this._deltaPosition, 1);
  87770. };
  87771. /**
  87772. * Legacy collision detection event support
  87773. */
  87774. this.onCollideEvent = null;
  87775. //event and body object due to cannon's event-based architecture.
  87776. this.onCollide = function (e) {
  87777. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  87778. return;
  87779. }
  87780. if (!_this._physicsEngine) {
  87781. return;
  87782. }
  87783. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  87784. if (otherImpostor) {
  87785. // Legacy collision detection event support
  87786. if (_this.onCollideEvent) {
  87787. _this.onCollideEvent(_this, otherImpostor);
  87788. }
  87789. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  87790. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  87791. }).forEach(function (obj) {
  87792. obj.callback(_this, otherImpostor);
  87793. });
  87794. }
  87795. };
  87796. //sanity check!
  87797. if (!this.object) {
  87798. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  87799. return;
  87800. }
  87801. //legacy support for old syntax.
  87802. if (!this._scene && object.getScene) {
  87803. this._scene = object.getScene();
  87804. }
  87805. if (!this._scene) {
  87806. return;
  87807. }
  87808. this._physicsEngine = this._scene.getPhysicsEngine();
  87809. if (!this._physicsEngine) {
  87810. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  87811. }
  87812. else {
  87813. //set the object's quaternion, if not set
  87814. if (!this.object.rotationQuaternion) {
  87815. if (this.object.rotation) {
  87816. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  87817. }
  87818. else {
  87819. this.object.rotationQuaternion = new BABYLON.Quaternion();
  87820. }
  87821. }
  87822. //default options params
  87823. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  87824. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  87825. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  87826. this._joints = [];
  87827. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  87828. if (!this.object.parent || this._options.ignoreParent) {
  87829. this._init();
  87830. }
  87831. else if (this.object.parent.physicsImpostor) {
  87832. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  87833. }
  87834. }
  87835. }
  87836. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  87837. get: function () {
  87838. return this._isDisposed;
  87839. },
  87840. enumerable: true,
  87841. configurable: true
  87842. });
  87843. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  87844. get: function () {
  87845. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  87846. },
  87847. set: function (value) {
  87848. this.setMass(value);
  87849. },
  87850. enumerable: true,
  87851. configurable: true
  87852. });
  87853. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  87854. get: function () {
  87855. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  87856. },
  87857. set: function (value) {
  87858. if (!this._physicsEngine) {
  87859. return;
  87860. }
  87861. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  87862. },
  87863. enumerable: true,
  87864. configurable: true
  87865. });
  87866. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  87867. get: function () {
  87868. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  87869. },
  87870. set: function (value) {
  87871. if (!this._physicsEngine) {
  87872. return;
  87873. }
  87874. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  87875. },
  87876. enumerable: true,
  87877. configurable: true
  87878. });
  87879. /**
  87880. * This function will completly initialize this impostor.
  87881. * It will create a new body - but only if this mesh has no parent.
  87882. * If it has, this impostor will not be used other than to define the impostor
  87883. * of the child mesh.
  87884. * @hidden
  87885. */
  87886. PhysicsImpostor.prototype._init = function () {
  87887. if (!this._physicsEngine) {
  87888. return;
  87889. }
  87890. this._physicsEngine.removeImpostor(this);
  87891. this.physicsBody = null;
  87892. this._parent = this._parent || this._getPhysicsParent();
  87893. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  87894. this._physicsEngine.addImpostor(this);
  87895. }
  87896. };
  87897. PhysicsImpostor.prototype._getPhysicsParent = function () {
  87898. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  87899. var parentMesh = this.object.parent;
  87900. return parentMesh.physicsImpostor;
  87901. }
  87902. return null;
  87903. };
  87904. /**
  87905. * Should a new body be generated.
  87906. */
  87907. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  87908. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  87909. };
  87910. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  87911. this.forceUpdate();
  87912. };
  87913. /**
  87914. * Force a regeneration of this or the parent's impostor's body.
  87915. * Use under cautious - This will remove all joints already implemented.
  87916. */
  87917. PhysicsImpostor.prototype.forceUpdate = function () {
  87918. this._init();
  87919. if (this.parent && !this._options.ignoreParent) {
  87920. this.parent.forceUpdate();
  87921. }
  87922. };
  87923. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  87924. /*public get mesh(): AbstractMesh {
  87925. return this._mesh;
  87926. }*/
  87927. /**
  87928. * Gets the body that holds this impostor. Either its own, or its parent.
  87929. */
  87930. get: function () {
  87931. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  87932. },
  87933. /**
  87934. * Set the physics body. Used mainly by the physics engine/plugin
  87935. */
  87936. set: function (physicsBody) {
  87937. if (this._physicsBody && this._physicsEngine) {
  87938. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  87939. }
  87940. this._physicsBody = physicsBody;
  87941. this.resetUpdateFlags();
  87942. },
  87943. enumerable: true,
  87944. configurable: true
  87945. });
  87946. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  87947. get: function () {
  87948. return !this._options.ignoreParent && this._parent ? this._parent : null;
  87949. },
  87950. set: function (value) {
  87951. this._parent = value;
  87952. },
  87953. enumerable: true,
  87954. configurable: true
  87955. });
  87956. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  87957. this._bodyUpdateRequired = false;
  87958. };
  87959. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  87960. if (this.object.getBoundingInfo) {
  87961. var q = this.object.rotationQuaternion;
  87962. //reset rotation
  87963. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  87964. //calculate the world matrix with no rotation
  87965. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  87966. var boundingInfo = this.object.getBoundingInfo();
  87967. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  87968. //bring back the rotation
  87969. this.object.rotationQuaternion = q;
  87970. //calculate the world matrix with the new rotation
  87971. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  87972. return size;
  87973. }
  87974. else {
  87975. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  87976. }
  87977. };
  87978. PhysicsImpostor.prototype.getObjectCenter = function () {
  87979. if (this.object.getBoundingInfo) {
  87980. var boundingInfo = this.object.getBoundingInfo();
  87981. return boundingInfo.boundingBox.centerWorld;
  87982. }
  87983. else {
  87984. return this.object.position;
  87985. }
  87986. };
  87987. /**
  87988. * Get a specific parametes from the options parameter.
  87989. */
  87990. PhysicsImpostor.prototype.getParam = function (paramName) {
  87991. return this._options[paramName];
  87992. };
  87993. /**
  87994. * Sets a specific parameter in the options given to the physics plugin
  87995. */
  87996. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  87997. this._options[paramName] = value;
  87998. this._bodyUpdateRequired = true;
  87999. };
  88000. /**
  88001. * Specifically change the body's mass option. Won't recreate the physics body object
  88002. */
  88003. PhysicsImpostor.prototype.setMass = function (mass) {
  88004. if (this.getParam("mass") !== mass) {
  88005. this.setParam("mass", mass);
  88006. }
  88007. if (this._physicsEngine) {
  88008. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  88009. }
  88010. };
  88011. PhysicsImpostor.prototype.getLinearVelocity = function () {
  88012. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  88013. };
  88014. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  88015. if (this._physicsEngine) {
  88016. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  88017. }
  88018. };
  88019. PhysicsImpostor.prototype.getAngularVelocity = function () {
  88020. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  88021. };
  88022. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  88023. if (this._physicsEngine) {
  88024. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  88025. }
  88026. };
  88027. /**
  88028. * Execute a function with the physics plugin native code.
  88029. * Provide a function the will have two variables - the world object and the physics body object.
  88030. */
  88031. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  88032. if (this._physicsEngine) {
  88033. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  88034. }
  88035. };
  88036. /**
  88037. * Register a function that will be executed before the physics world is stepping forward.
  88038. */
  88039. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  88040. this._onBeforePhysicsStepCallbacks.push(func);
  88041. };
  88042. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  88043. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  88044. if (index > -1) {
  88045. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  88046. }
  88047. else {
  88048. BABYLON.Tools.Warn("Function to remove was not found");
  88049. }
  88050. };
  88051. /**
  88052. * Register a function that will be executed after the physics step
  88053. */
  88054. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  88055. this._onAfterPhysicsStepCallbacks.push(func);
  88056. };
  88057. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  88058. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  88059. if (index > -1) {
  88060. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  88061. }
  88062. else {
  88063. BABYLON.Tools.Warn("Function to remove was not found");
  88064. }
  88065. };
  88066. /**
  88067. * register a function that will be executed when this impostor collides against a different body.
  88068. */
  88069. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  88070. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  88071. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  88072. };
  88073. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  88074. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  88075. var index = -1;
  88076. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  88077. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  88078. // chcek the arrays match
  88079. var sameList = cbDef.otherImpostors.every(function (impostor) {
  88080. return collidedAgainstList.indexOf(impostor) > -1;
  88081. });
  88082. if (sameList) {
  88083. index = idx;
  88084. }
  88085. return sameList;
  88086. }
  88087. return false;
  88088. });
  88089. if (found) {
  88090. this._onPhysicsCollideCallbacks.splice(index, 1);
  88091. }
  88092. else {
  88093. BABYLON.Tools.Warn("Function to remove was not found");
  88094. }
  88095. };
  88096. PhysicsImpostor.prototype.getParentsRotation = function () {
  88097. var parent = this.object.parent;
  88098. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  88099. while (parent) {
  88100. if (parent.rotationQuaternion) {
  88101. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  88102. }
  88103. else {
  88104. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  88105. }
  88106. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  88107. parent = parent.parent;
  88108. }
  88109. return this._tmpQuat;
  88110. };
  88111. /**
  88112. * Apply a force
  88113. */
  88114. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  88115. if (this._physicsEngine) {
  88116. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  88117. }
  88118. return this;
  88119. };
  88120. /**
  88121. * Apply an impulse
  88122. */
  88123. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  88124. if (this._physicsEngine) {
  88125. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  88126. }
  88127. return this;
  88128. };
  88129. /**
  88130. * A help function to create a joint.
  88131. */
  88132. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  88133. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  88134. this.addJoint(otherImpostor, joint);
  88135. return this;
  88136. };
  88137. /**
  88138. * Add a joint to this impostor with a different impostor.
  88139. */
  88140. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  88141. this._joints.push({
  88142. otherImpostor: otherImpostor,
  88143. joint: joint
  88144. });
  88145. if (this._physicsEngine) {
  88146. this._physicsEngine.addJoint(this, otherImpostor, joint);
  88147. }
  88148. return this;
  88149. };
  88150. /**
  88151. * Will keep this body still, in a sleep mode.
  88152. */
  88153. PhysicsImpostor.prototype.sleep = function () {
  88154. if (this._physicsEngine) {
  88155. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  88156. }
  88157. return this;
  88158. };
  88159. /**
  88160. * Wake the body up.
  88161. */
  88162. PhysicsImpostor.prototype.wakeUp = function () {
  88163. if (this._physicsEngine) {
  88164. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  88165. }
  88166. return this;
  88167. };
  88168. PhysicsImpostor.prototype.clone = function (newObject) {
  88169. if (!newObject)
  88170. return null;
  88171. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  88172. };
  88173. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  88174. var _this = this;
  88175. //no dispose if no physics engine is available.
  88176. if (!this._physicsEngine) {
  88177. return;
  88178. }
  88179. this._joints.forEach(function (j) {
  88180. if (_this._physicsEngine) {
  88181. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  88182. }
  88183. });
  88184. //dispose the physics body
  88185. this._physicsEngine.removeImpostor(this);
  88186. if (this.parent) {
  88187. this.parent.forceUpdate();
  88188. }
  88189. else {
  88190. /*this._object.getChildMeshes().forEach(function(mesh) {
  88191. if (mesh.physicsImpostor) {
  88192. if (disposeChildren) {
  88193. mesh.physicsImpostor.dispose();
  88194. mesh.physicsImpostor = null;
  88195. }
  88196. }
  88197. })*/
  88198. }
  88199. this._isDisposed = true;
  88200. };
  88201. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  88202. this._deltaPosition.copyFrom(position);
  88203. };
  88204. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  88205. if (!this._deltaRotation) {
  88206. this._deltaRotation = new BABYLON.Quaternion();
  88207. }
  88208. this._deltaRotation.copyFrom(rotation);
  88209. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  88210. };
  88211. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  88212. if (this._physicsEngine) {
  88213. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  88214. }
  88215. return this;
  88216. };
  88217. PhysicsImpostor.prototype.getRadius = function () {
  88218. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  88219. };
  88220. /**
  88221. * Sync a bone with this impostor
  88222. * @param bone The bone to sync to the impostor.
  88223. * @param boneMesh The mesh that the bone is influencing.
  88224. * @param jointPivot The pivot of the joint / bone in local space.
  88225. * @param distToJoint Optional distance from the impostor to the joint.
  88226. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  88227. */
  88228. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  88229. var tempVec = PhysicsImpostor._tmpVecs[0];
  88230. var mesh = this.object;
  88231. if (mesh.rotationQuaternion) {
  88232. if (adjustRotation) {
  88233. var tempQuat = PhysicsImpostor._tmpQuat;
  88234. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  88235. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  88236. }
  88237. else {
  88238. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  88239. }
  88240. }
  88241. tempVec.x = 0;
  88242. tempVec.y = 0;
  88243. tempVec.z = 0;
  88244. if (jointPivot) {
  88245. tempVec.x = jointPivot.x;
  88246. tempVec.y = jointPivot.y;
  88247. tempVec.z = jointPivot.z;
  88248. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  88249. if (distToJoint === undefined || distToJoint === null) {
  88250. distToJoint = jointPivot.length();
  88251. }
  88252. tempVec.x *= distToJoint;
  88253. tempVec.y *= distToJoint;
  88254. tempVec.z *= distToJoint;
  88255. }
  88256. if (bone.getParent()) {
  88257. tempVec.addInPlace(mesh.getAbsolutePosition());
  88258. bone.setAbsolutePosition(tempVec, boneMesh);
  88259. }
  88260. else {
  88261. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  88262. boneMesh.position.x -= tempVec.x;
  88263. boneMesh.position.y -= tempVec.y;
  88264. boneMesh.position.z -= tempVec.z;
  88265. }
  88266. };
  88267. /**
  88268. * Sync impostor to a bone
  88269. * @param bone The bone that the impostor will be synced to.
  88270. * @param boneMesh The mesh that the bone is influencing.
  88271. * @param jointPivot The pivot of the joint / bone in local space.
  88272. * @param distToJoint Optional distance from the impostor to the joint.
  88273. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  88274. * @param boneAxis Optional vector3 axis the bone is aligned with
  88275. */
  88276. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  88277. var mesh = this.object;
  88278. if (mesh.rotationQuaternion) {
  88279. if (adjustRotation) {
  88280. var tempQuat = PhysicsImpostor._tmpQuat;
  88281. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  88282. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  88283. }
  88284. else {
  88285. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  88286. }
  88287. }
  88288. var pos = PhysicsImpostor._tmpVecs[0];
  88289. var boneDir = PhysicsImpostor._tmpVecs[1];
  88290. if (!boneAxis) {
  88291. boneAxis = PhysicsImpostor._tmpVecs[2];
  88292. boneAxis.x = 0;
  88293. boneAxis.y = 1;
  88294. boneAxis.z = 0;
  88295. }
  88296. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  88297. bone.getAbsolutePositionToRef(boneMesh, pos);
  88298. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  88299. distToJoint = jointPivot.length();
  88300. }
  88301. if (distToJoint !== undefined && distToJoint !== null) {
  88302. pos.x += boneDir.x * distToJoint;
  88303. pos.y += boneDir.y * distToJoint;
  88304. pos.z += boneDir.z * distToJoint;
  88305. }
  88306. mesh.setAbsolutePosition(pos);
  88307. };
  88308. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  88309. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  88310. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88311. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  88312. //Impostor types
  88313. PhysicsImpostor.NoImpostor = 0;
  88314. PhysicsImpostor.SphereImpostor = 1;
  88315. PhysicsImpostor.BoxImpostor = 2;
  88316. PhysicsImpostor.PlaneImpostor = 3;
  88317. PhysicsImpostor.MeshImpostor = 4;
  88318. PhysicsImpostor.CylinderImpostor = 7;
  88319. PhysicsImpostor.ParticleImpostor = 8;
  88320. PhysicsImpostor.HeightmapImpostor = 9;
  88321. return PhysicsImpostor;
  88322. }());
  88323. BABYLON.PhysicsImpostor = PhysicsImpostor;
  88324. })(BABYLON || (BABYLON = {}));
  88325. //# sourceMappingURL=babylon.physicsImpostor.js.map
  88326. var BABYLON;
  88327. (function (BABYLON) {
  88328. var PhysicsEngine = /** @class */ (function () {
  88329. function PhysicsEngine(gravity, _physicsPlugin) {
  88330. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  88331. this._physicsPlugin = _physicsPlugin;
  88332. //new methods and parameters
  88333. this._impostors = [];
  88334. this._joints = [];
  88335. if (!this._physicsPlugin.isSupported()) {
  88336. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  88337. + "Please make sure it is included.");
  88338. }
  88339. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  88340. this.setGravity(gravity);
  88341. this.setTimeStep();
  88342. }
  88343. PhysicsEngine.prototype.setGravity = function (gravity) {
  88344. this.gravity = gravity;
  88345. this._physicsPlugin.setGravity(this.gravity);
  88346. };
  88347. /**
  88348. * Set the time step of the physics engine.
  88349. * default is 1/60.
  88350. * To slow it down, enter 1/600 for example.
  88351. * To speed it up, 1/30
  88352. * @param {number} newTimeStep the new timestep to apply to this world.
  88353. */
  88354. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  88355. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  88356. this._physicsPlugin.setTimeStep(newTimeStep);
  88357. };
  88358. /**
  88359. * Get the time step of the physics engine.
  88360. */
  88361. PhysicsEngine.prototype.getTimeStep = function () {
  88362. return this._physicsPlugin.getTimeStep();
  88363. };
  88364. PhysicsEngine.prototype.dispose = function () {
  88365. this._impostors.forEach(function (impostor) {
  88366. impostor.dispose();
  88367. });
  88368. this._physicsPlugin.dispose();
  88369. };
  88370. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  88371. return this._physicsPlugin.name;
  88372. };
  88373. /**
  88374. * Adding a new impostor for the impostor tracking.
  88375. * This will be done by the impostor itself.
  88376. * @param {PhysicsImpostor} impostor the impostor to add
  88377. */
  88378. PhysicsEngine.prototype.addImpostor = function (impostor) {
  88379. impostor.uniqueId = this._impostors.push(impostor);
  88380. //if no parent, generate the body
  88381. if (!impostor.parent) {
  88382. this._physicsPlugin.generatePhysicsBody(impostor);
  88383. }
  88384. };
  88385. /**
  88386. * Remove an impostor from the engine.
  88387. * This impostor and its mesh will not longer be updated by the physics engine.
  88388. * @param {PhysicsImpostor} impostor the impostor to remove
  88389. */
  88390. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  88391. var index = this._impostors.indexOf(impostor);
  88392. if (index > -1) {
  88393. var removed = this._impostors.splice(index, 1);
  88394. //Is it needed?
  88395. if (removed.length) {
  88396. //this will also remove it from the world.
  88397. removed[0].physicsBody = null;
  88398. }
  88399. }
  88400. };
  88401. /**
  88402. * Add a joint to the physics engine
  88403. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  88404. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  88405. * @param {PhysicsJoint} the joint that will connect both impostors.
  88406. */
  88407. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  88408. var impostorJoint = {
  88409. mainImpostor: mainImpostor,
  88410. connectedImpostor: connectedImpostor,
  88411. joint: joint
  88412. };
  88413. joint.physicsPlugin = this._physicsPlugin;
  88414. this._joints.push(impostorJoint);
  88415. this._physicsPlugin.generateJoint(impostorJoint);
  88416. };
  88417. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  88418. var matchingJoints = this._joints.filter(function (impostorJoint) {
  88419. return (impostorJoint.connectedImpostor === connectedImpostor
  88420. && impostorJoint.joint === joint
  88421. && impostorJoint.mainImpostor === mainImpostor);
  88422. });
  88423. if (matchingJoints.length) {
  88424. this._physicsPlugin.removeJoint(matchingJoints[0]);
  88425. //TODO remove it from the list as well
  88426. }
  88427. };
  88428. /**
  88429. * Called by the scene. no need to call it.
  88430. * @hidden
  88431. */
  88432. PhysicsEngine.prototype._step = function (delta) {
  88433. var _this = this;
  88434. //check if any mesh has no body / requires an update
  88435. this._impostors.forEach(function (impostor) {
  88436. if (impostor.isBodyInitRequired()) {
  88437. _this._physicsPlugin.generatePhysicsBody(impostor);
  88438. }
  88439. });
  88440. if (delta > 0.1) {
  88441. delta = 0.1;
  88442. }
  88443. else if (delta <= 0) {
  88444. delta = 1.0 / 60.0;
  88445. }
  88446. this._physicsPlugin.executeStep(delta, this._impostors);
  88447. };
  88448. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  88449. return this._physicsPlugin;
  88450. };
  88451. PhysicsEngine.prototype.getImpostors = function () {
  88452. return this._impostors;
  88453. };
  88454. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  88455. for (var i = 0; i < this._impostors.length; ++i) {
  88456. if (this._impostors[i].object === object) {
  88457. return this._impostors[i];
  88458. }
  88459. }
  88460. return null;
  88461. };
  88462. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  88463. for (var i = 0; i < this._impostors.length; ++i) {
  88464. if (this._impostors[i].physicsBody === body) {
  88465. return this._impostors[i];
  88466. }
  88467. }
  88468. return null;
  88469. };
  88470. // Statics
  88471. PhysicsEngine.Epsilon = 0.001;
  88472. return PhysicsEngine;
  88473. }());
  88474. BABYLON.PhysicsEngine = PhysicsEngine;
  88475. })(BABYLON || (BABYLON = {}));
  88476. //# sourceMappingURL=babylon.physicsEngine.js.map
  88477. var BABYLON;
  88478. (function (BABYLON) {
  88479. var PhysicsHelper = /** @class */ (function () {
  88480. function PhysicsHelper(scene) {
  88481. this._scene = scene;
  88482. this._physicsEngine = this._scene.getPhysicsEngine();
  88483. if (!this._physicsEngine) {
  88484. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  88485. }
  88486. }
  88487. /**
  88488. * @param {Vector3} origin the origin of the explosion
  88489. * @param {number} radius the explosion radius
  88490. * @param {number} strength the explosion strength
  88491. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  88492. */
  88493. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  88494. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  88495. if (!this._physicsEngine) {
  88496. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  88497. return null;
  88498. }
  88499. var impostors = this._physicsEngine.getImpostors();
  88500. if (impostors.length === 0) {
  88501. return null;
  88502. }
  88503. var event = new PhysicsRadialExplosionEvent(this._scene);
  88504. impostors.forEach(function (impostor) {
  88505. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  88506. if (!impostorForceAndContactPoint) {
  88507. return;
  88508. }
  88509. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88510. });
  88511. event.dispose(false);
  88512. return event;
  88513. };
  88514. /**
  88515. * @param {Vector3} origin the origin of the explosion
  88516. * @param {number} radius the explosion radius
  88517. * @param {number} strength the explosion strength
  88518. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  88519. */
  88520. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  88521. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  88522. if (!this._physicsEngine) {
  88523. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  88524. return null;
  88525. }
  88526. var impostors = this._physicsEngine.getImpostors();
  88527. if (impostors.length === 0) {
  88528. return null;
  88529. }
  88530. var event = new PhysicsRadialExplosionEvent(this._scene);
  88531. impostors.forEach(function (impostor) {
  88532. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  88533. if (!impostorForceAndContactPoint) {
  88534. return;
  88535. }
  88536. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88537. });
  88538. event.dispose(false);
  88539. return event;
  88540. };
  88541. /**
  88542. * @param {Vector3} origin the origin of the explosion
  88543. * @param {number} radius the explosion radius
  88544. * @param {number} strength the explosion strength
  88545. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  88546. */
  88547. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  88548. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  88549. if (!this._physicsEngine) {
  88550. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  88551. return null;
  88552. }
  88553. var impostors = this._physicsEngine.getImpostors();
  88554. if (impostors.length === 0) {
  88555. return null;
  88556. }
  88557. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  88558. event.dispose(false);
  88559. return event;
  88560. };
  88561. /**
  88562. * @param {Vector3} origin the origin of the updraft
  88563. * @param {number} radius the radius of the updraft
  88564. * @param {number} strength the strength of the updraft
  88565. * @param {number} height the height of the updraft
  88566. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  88567. */
  88568. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  88569. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  88570. if (!this._physicsEngine) {
  88571. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  88572. return null;
  88573. }
  88574. if (this._physicsEngine.getImpostors().length === 0) {
  88575. return null;
  88576. }
  88577. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  88578. event.dispose(false);
  88579. return event;
  88580. };
  88581. /**
  88582. * @param {Vector3} origin the of the vortex
  88583. * @param {number} radius the radius of the vortex
  88584. * @param {number} strength the strength of the vortex
  88585. * @param {number} height the height of the vortex
  88586. */
  88587. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  88588. if (!this._physicsEngine) {
  88589. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  88590. return null;
  88591. }
  88592. if (this._physicsEngine.getImpostors().length === 0) {
  88593. return null;
  88594. }
  88595. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  88596. event.dispose(false);
  88597. return event;
  88598. };
  88599. return PhysicsHelper;
  88600. }());
  88601. BABYLON.PhysicsHelper = PhysicsHelper;
  88602. /***** Radial explosion *****/
  88603. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  88604. function PhysicsRadialExplosionEvent(scene) {
  88605. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  88606. this._rays = [];
  88607. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  88608. this._scene = scene;
  88609. }
  88610. /**
  88611. * Returns the data related to the radial explosion event (sphere & rays).
  88612. * @returns {PhysicsRadialExplosionEventData}
  88613. */
  88614. PhysicsRadialExplosionEvent.prototype.getData = function () {
  88615. this._dataFetched = true;
  88616. return {
  88617. sphere: this._sphere,
  88618. rays: this._rays,
  88619. };
  88620. };
  88621. /**
  88622. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  88623. * @param impostor
  88624. * @param {Vector3} origin the origin of the explosion
  88625. * @param {number} radius the explosion radius
  88626. * @param {number} strength the explosion strength
  88627. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  88628. * @returns {Nullable<PhysicsForceAndContactPoint>}
  88629. */
  88630. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  88631. if (impostor.mass === 0) {
  88632. return null;
  88633. }
  88634. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  88635. return null;
  88636. }
  88637. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  88638. return null;
  88639. }
  88640. var impostorObjectCenter = impostor.getObjectCenter();
  88641. var direction = impostorObjectCenter.subtract(origin);
  88642. var ray = new BABYLON.Ray(origin, direction, radius);
  88643. this._rays.push(ray);
  88644. var hit = ray.intersectsMesh(impostor.object);
  88645. var contactPoint = hit.pickedPoint;
  88646. if (!contactPoint) {
  88647. return null;
  88648. }
  88649. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  88650. if (distanceFromOrigin > radius) {
  88651. return null;
  88652. }
  88653. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  88654. ? strength
  88655. : strength * (1 - (distanceFromOrigin / radius));
  88656. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  88657. return { force: force, contactPoint: contactPoint };
  88658. };
  88659. /**
  88660. * Disposes the sphere.
  88661. * @param {bolean} force
  88662. */
  88663. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  88664. var _this = this;
  88665. if (force === void 0) { force = true; }
  88666. if (force) {
  88667. this._sphere.dispose();
  88668. }
  88669. else {
  88670. setTimeout(function () {
  88671. if (!_this._dataFetched) {
  88672. _this._sphere.dispose();
  88673. }
  88674. }, 0);
  88675. }
  88676. };
  88677. /*** Helpers ***/
  88678. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  88679. if (!this._sphere) {
  88680. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  88681. this._sphere.isVisible = false;
  88682. }
  88683. };
  88684. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  88685. var impostorObject = impostor.object;
  88686. this._prepareSphere();
  88687. this._sphere.position = origin;
  88688. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  88689. this._sphere._updateBoundingInfo();
  88690. this._sphere.computeWorldMatrix(true);
  88691. return this._sphere.intersectsMesh(impostorObject, true);
  88692. };
  88693. return PhysicsRadialExplosionEvent;
  88694. }());
  88695. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  88696. /***** Gravitational Field *****/
  88697. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  88698. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  88699. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  88700. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  88701. this._physicsHelper = physicsHelper;
  88702. this._scene = scene;
  88703. this._origin = origin;
  88704. this._radius = radius;
  88705. this._strength = strength;
  88706. this._falloff = falloff;
  88707. this._tickCallback = this._tick.bind(this);
  88708. }
  88709. /**
  88710. * Returns the data related to the gravitational field event (sphere).
  88711. * @returns {PhysicsGravitationalFieldEventData}
  88712. */
  88713. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  88714. this._dataFetched = true;
  88715. return {
  88716. sphere: this._sphere,
  88717. };
  88718. };
  88719. /**
  88720. * Enables the gravitational field.
  88721. */
  88722. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  88723. this._tickCallback.call(this);
  88724. this._scene.registerBeforeRender(this._tickCallback);
  88725. };
  88726. /**
  88727. * Disables the gravitational field.
  88728. */
  88729. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  88730. this._scene.unregisterBeforeRender(this._tickCallback);
  88731. };
  88732. /**
  88733. * Disposes the sphere.
  88734. * @param {bolean} force
  88735. */
  88736. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  88737. var _this = this;
  88738. if (force === void 0) { force = true; }
  88739. if (force) {
  88740. this._sphere.dispose();
  88741. }
  88742. else {
  88743. setTimeout(function () {
  88744. if (!_this._dataFetched) {
  88745. _this._sphere.dispose();
  88746. }
  88747. }, 0);
  88748. }
  88749. };
  88750. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  88751. // Since the params won't change, we fetch the event only once
  88752. if (this._sphere) {
  88753. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  88754. }
  88755. else {
  88756. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  88757. if (radialExplosionEvent) {
  88758. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  88759. }
  88760. }
  88761. };
  88762. return PhysicsGravitationalFieldEvent;
  88763. }());
  88764. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  88765. /***** Updraft *****/
  88766. var PhysicsUpdraftEvent = /** @class */ (function () {
  88767. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  88768. this._scene = _scene;
  88769. this._origin = _origin;
  88770. this._radius = _radius;
  88771. this._strength = _strength;
  88772. this._height = _height;
  88773. this._updraftMode = _updraftMode;
  88774. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  88775. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  88776. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  88777. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  88778. this._physicsEngine = this._scene.getPhysicsEngine();
  88779. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  88780. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  88781. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  88782. this._originDirection = this._origin.subtract(this._originTop).normalize();
  88783. }
  88784. this._tickCallback = this._tick.bind(this);
  88785. }
  88786. /**
  88787. * Returns the data related to the updraft event (cylinder).
  88788. * @returns {PhysicsUpdraftEventData}
  88789. */
  88790. PhysicsUpdraftEvent.prototype.getData = function () {
  88791. this._dataFetched = true;
  88792. return {
  88793. cylinder: this._cylinder,
  88794. };
  88795. };
  88796. /**
  88797. * Enables the updraft.
  88798. */
  88799. PhysicsUpdraftEvent.prototype.enable = function () {
  88800. this._tickCallback.call(this);
  88801. this._scene.registerBeforeRender(this._tickCallback);
  88802. };
  88803. /**
  88804. * Disables the cortex.
  88805. */
  88806. PhysicsUpdraftEvent.prototype.disable = function () {
  88807. this._scene.unregisterBeforeRender(this._tickCallback);
  88808. };
  88809. /**
  88810. * Disposes the sphere.
  88811. * @param {bolean} force
  88812. */
  88813. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  88814. var _this = this;
  88815. if (force === void 0) { force = true; }
  88816. if (force) {
  88817. this._cylinder.dispose();
  88818. }
  88819. else {
  88820. setTimeout(function () {
  88821. if (!_this._dataFetched) {
  88822. _this._cylinder.dispose();
  88823. }
  88824. }, 0);
  88825. }
  88826. };
  88827. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  88828. if (impostor.mass === 0) {
  88829. return null;
  88830. }
  88831. if (!this._intersectsWithCylinder(impostor)) {
  88832. return null;
  88833. }
  88834. var impostorObjectCenter = impostor.getObjectCenter();
  88835. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  88836. var direction = this._originDirection;
  88837. }
  88838. else {
  88839. var direction = impostorObjectCenter.subtract(this._originTop);
  88840. }
  88841. var multiplier = this._strength * -1;
  88842. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  88843. return { force: force, contactPoint: impostorObjectCenter };
  88844. };
  88845. PhysicsUpdraftEvent.prototype._tick = function () {
  88846. var _this = this;
  88847. this._physicsEngine.getImpostors().forEach(function (impostor) {
  88848. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  88849. if (!impostorForceAndContactPoint) {
  88850. return;
  88851. }
  88852. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88853. });
  88854. };
  88855. /*** Helpers ***/
  88856. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  88857. if (!this._cylinder) {
  88858. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  88859. height: this._height,
  88860. diameter: this._radius * 2,
  88861. }, this._scene);
  88862. this._cylinder.isVisible = false;
  88863. }
  88864. };
  88865. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  88866. var impostorObject = impostor.object;
  88867. this._prepareCylinder();
  88868. this._cylinder.position = this._cylinderPosition;
  88869. return this._cylinder.intersectsMesh(impostorObject, true);
  88870. };
  88871. return PhysicsUpdraftEvent;
  88872. }());
  88873. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  88874. /***** Vortex *****/
  88875. var PhysicsVortexEvent = /** @class */ (function () {
  88876. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  88877. this._scene = _scene;
  88878. this._origin = _origin;
  88879. this._radius = _radius;
  88880. this._strength = _strength;
  88881. this._height = _height;
  88882. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  88883. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  88884. this._updraftMultiplier = 0.02;
  88885. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  88886. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  88887. this._physicsEngine = this._scene.getPhysicsEngine();
  88888. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  88889. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  88890. this._tickCallback = this._tick.bind(this);
  88891. }
  88892. /**
  88893. * Returns the data related to the vortex event (cylinder).
  88894. * @returns {PhysicsVortexEventData}
  88895. */
  88896. PhysicsVortexEvent.prototype.getData = function () {
  88897. this._dataFetched = true;
  88898. return {
  88899. cylinder: this._cylinder,
  88900. };
  88901. };
  88902. /**
  88903. * Enables the vortex.
  88904. */
  88905. PhysicsVortexEvent.prototype.enable = function () {
  88906. this._tickCallback.call(this);
  88907. this._scene.registerBeforeRender(this._tickCallback);
  88908. };
  88909. /**
  88910. * Disables the cortex.
  88911. */
  88912. PhysicsVortexEvent.prototype.disable = function () {
  88913. this._scene.unregisterBeforeRender(this._tickCallback);
  88914. };
  88915. /**
  88916. * Disposes the sphere.
  88917. * @param {bolean} force
  88918. */
  88919. PhysicsVortexEvent.prototype.dispose = function (force) {
  88920. var _this = this;
  88921. if (force === void 0) { force = true; }
  88922. if (force) {
  88923. this._cylinder.dispose();
  88924. }
  88925. else {
  88926. setTimeout(function () {
  88927. if (!_this._dataFetched) {
  88928. _this._cylinder.dispose();
  88929. }
  88930. }, 0);
  88931. }
  88932. };
  88933. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  88934. if (impostor.mass === 0) {
  88935. return null;
  88936. }
  88937. if (!this._intersectsWithCylinder(impostor)) {
  88938. return null;
  88939. }
  88940. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  88941. return null;
  88942. }
  88943. var impostorObjectCenter = impostor.getObjectCenter();
  88944. 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)
  88945. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  88946. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  88947. var hit = ray.intersectsMesh(impostor.object);
  88948. var contactPoint = hit.pickedPoint;
  88949. if (!contactPoint) {
  88950. return null;
  88951. }
  88952. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  88953. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  88954. var directionToOrigin = contactPoint.normalize();
  88955. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  88956. directionToOrigin = directionToOrigin.negate();
  88957. }
  88958. // TODO: find a more physically based solution
  88959. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  88960. var forceX = directionToOrigin.x * this._strength / 8;
  88961. var forceY = directionToOrigin.y * this._updraftMultiplier;
  88962. var forceZ = directionToOrigin.z * this._strength / 8;
  88963. }
  88964. else {
  88965. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  88966. var forceY = this._originTop.y * this._updraftMultiplier;
  88967. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  88968. }
  88969. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  88970. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  88971. return { force: force, contactPoint: impostorObjectCenter };
  88972. };
  88973. PhysicsVortexEvent.prototype._tick = function () {
  88974. var _this = this;
  88975. this._physicsEngine.getImpostors().forEach(function (impostor) {
  88976. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  88977. if (!impostorForceAndContactPoint) {
  88978. return;
  88979. }
  88980. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88981. });
  88982. };
  88983. /*** Helpers ***/
  88984. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  88985. if (!this._cylinder) {
  88986. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  88987. height: this._height,
  88988. diameter: this._radius * 2,
  88989. }, this._scene);
  88990. this._cylinder.isVisible = false;
  88991. }
  88992. };
  88993. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  88994. var impostorObject = impostor.object;
  88995. this._prepareCylinder();
  88996. this._cylinder.position = this._cylinderPosition;
  88997. return this._cylinder.intersectsMesh(impostorObject, true);
  88998. };
  88999. return PhysicsVortexEvent;
  89000. }());
  89001. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  89002. /***** Enums *****/
  89003. /**
  89004. * The strenght of the force in correspondence to the distance of the affected object
  89005. */
  89006. var PhysicsRadialImpulseFalloff;
  89007. (function (PhysicsRadialImpulseFalloff) {
  89008. /** Defines that impulse is constant in strength across it's whole radius */
  89009. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  89010. /** DEfines that impulse gets weaker if it's further from the origin */
  89011. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  89012. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  89013. /**
  89014. * The strenght of the force in correspondence to the distance of the affected object
  89015. */
  89016. var PhysicsUpdraftMode;
  89017. (function (PhysicsUpdraftMode) {
  89018. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  89019. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  89020. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  89021. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  89022. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  89023. })(BABYLON || (BABYLON = {}));
  89024. //# sourceMappingURL=babylon.physicsHelper.js.map
  89025. var BABYLON;
  89026. (function (BABYLON) {
  89027. var CannonJSPlugin = /** @class */ (function () {
  89028. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  89029. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  89030. if (iterations === void 0) { iterations = 10; }
  89031. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  89032. this.name = "CannonJSPlugin";
  89033. this._physicsMaterials = new Array();
  89034. this._fixedTimeStep = 1 / 60;
  89035. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  89036. this.BJSCANNON = CANNON;
  89037. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  89038. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  89039. this._tmpPosition = BABYLON.Vector3.Zero();
  89040. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  89041. this._tmpUnityRotation = new BABYLON.Quaternion();
  89042. if (!this.isSupported()) {
  89043. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  89044. return;
  89045. }
  89046. this._extendNamespace();
  89047. this.world = new this.BJSCANNON.World();
  89048. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  89049. this.world.solver.iterations = iterations;
  89050. }
  89051. CannonJSPlugin.prototype.setGravity = function (gravity) {
  89052. this.world.gravity.copy(gravity);
  89053. };
  89054. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  89055. this._fixedTimeStep = timeStep;
  89056. };
  89057. CannonJSPlugin.prototype.getTimeStep = function () {
  89058. return this._fixedTimeStep;
  89059. };
  89060. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  89061. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  89062. };
  89063. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  89064. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  89065. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  89066. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  89067. };
  89068. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  89069. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  89070. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  89071. impostor.physicsBody.applyForce(impulse, worldPoint);
  89072. };
  89073. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  89074. //parent-child relationship. Does this impostor has a parent impostor?
  89075. if (impostor.parent) {
  89076. if (impostor.physicsBody) {
  89077. this.removePhysicsBody(impostor);
  89078. //TODO is that needed?
  89079. impostor.forceUpdate();
  89080. }
  89081. return;
  89082. }
  89083. //should a new body be created for this impostor?
  89084. if (impostor.isBodyInitRequired()) {
  89085. var shape = this._createShape(impostor);
  89086. //unregister events, if body is being changed
  89087. var oldBody = impostor.physicsBody;
  89088. if (oldBody) {
  89089. this.removePhysicsBody(impostor);
  89090. }
  89091. //create the body and material
  89092. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  89093. var bodyCreationObject = {
  89094. mass: impostor.getParam("mass"),
  89095. material: material
  89096. };
  89097. // A simple extend, in case native options were used.
  89098. var nativeOptions = impostor.getParam("nativeOptions");
  89099. for (var key in nativeOptions) {
  89100. if (nativeOptions.hasOwnProperty(key)) {
  89101. bodyCreationObject[key] = nativeOptions[key];
  89102. }
  89103. }
  89104. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  89105. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  89106. this.world.addEventListener("preStep", impostor.beforeStep);
  89107. this.world.addEventListener("postStep", impostor.afterStep);
  89108. impostor.physicsBody.addShape(shape);
  89109. this.world.add(impostor.physicsBody);
  89110. //try to keep the body moving in the right direction by taking old properties.
  89111. //Should be tested!
  89112. if (oldBody) {
  89113. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  89114. impostor.physicsBody[param].copy(oldBody[param]);
  89115. });
  89116. }
  89117. this._processChildMeshes(impostor);
  89118. }
  89119. //now update the body's transformation
  89120. this._updatePhysicsBodyTransformation(impostor);
  89121. };
  89122. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  89123. var _this = this;
  89124. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  89125. var currentRotation = mainImpostor.object.rotationQuaternion;
  89126. if (meshChildren.length) {
  89127. var processMesh = function (localPosition, mesh) {
  89128. if (!currentRotation || !mesh.rotationQuaternion) {
  89129. return;
  89130. }
  89131. var childImpostor = mesh.getPhysicsImpostor();
  89132. if (childImpostor) {
  89133. var parent = childImpostor.parent;
  89134. if (parent !== mainImpostor) {
  89135. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  89136. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  89137. if (childImpostor.physicsBody) {
  89138. _this.removePhysicsBody(childImpostor);
  89139. childImpostor.physicsBody = null;
  89140. }
  89141. childImpostor.parent = mainImpostor;
  89142. childImpostor.resetUpdateFlags();
  89143. 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));
  89144. //Add the mass of the children.
  89145. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  89146. }
  89147. }
  89148. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  89149. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  89150. };
  89151. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  89152. }
  89153. };
  89154. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  89155. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  89156. this.world.removeEventListener("preStep", impostor.beforeStep);
  89157. this.world.removeEventListener("postStep", impostor.afterStep);
  89158. this.world.remove(impostor.physicsBody);
  89159. };
  89160. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  89161. var mainBody = impostorJoint.mainImpostor.physicsBody;
  89162. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  89163. if (!mainBody || !connectedBody) {
  89164. return;
  89165. }
  89166. var constraint;
  89167. var jointData = impostorJoint.joint.jointData;
  89168. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  89169. var constraintData = {
  89170. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  89171. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  89172. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  89173. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  89174. maxForce: jointData.nativeParams.maxForce,
  89175. collideConnected: !!jointData.collision
  89176. };
  89177. switch (impostorJoint.joint.type) {
  89178. case BABYLON.PhysicsJoint.HingeJoint:
  89179. case BABYLON.PhysicsJoint.Hinge2Joint:
  89180. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  89181. break;
  89182. case BABYLON.PhysicsJoint.DistanceJoint:
  89183. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  89184. break;
  89185. case BABYLON.PhysicsJoint.SpringJoint:
  89186. var springData = jointData;
  89187. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  89188. restLength: springData.length,
  89189. stiffness: springData.stiffness,
  89190. damping: springData.damping,
  89191. localAnchorA: constraintData.pivotA,
  89192. localAnchorB: constraintData.pivotB
  89193. });
  89194. break;
  89195. case BABYLON.PhysicsJoint.LockJoint:
  89196. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  89197. break;
  89198. case BABYLON.PhysicsJoint.PointToPointJoint:
  89199. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  89200. default:
  89201. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  89202. break;
  89203. }
  89204. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  89205. constraint.collideConnected = !!jointData.collision;
  89206. impostorJoint.joint.physicsJoint = constraint;
  89207. //don't add spring as constraint, as it is not one.
  89208. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  89209. this.world.addConstraint(constraint);
  89210. }
  89211. else {
  89212. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  89213. constraint.applyForce();
  89214. };
  89215. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  89216. }
  89217. };
  89218. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  89219. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  89220. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  89221. }
  89222. else {
  89223. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  89224. }
  89225. };
  89226. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  89227. var index;
  89228. var mat;
  89229. for (index = 0; index < this._physicsMaterials.length; index++) {
  89230. mat = this._physicsMaterials[index];
  89231. if (mat.friction === friction && mat.restitution === restitution) {
  89232. return mat;
  89233. }
  89234. }
  89235. var currentMat = new this.BJSCANNON.Material(name);
  89236. currentMat.friction = friction;
  89237. currentMat.restitution = restitution;
  89238. this._physicsMaterials.push(currentMat);
  89239. return currentMat;
  89240. };
  89241. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  89242. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  89243. };
  89244. CannonJSPlugin.prototype._createShape = function (impostor) {
  89245. var object = impostor.object;
  89246. var returnValue;
  89247. var extendSize = impostor.getObjectExtendSize();
  89248. switch (impostor.type) {
  89249. case BABYLON.PhysicsImpostor.SphereImpostor:
  89250. var radiusX = extendSize.x;
  89251. var radiusY = extendSize.y;
  89252. var radiusZ = extendSize.z;
  89253. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  89254. break;
  89255. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  89256. case BABYLON.PhysicsImpostor.CylinderImpostor:
  89257. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  89258. break;
  89259. case BABYLON.PhysicsImpostor.BoxImpostor:
  89260. var box = extendSize.scale(0.5);
  89261. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  89262. break;
  89263. case BABYLON.PhysicsImpostor.PlaneImpostor:
  89264. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  89265. returnValue = new this.BJSCANNON.Plane();
  89266. break;
  89267. case BABYLON.PhysicsImpostor.MeshImpostor:
  89268. // should transform the vertex data to world coordinates!!
  89269. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  89270. var rawFaces = object.getIndices ? object.getIndices() : [];
  89271. if (!rawVerts)
  89272. return;
  89273. // get only scale! so the object could transform correctly.
  89274. var oldPosition = object.position.clone();
  89275. var oldRotation = object.rotation && object.rotation.clone();
  89276. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  89277. object.position.copyFromFloats(0, 0, 0);
  89278. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  89279. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  89280. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  89281. var transform = object.computeWorldMatrix(true);
  89282. // convert rawVerts to object space
  89283. var temp = new Array();
  89284. var index;
  89285. for (index = 0; index < rawVerts.length; index += 3) {
  89286. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  89287. }
  89288. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  89289. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  89290. //now set back the transformation!
  89291. object.position.copyFrom(oldPosition);
  89292. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  89293. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  89294. break;
  89295. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  89296. var oldPosition2 = object.position.clone();
  89297. var oldRotation2 = object.rotation && object.rotation.clone();
  89298. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  89299. object.position.copyFromFloats(0, 0, 0);
  89300. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  89301. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  89302. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  89303. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  89304. returnValue = this._createHeightmap(object);
  89305. object.position.copyFrom(oldPosition2);
  89306. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  89307. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  89308. object.computeWorldMatrix(true);
  89309. break;
  89310. case BABYLON.PhysicsImpostor.ParticleImpostor:
  89311. returnValue = new this.BJSCANNON.Particle();
  89312. break;
  89313. }
  89314. return returnValue;
  89315. };
  89316. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  89317. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  89318. var transform = object.computeWorldMatrix(true);
  89319. // convert rawVerts to object space
  89320. var temp = new Array();
  89321. var index;
  89322. for (index = 0; index < pos.length; index += 3) {
  89323. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  89324. }
  89325. pos = temp;
  89326. var matrix = new Array();
  89327. //For now pointDepth will not be used and will be automatically calculated.
  89328. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  89329. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  89330. var boundingInfo = object.getBoundingInfo();
  89331. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  89332. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  89333. var elementSize = dim * 2 / arraySize;
  89334. for (var i = 0; i < pos.length; i = i + 3) {
  89335. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  89336. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  89337. var y = -pos[i + 2] + minY;
  89338. if (!matrix[x]) {
  89339. matrix[x] = [];
  89340. }
  89341. if (!matrix[x][z]) {
  89342. matrix[x][z] = y;
  89343. }
  89344. matrix[x][z] = Math.max(y, matrix[x][z]);
  89345. }
  89346. for (var x = 0; x <= arraySize; ++x) {
  89347. if (!matrix[x]) {
  89348. var loc = 1;
  89349. while (!matrix[(x + loc) % arraySize]) {
  89350. loc++;
  89351. }
  89352. matrix[x] = matrix[(x + loc) % arraySize].slice();
  89353. //console.log("missing x", x);
  89354. }
  89355. for (var z = 0; z <= arraySize; ++z) {
  89356. if (!matrix[x][z]) {
  89357. var loc = 1;
  89358. var newValue;
  89359. while (newValue === undefined) {
  89360. newValue = matrix[x][(z + loc++) % arraySize];
  89361. }
  89362. matrix[x][z] = newValue;
  89363. }
  89364. }
  89365. }
  89366. var shape = new this.BJSCANNON.Heightfield(matrix, {
  89367. elementSize: elementSize
  89368. });
  89369. //For future reference, needed for body transformation
  89370. shape.minY = minY;
  89371. return shape;
  89372. };
  89373. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  89374. var object = impostor.object;
  89375. //make sure it is updated...
  89376. object.computeWorldMatrix && object.computeWorldMatrix(true);
  89377. // The delta between the mesh position and the mesh bounding box center
  89378. var bInfo = object.getBoundingInfo();
  89379. if (!bInfo)
  89380. return;
  89381. var center = impostor.getObjectCenter();
  89382. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  89383. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  89384. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  89385. this._tmpPosition.copyFrom(center);
  89386. var quaternion = object.rotationQuaternion;
  89387. if (!quaternion) {
  89388. return;
  89389. }
  89390. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  89391. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  89392. //-90 DEG in X, precalculated
  89393. quaternion = quaternion.multiply(this._minus90X);
  89394. //Invert! (Precalculated, 90 deg in X)
  89395. //No need to clone. this will never change.
  89396. impostor.setDeltaRotation(this._plus90X);
  89397. }
  89398. //If it is a heightfield, if should be centered.
  89399. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  89400. var mesh = object;
  89401. var boundingInfo = mesh.getBoundingInfo();
  89402. //calculate the correct body position:
  89403. var rotationQuaternion = mesh.rotationQuaternion;
  89404. mesh.rotationQuaternion = this._tmpUnityRotation;
  89405. mesh.computeWorldMatrix(true);
  89406. //get original center with no rotation
  89407. var c = center.clone();
  89408. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  89409. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  89410. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  89411. mesh.setPreTransformMatrix(p);
  89412. mesh.computeWorldMatrix(true);
  89413. //calculate the translation
  89414. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  89415. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  89416. //add it inverted to the delta
  89417. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  89418. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  89419. //rotation is back
  89420. mesh.rotationQuaternion = rotationQuaternion;
  89421. mesh.setPreTransformMatrix(oldPivot);
  89422. mesh.computeWorldMatrix(true);
  89423. }
  89424. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  89425. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  89426. //this._tmpPosition.copyFrom(object.position);
  89427. }
  89428. impostor.setDeltaPosition(this._tmpDeltaPosition);
  89429. //Now update the impostor object
  89430. impostor.physicsBody.position.copy(this._tmpPosition);
  89431. impostor.physicsBody.quaternion.copy(quaternion);
  89432. };
  89433. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  89434. impostor.object.position.copyFrom(impostor.physicsBody.position);
  89435. if (impostor.object.rotationQuaternion) {
  89436. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  89437. }
  89438. };
  89439. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  89440. impostor.physicsBody.position.copy(newPosition);
  89441. impostor.physicsBody.quaternion.copy(newRotation);
  89442. };
  89443. CannonJSPlugin.prototype.isSupported = function () {
  89444. return this.BJSCANNON !== undefined;
  89445. };
  89446. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  89447. impostor.physicsBody.velocity.copy(velocity);
  89448. };
  89449. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  89450. impostor.physicsBody.angularVelocity.copy(velocity);
  89451. };
  89452. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  89453. var v = impostor.physicsBody.velocity;
  89454. if (!v) {
  89455. return null;
  89456. }
  89457. return new BABYLON.Vector3(v.x, v.y, v.z);
  89458. };
  89459. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  89460. var v = impostor.physicsBody.angularVelocity;
  89461. if (!v) {
  89462. return null;
  89463. }
  89464. return new BABYLON.Vector3(v.x, v.y, v.z);
  89465. };
  89466. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  89467. impostor.physicsBody.mass = mass;
  89468. impostor.physicsBody.updateMassProperties();
  89469. };
  89470. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  89471. return impostor.physicsBody.mass;
  89472. };
  89473. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  89474. return impostor.physicsBody.material.friction;
  89475. };
  89476. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  89477. impostor.physicsBody.material.friction = friction;
  89478. };
  89479. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  89480. return impostor.physicsBody.material.restitution;
  89481. };
  89482. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  89483. impostor.physicsBody.material.restitution = restitution;
  89484. };
  89485. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  89486. impostor.physicsBody.sleep();
  89487. };
  89488. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  89489. impostor.physicsBody.wakeUp();
  89490. };
  89491. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  89492. joint.physicsJoint.distance = maxDistance;
  89493. };
  89494. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  89495. // if (!motorIndex) {
  89496. // joint.physicsJoint.enableMotor();
  89497. // }
  89498. // }
  89499. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  89500. // if (!motorIndex) {
  89501. // joint.physicsJoint.disableMotor();
  89502. // }
  89503. // }
  89504. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  89505. if (!motorIndex) {
  89506. joint.physicsJoint.enableMotor();
  89507. joint.physicsJoint.setMotorSpeed(speed);
  89508. if (maxForce) {
  89509. this.setLimit(joint, maxForce);
  89510. }
  89511. }
  89512. };
  89513. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  89514. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  89515. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  89516. };
  89517. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  89518. var body = impostor.physicsBody;
  89519. mesh.position.x = body.position.x;
  89520. mesh.position.y = body.position.y;
  89521. mesh.position.z = body.position.z;
  89522. if (mesh.rotationQuaternion) {
  89523. mesh.rotationQuaternion.x = body.quaternion.x;
  89524. mesh.rotationQuaternion.y = body.quaternion.y;
  89525. mesh.rotationQuaternion.z = body.quaternion.z;
  89526. mesh.rotationQuaternion.w = body.quaternion.w;
  89527. }
  89528. };
  89529. CannonJSPlugin.prototype.getRadius = function (impostor) {
  89530. var shape = impostor.physicsBody.shapes[0];
  89531. return shape.boundingSphereRadius;
  89532. };
  89533. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  89534. var shape = impostor.physicsBody.shapes[0];
  89535. result.x = shape.halfExtents.x * 2;
  89536. result.y = shape.halfExtents.y * 2;
  89537. result.z = shape.halfExtents.z * 2;
  89538. };
  89539. CannonJSPlugin.prototype.dispose = function () {
  89540. };
  89541. CannonJSPlugin.prototype._extendNamespace = function () {
  89542. //this will force cannon to execute at least one step when using interpolation
  89543. var step_tmp1 = new this.BJSCANNON.Vec3();
  89544. var Engine = this.BJSCANNON;
  89545. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  89546. maxSubSteps = maxSubSteps || 10;
  89547. timeSinceLastCalled = timeSinceLastCalled || 0;
  89548. if (timeSinceLastCalled === 0) {
  89549. this.internalStep(dt);
  89550. this.time += dt;
  89551. }
  89552. else {
  89553. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  89554. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  89555. var t0 = performance.now();
  89556. for (var i = 0; i !== internalSteps; i++) {
  89557. this.internalStep(dt);
  89558. if (performance.now() - t0 > dt * 1000) {
  89559. break;
  89560. }
  89561. }
  89562. this.time += timeSinceLastCalled;
  89563. var h = this.time % dt;
  89564. var h_div_dt = h / dt;
  89565. var interpvelo = step_tmp1;
  89566. var bodies = this.bodies;
  89567. for (var j = 0; j !== bodies.length; j++) {
  89568. var b = bodies[j];
  89569. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  89570. b.position.vsub(b.previousPosition, interpvelo);
  89571. interpvelo.scale(h_div_dt, interpvelo);
  89572. b.position.vadd(interpvelo, b.interpolatedPosition);
  89573. }
  89574. else {
  89575. b.interpolatedPosition.copy(b.position);
  89576. b.interpolatedQuaternion.copy(b.quaternion);
  89577. }
  89578. }
  89579. }
  89580. };
  89581. };
  89582. return CannonJSPlugin;
  89583. }());
  89584. BABYLON.CannonJSPlugin = CannonJSPlugin;
  89585. })(BABYLON || (BABYLON = {}));
  89586. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  89587. var BABYLON;
  89588. (function (BABYLON) {
  89589. var OimoJSPlugin = /** @class */ (function () {
  89590. function OimoJSPlugin(iterations) {
  89591. this.name = "OimoJSPlugin";
  89592. this._tmpImpostorsArray = [];
  89593. this._tmpPositionVector = BABYLON.Vector3.Zero();
  89594. this.BJSOIMO = OIMO;
  89595. this.world = new this.BJSOIMO.World({
  89596. iterations: iterations
  89597. });
  89598. this.world.clear();
  89599. }
  89600. OimoJSPlugin.prototype.setGravity = function (gravity) {
  89601. this.world.gravity.copy(gravity);
  89602. };
  89603. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  89604. this.world.timeStep = timeStep;
  89605. };
  89606. OimoJSPlugin.prototype.getTimeStep = function () {
  89607. return this.world.timeStep;
  89608. };
  89609. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  89610. var _this = this;
  89611. impostors.forEach(function (impostor) {
  89612. impostor.beforeStep();
  89613. });
  89614. this.world.step();
  89615. impostors.forEach(function (impostor) {
  89616. impostor.afterStep();
  89617. //update the ordered impostors array
  89618. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  89619. });
  89620. //check for collisions
  89621. var contact = this.world.contacts;
  89622. while (contact !== null) {
  89623. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  89624. contact = contact.next;
  89625. continue;
  89626. }
  89627. //is this body colliding with any other? get the impostor
  89628. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  89629. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  89630. if (!mainImpostor || !collidingImpostor) {
  89631. contact = contact.next;
  89632. continue;
  89633. }
  89634. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  89635. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  89636. contact = contact.next;
  89637. }
  89638. };
  89639. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  89640. var mass = impostor.physicsBody.mass;
  89641. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  89642. };
  89643. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  89644. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  89645. this.applyImpulse(impostor, force, contactPoint);
  89646. };
  89647. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  89648. var _this = this;
  89649. //parent-child relationship. Does this impostor has a parent impostor?
  89650. if (impostor.parent) {
  89651. if (impostor.physicsBody) {
  89652. this.removePhysicsBody(impostor);
  89653. //TODO is that needed?
  89654. impostor.forceUpdate();
  89655. }
  89656. return;
  89657. }
  89658. if (impostor.isBodyInitRequired()) {
  89659. var bodyConfig = {
  89660. name: impostor.uniqueId,
  89661. //Oimo must have mass, also for static objects.
  89662. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  89663. size: [],
  89664. type: [],
  89665. pos: [],
  89666. posShape: [],
  89667. rot: [],
  89668. rotShape: [],
  89669. move: impostor.getParam("mass") !== 0,
  89670. density: impostor.getParam("mass"),
  89671. friction: impostor.getParam("friction"),
  89672. restitution: impostor.getParam("restitution"),
  89673. //Supporting older versions of Oimo
  89674. world: this.world
  89675. };
  89676. var impostors = [impostor];
  89677. var addToArray = function (parent) {
  89678. if (!parent.getChildMeshes)
  89679. return;
  89680. parent.getChildMeshes().forEach(function (m) {
  89681. if (m.physicsImpostor) {
  89682. impostors.push(m.physicsImpostor);
  89683. //m.physicsImpostor._init();
  89684. }
  89685. });
  89686. };
  89687. addToArray(impostor.object);
  89688. var checkWithEpsilon_1 = function (value) {
  89689. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  89690. };
  89691. var globalQuaternion_1 = new BABYLON.Quaternion();
  89692. impostors.forEach(function (i) {
  89693. if (!i.object.rotationQuaternion) {
  89694. return;
  89695. }
  89696. //get the correct bounding box
  89697. var oldQuaternion = i.object.rotationQuaternion;
  89698. globalQuaternion_1 = oldQuaternion.clone();
  89699. var rot = oldQuaternion.toEulerAngles();
  89700. var extendSize = i.getObjectExtendSize();
  89701. var radToDeg = 57.295779513082320876;
  89702. if (i === impostor) {
  89703. var center = impostor.getObjectCenter();
  89704. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  89705. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  89706. //Can also use Array.prototype.push.apply
  89707. bodyConfig.pos.push(center.x);
  89708. bodyConfig.pos.push(center.y);
  89709. bodyConfig.pos.push(center.z);
  89710. bodyConfig.posShape.push(0, 0, 0);
  89711. //tmp solution
  89712. bodyConfig.rot.push(0);
  89713. bodyConfig.rot.push(0);
  89714. bodyConfig.rot.push(0);
  89715. bodyConfig.rotShape.push(0, 0, 0);
  89716. }
  89717. else {
  89718. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  89719. bodyConfig.posShape.push(localPosition.x);
  89720. bodyConfig.posShape.push(localPosition.y);
  89721. bodyConfig.posShape.push(localPosition.z);
  89722. bodyConfig.pos.push(0, 0, 0);
  89723. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  89724. bodyConfig.rot.push(0);
  89725. bodyConfig.rot.push(0);
  89726. bodyConfig.rot.push(0);
  89727. bodyConfig.rotShape.push(rot.x * radToDeg);
  89728. bodyConfig.rotShape.push(rot.y * radToDeg);
  89729. bodyConfig.rotShape.push(rot.z * radToDeg);
  89730. }
  89731. // register mesh
  89732. switch (i.type) {
  89733. case BABYLON.PhysicsImpostor.ParticleImpostor:
  89734. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  89735. case BABYLON.PhysicsImpostor.SphereImpostor:
  89736. var radiusX = extendSize.x;
  89737. var radiusY = extendSize.y;
  89738. var radiusZ = extendSize.z;
  89739. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  89740. bodyConfig.type.push('sphere');
  89741. //due to the way oimo works with compounds, add 3 times
  89742. bodyConfig.size.push(size);
  89743. bodyConfig.size.push(size);
  89744. bodyConfig.size.push(size);
  89745. break;
  89746. case BABYLON.PhysicsImpostor.CylinderImpostor:
  89747. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  89748. var sizeY = checkWithEpsilon_1(extendSize.y);
  89749. bodyConfig.type.push('cylinder');
  89750. bodyConfig.size.push(sizeX);
  89751. bodyConfig.size.push(sizeY);
  89752. //due to the way oimo works with compounds, add one more value.
  89753. bodyConfig.size.push(sizeY);
  89754. break;
  89755. case BABYLON.PhysicsImpostor.PlaneImpostor:
  89756. case BABYLON.PhysicsImpostor.BoxImpostor:
  89757. default:
  89758. var sizeX = checkWithEpsilon_1(extendSize.x);
  89759. var sizeY = checkWithEpsilon_1(extendSize.y);
  89760. var sizeZ = checkWithEpsilon_1(extendSize.z);
  89761. bodyConfig.type.push('box');
  89762. //if (i === impostor) {
  89763. bodyConfig.size.push(sizeX);
  89764. bodyConfig.size.push(sizeY);
  89765. bodyConfig.size.push(sizeZ);
  89766. //} else {
  89767. // bodyConfig.size.push(0,0,0);
  89768. //}
  89769. break;
  89770. }
  89771. //actually not needed, but hey...
  89772. i.object.rotationQuaternion = oldQuaternion;
  89773. });
  89774. impostor.physicsBody = this.world.add(bodyConfig);
  89775. // set the quaternion, ignoring the previously defined (euler) rotation
  89776. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  89777. // update with delta 0, so the body will reveive the new rotation.
  89778. impostor.physicsBody.updatePosition(0);
  89779. }
  89780. else {
  89781. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  89782. }
  89783. impostor.setDeltaPosition(this._tmpPositionVector);
  89784. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  89785. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  89786. };
  89787. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  89788. //impostor.physicsBody.dispose();
  89789. //Same as : (older oimo versions)
  89790. this.world.removeRigidBody(impostor.physicsBody);
  89791. };
  89792. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  89793. var mainBody = impostorJoint.mainImpostor.physicsBody;
  89794. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  89795. if (!mainBody || !connectedBody) {
  89796. return;
  89797. }
  89798. var jointData = impostorJoint.joint.jointData;
  89799. var options = jointData.nativeParams || {};
  89800. var type;
  89801. var nativeJointData = {
  89802. body1: mainBody,
  89803. body2: connectedBody,
  89804. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  89805. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  89806. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  89807. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  89808. min: options.min,
  89809. max: options.max,
  89810. collision: options.collision || jointData.collision,
  89811. spring: options.spring,
  89812. //supporting older version of Oimo
  89813. world: this.world
  89814. };
  89815. switch (impostorJoint.joint.type) {
  89816. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  89817. type = "jointBall";
  89818. break;
  89819. case BABYLON.PhysicsJoint.SpringJoint:
  89820. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  89821. var springData = jointData;
  89822. nativeJointData.min = springData.length || nativeJointData.min;
  89823. //Max should also be set, just make sure it is at least min
  89824. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  89825. case BABYLON.PhysicsJoint.DistanceJoint:
  89826. type = "jointDistance";
  89827. nativeJointData.max = jointData.maxDistance;
  89828. break;
  89829. case BABYLON.PhysicsJoint.PrismaticJoint:
  89830. type = "jointPrisme";
  89831. break;
  89832. case BABYLON.PhysicsJoint.SliderJoint:
  89833. type = "jointSlide";
  89834. break;
  89835. case BABYLON.PhysicsJoint.WheelJoint:
  89836. type = "jointWheel";
  89837. break;
  89838. case BABYLON.PhysicsJoint.HingeJoint:
  89839. default:
  89840. type = "jointHinge";
  89841. break;
  89842. }
  89843. nativeJointData.type = type;
  89844. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  89845. };
  89846. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  89847. //Bug in Oimo prevents us from disposing a joint in the playground
  89848. //joint.joint.physicsJoint.dispose();
  89849. //So we will bruteforce it!
  89850. try {
  89851. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  89852. }
  89853. catch (e) {
  89854. BABYLON.Tools.Warn(e);
  89855. }
  89856. };
  89857. OimoJSPlugin.prototype.isSupported = function () {
  89858. return this.BJSOIMO !== undefined;
  89859. };
  89860. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  89861. if (!impostor.physicsBody.sleeping) {
  89862. //TODO check that
  89863. /*if (impostor.physicsBody.shapes.next) {
  89864. var parentShape = this._getLastShape(impostor.physicsBody);
  89865. impostor.object.position.copyFrom(parentShape.position);
  89866. console.log(parentShape.position);
  89867. } else {*/
  89868. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  89869. //}
  89870. if (impostor.object.rotationQuaternion) {
  89871. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  89872. }
  89873. }
  89874. };
  89875. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  89876. var body = impostor.physicsBody;
  89877. body.position.copy(newPosition);
  89878. body.orientation.copy(newRotation);
  89879. body.syncShapes();
  89880. body.awake();
  89881. };
  89882. /*private _getLastShape(body: any): any {
  89883. var lastShape = body.shapes;
  89884. while (lastShape.next) {
  89885. lastShape = lastShape.next;
  89886. }
  89887. return lastShape;
  89888. }*/
  89889. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  89890. impostor.physicsBody.linearVelocity.copy(velocity);
  89891. };
  89892. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  89893. impostor.physicsBody.angularVelocity.copy(velocity);
  89894. };
  89895. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  89896. var v = impostor.physicsBody.linearVelocity;
  89897. if (!v) {
  89898. return null;
  89899. }
  89900. return new BABYLON.Vector3(v.x, v.y, v.z);
  89901. };
  89902. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  89903. var v = impostor.physicsBody.angularVelocity;
  89904. if (!v) {
  89905. return null;
  89906. }
  89907. return new BABYLON.Vector3(v.x, v.y, v.z);
  89908. };
  89909. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  89910. var staticBody = mass === 0;
  89911. //this will actually set the body's density and not its mass.
  89912. //But this is how oimo treats the mass variable.
  89913. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  89914. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  89915. };
  89916. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  89917. return impostor.physicsBody.shapes.density;
  89918. };
  89919. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  89920. return impostor.physicsBody.shapes.friction;
  89921. };
  89922. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  89923. impostor.physicsBody.shapes.friction = friction;
  89924. };
  89925. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  89926. return impostor.physicsBody.shapes.restitution;
  89927. };
  89928. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  89929. impostor.physicsBody.shapes.restitution = restitution;
  89930. };
  89931. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  89932. impostor.physicsBody.sleep();
  89933. };
  89934. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  89935. impostor.physicsBody.awake();
  89936. };
  89937. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  89938. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  89939. if (minDistance !== void 0) {
  89940. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  89941. }
  89942. };
  89943. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  89944. //TODO separate rotational and transational motors.
  89945. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  89946. if (motor) {
  89947. motor.setMotor(speed, maxForce);
  89948. }
  89949. };
  89950. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  89951. //TODO separate rotational and transational motors.
  89952. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  89953. if (motor) {
  89954. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  89955. }
  89956. };
  89957. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  89958. var body = impostor.physicsBody;
  89959. mesh.position.x = body.position.x;
  89960. mesh.position.y = body.position.y;
  89961. mesh.position.z = body.position.z;
  89962. if (mesh.rotationQuaternion) {
  89963. mesh.rotationQuaternion.x = body.orientation.x;
  89964. mesh.rotationQuaternion.y = body.orientation.y;
  89965. mesh.rotationQuaternion.z = body.orientation.z;
  89966. mesh.rotationQuaternion.w = body.orientation.s;
  89967. }
  89968. };
  89969. OimoJSPlugin.prototype.getRadius = function (impostor) {
  89970. return impostor.physicsBody.shapes.radius;
  89971. };
  89972. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  89973. var shape = impostor.physicsBody.shapes;
  89974. result.x = shape.halfWidth * 2;
  89975. result.y = shape.halfHeight * 2;
  89976. result.z = shape.halfDepth * 2;
  89977. };
  89978. OimoJSPlugin.prototype.dispose = function () {
  89979. this.world.clear();
  89980. };
  89981. return OimoJSPlugin;
  89982. }());
  89983. BABYLON.OimoJSPlugin = OimoJSPlugin;
  89984. })(BABYLON || (BABYLON = {}));
  89985. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  89986. var BABYLON;
  89987. (function (BABYLON) {
  89988. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  89989. // All values and structures referenced from:
  89990. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  89991. var DDS_MAGIC = 0x20534444;
  89992. var
  89993. //DDSD_CAPS = 0x1,
  89994. //DDSD_HEIGHT = 0x2,
  89995. //DDSD_WIDTH = 0x4,
  89996. //DDSD_PITCH = 0x8,
  89997. //DDSD_PIXELFORMAT = 0x1000,
  89998. DDSD_MIPMAPCOUNT = 0x20000;
  89999. //DDSD_LINEARSIZE = 0x80000,
  90000. //DDSD_DEPTH = 0x800000;
  90001. // var DDSCAPS_COMPLEX = 0x8,
  90002. // DDSCAPS_MIPMAP = 0x400000,
  90003. // DDSCAPS_TEXTURE = 0x1000;
  90004. var DDSCAPS2_CUBEMAP = 0x200;
  90005. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  90006. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  90007. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  90008. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  90009. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  90010. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  90011. // DDSCAPS2_VOLUME = 0x200000;
  90012. var
  90013. //DDPF_ALPHAPIXELS = 0x1,
  90014. //DDPF_ALPHA = 0x2,
  90015. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  90016. //DDPF_YUV = 0x200,
  90017. DDPF_LUMINANCE = 0x20000;
  90018. function FourCCToInt32(value) {
  90019. return value.charCodeAt(0) +
  90020. (value.charCodeAt(1) << 8) +
  90021. (value.charCodeAt(2) << 16) +
  90022. (value.charCodeAt(3) << 24);
  90023. }
  90024. function Int32ToFourCC(value) {
  90025. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  90026. }
  90027. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  90028. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  90029. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  90030. var FOURCC_DX10 = FourCCToInt32("DX10");
  90031. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  90032. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  90033. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  90034. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  90035. var headerLengthInt = 31; // The header length in 32 bit ints
  90036. // Offsets into the header array
  90037. var off_magic = 0;
  90038. var off_size = 1;
  90039. var off_flags = 2;
  90040. var off_height = 3;
  90041. var off_width = 4;
  90042. var off_mipmapCount = 7;
  90043. var off_pfFlags = 20;
  90044. var off_pfFourCC = 21;
  90045. var off_RGBbpp = 22;
  90046. var off_RMask = 23;
  90047. var off_GMask = 24;
  90048. var off_BMask = 25;
  90049. var off_AMask = 26;
  90050. // var off_caps1 = 27;
  90051. var off_caps2 = 28;
  90052. // var off_caps3 = 29;
  90053. // var off_caps4 = 30;
  90054. var off_dxgiFormat = 32;
  90055. ;
  90056. var DDSTools = /** @class */ (function () {
  90057. function DDSTools() {
  90058. }
  90059. DDSTools.GetDDSInfo = function (arrayBuffer) {
  90060. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  90061. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  90062. var mipmapCount = 1;
  90063. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  90064. mipmapCount = Math.max(1, header[off_mipmapCount]);
  90065. }
  90066. var fourCC = header[off_pfFourCC];
  90067. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  90068. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90069. switch (fourCC) {
  90070. case FOURCC_D3DFMT_R16G16B16A16F:
  90071. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90072. break;
  90073. case FOURCC_D3DFMT_R32G32B32A32F:
  90074. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90075. break;
  90076. case FOURCC_DX10:
  90077. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  90078. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90079. break;
  90080. }
  90081. }
  90082. return {
  90083. width: header[off_width],
  90084. height: header[off_height],
  90085. mipmapCount: mipmapCount,
  90086. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  90087. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  90088. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  90089. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  90090. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  90091. dxgiFormat: dxgiFormat,
  90092. textureType: textureType
  90093. };
  90094. };
  90095. DDSTools._ToHalfFloat = function (value) {
  90096. if (!DDSTools._FloatView) {
  90097. DDSTools._FloatView = new Float32Array(1);
  90098. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  90099. }
  90100. DDSTools._FloatView[0] = value;
  90101. var x = DDSTools._Int32View[0];
  90102. var bits = (x >> 16) & 0x8000; /* Get the sign */
  90103. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  90104. var e = (x >> 23) & 0xff; /* Using int is faster here */
  90105. /* If zero, or denormal, or exponent underflows too much for a denormal
  90106. * half, return signed zero. */
  90107. if (e < 103) {
  90108. return bits;
  90109. }
  90110. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  90111. if (e > 142) {
  90112. bits |= 0x7c00;
  90113. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  90114. * not Inf, so make sure we set one mantissa bit too. */
  90115. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  90116. return bits;
  90117. }
  90118. /* If exponent underflows but not too much, return a denormal */
  90119. if (e < 113) {
  90120. m |= 0x0800;
  90121. /* Extra rounding may overflow and set mantissa to 0 and exponent
  90122. * to 1, which is OK. */
  90123. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  90124. return bits;
  90125. }
  90126. bits |= ((e - 112) << 10) | (m >> 1);
  90127. bits += m & 1;
  90128. return bits;
  90129. };
  90130. DDSTools._FromHalfFloat = function (value) {
  90131. var s = (value & 0x8000) >> 15;
  90132. var e = (value & 0x7C00) >> 10;
  90133. var f = value & 0x03FF;
  90134. if (e === 0) {
  90135. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  90136. }
  90137. else if (e == 0x1F) {
  90138. return f ? NaN : ((s ? -1 : 1) * Infinity);
  90139. }
  90140. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  90141. };
  90142. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90143. var destArray = new Float32Array(dataLength);
  90144. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  90145. var index = 0;
  90146. for (var y = 0; y < height; y++) {
  90147. for (var x = 0; x < width; x++) {
  90148. var srcPos = (x + y * width) * 4;
  90149. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  90150. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  90151. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  90152. if (DDSTools.StoreLODInAlphaChannel) {
  90153. destArray[index + 3] = lod;
  90154. }
  90155. else {
  90156. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  90157. }
  90158. index += 4;
  90159. }
  90160. }
  90161. return destArray;
  90162. };
  90163. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90164. if (DDSTools.StoreLODInAlphaChannel) {
  90165. var destArray = new Uint16Array(dataLength);
  90166. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  90167. var index = 0;
  90168. for (var y = 0; y < height; y++) {
  90169. for (var x = 0; x < width; x++) {
  90170. var srcPos = (x + y * width) * 4;
  90171. destArray[index] = srcData[srcPos];
  90172. destArray[index + 1] = srcData[srcPos + 1];
  90173. destArray[index + 2] = srcData[srcPos + 2];
  90174. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  90175. index += 4;
  90176. }
  90177. }
  90178. return destArray;
  90179. }
  90180. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  90181. };
  90182. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90183. if (DDSTools.StoreLODInAlphaChannel) {
  90184. var destArray = new Float32Array(dataLength);
  90185. var srcData = new Float32Array(arrayBuffer, dataOffset);
  90186. var index = 0;
  90187. for (var y = 0; y < height; y++) {
  90188. for (var x = 0; x < width; x++) {
  90189. var srcPos = (x + y * width) * 4;
  90190. destArray[index] = srcData[srcPos];
  90191. destArray[index + 1] = srcData[srcPos + 1];
  90192. destArray[index + 2] = srcData[srcPos + 2];
  90193. destArray[index + 3] = lod;
  90194. index += 4;
  90195. }
  90196. }
  90197. return destArray;
  90198. }
  90199. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  90200. };
  90201. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90202. var destArray = new Uint8Array(dataLength);
  90203. var srcData = new Float32Array(arrayBuffer, dataOffset);
  90204. var index = 0;
  90205. for (var y = 0; y < height; y++) {
  90206. for (var x = 0; x < width; x++) {
  90207. var srcPos = (x + y * width) * 4;
  90208. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  90209. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  90210. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  90211. if (DDSTools.StoreLODInAlphaChannel) {
  90212. destArray[index + 3] = lod;
  90213. }
  90214. else {
  90215. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  90216. }
  90217. index += 4;
  90218. }
  90219. }
  90220. return destArray;
  90221. };
  90222. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90223. var destArray = new Uint8Array(dataLength);
  90224. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  90225. var index = 0;
  90226. for (var y = 0; y < height; y++) {
  90227. for (var x = 0; x < width; x++) {
  90228. var srcPos = (x + y * width) * 4;
  90229. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  90230. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  90231. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  90232. if (DDSTools.StoreLODInAlphaChannel) {
  90233. destArray[index + 3] = lod;
  90234. }
  90235. else {
  90236. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  90237. }
  90238. index += 4;
  90239. }
  90240. }
  90241. return destArray;
  90242. };
  90243. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  90244. var byteArray = new Uint8Array(dataLength);
  90245. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90246. var index = 0;
  90247. for (var y = 0; y < height; y++) {
  90248. for (var x = 0; x < width; x++) {
  90249. var srcPos = (x + y * width) * 4;
  90250. byteArray[index] = srcData[srcPos + rOffset];
  90251. byteArray[index + 1] = srcData[srcPos + gOffset];
  90252. byteArray[index + 2] = srcData[srcPos + bOffset];
  90253. byteArray[index + 3] = srcData[srcPos + aOffset];
  90254. index += 4;
  90255. }
  90256. }
  90257. return byteArray;
  90258. };
  90259. DDSTools._ExtractLongWordOrder = function (value) {
  90260. if (value === 0 || value === 255 || value === -16777216) {
  90261. return 0;
  90262. }
  90263. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  90264. };
  90265. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  90266. var byteArray = new Uint8Array(dataLength);
  90267. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90268. var index = 0;
  90269. for (var y = 0; y < height; y++) {
  90270. for (var x = 0; x < width; x++) {
  90271. var srcPos = (x + y * width) * 3;
  90272. byteArray[index] = srcData[srcPos + rOffset];
  90273. byteArray[index + 1] = srcData[srcPos + gOffset];
  90274. byteArray[index + 2] = srcData[srcPos + bOffset];
  90275. index += 3;
  90276. }
  90277. }
  90278. return byteArray;
  90279. };
  90280. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  90281. var byteArray = new Uint8Array(dataLength);
  90282. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90283. var index = 0;
  90284. for (var y = 0; y < height; y++) {
  90285. for (var x = 0; x < width; x++) {
  90286. var srcPos = (x + y * width);
  90287. byteArray[index] = srcData[srcPos];
  90288. index++;
  90289. }
  90290. }
  90291. return byteArray;
  90292. };
  90293. /**
  90294. * Uploads DDS Levels to a Babylon Texture
  90295. * @hidden
  90296. */
  90297. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  90298. if (lodIndex === void 0) { lodIndex = -1; }
  90299. var sphericalPolynomialFaces = null;
  90300. if (info.sphericalPolynomial) {
  90301. sphericalPolynomialFaces = new Array();
  90302. }
  90303. var ext = engine.getCaps().s3tc;
  90304. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  90305. var fourCC, width, height, dataLength = 0, dataOffset;
  90306. var byteArray, mipmapCount, mip;
  90307. var internalCompressedFormat = 0;
  90308. var blockBytes = 1;
  90309. if (header[off_magic] !== DDS_MAGIC) {
  90310. BABYLON.Tools.Error("Invalid magic number in DDS header");
  90311. return;
  90312. }
  90313. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  90314. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  90315. return;
  90316. }
  90317. if (info.isCompressed && !ext) {
  90318. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  90319. return;
  90320. }
  90321. var bpp = header[off_RGBbpp];
  90322. dataOffset = header[off_size] + 4;
  90323. var computeFormats = false;
  90324. if (info.isFourCC) {
  90325. fourCC = header[off_pfFourCC];
  90326. switch (fourCC) {
  90327. case FOURCC_DXT1:
  90328. blockBytes = 8;
  90329. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  90330. break;
  90331. case FOURCC_DXT3:
  90332. blockBytes = 16;
  90333. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  90334. break;
  90335. case FOURCC_DXT5:
  90336. blockBytes = 16;
  90337. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  90338. break;
  90339. case FOURCC_D3DFMT_R16G16B16A16F:
  90340. computeFormats = true;
  90341. break;
  90342. case FOURCC_D3DFMT_R32G32B32A32F:
  90343. computeFormats = true;
  90344. break;
  90345. case FOURCC_DX10:
  90346. // There is an additionnal header so dataOffset need to be changed
  90347. dataOffset += 5 * 4; // 5 uints
  90348. var supported = false;
  90349. switch (info.dxgiFormat) {
  90350. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  90351. computeFormats = true;
  90352. supported = true;
  90353. break;
  90354. case DXGI_FORMAT_B8G8R8X8_UNORM:
  90355. info.isRGB = true;
  90356. info.isFourCC = false;
  90357. bpp = 32;
  90358. supported = true;
  90359. break;
  90360. }
  90361. if (supported) {
  90362. break;
  90363. }
  90364. default:
  90365. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  90366. return;
  90367. }
  90368. }
  90369. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  90370. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  90371. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  90372. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  90373. if (computeFormats) {
  90374. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  90375. }
  90376. mipmapCount = 1;
  90377. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  90378. mipmapCount = Math.max(1, header[off_mipmapCount]);
  90379. }
  90380. for (var face = 0; face < faces; face++) {
  90381. width = header[off_width];
  90382. height = header[off_height];
  90383. for (mip = 0; mip < mipmapCount; ++mip) {
  90384. if (lodIndex === -1 || lodIndex === mip) {
  90385. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  90386. var i = (lodIndex === -1) ? mip : 0;
  90387. if (!info.isCompressed && info.isFourCC) {
  90388. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90389. dataLength = width * height * 4;
  90390. var floatArray = null;
  90391. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  90392. if (bpp === 128) {
  90393. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90394. if (sphericalPolynomialFaces && i == 0) {
  90395. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90396. }
  90397. }
  90398. else if (bpp === 64) {
  90399. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90400. if (sphericalPolynomialFaces && i == 0) {
  90401. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90402. }
  90403. }
  90404. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90405. }
  90406. else {
  90407. if (bpp === 128) {
  90408. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90409. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90410. if (sphericalPolynomialFaces && i == 0) {
  90411. sphericalPolynomialFaces.push(floatArray);
  90412. }
  90413. }
  90414. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  90415. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90416. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90417. if (sphericalPolynomialFaces && i == 0) {
  90418. sphericalPolynomialFaces.push(floatArray);
  90419. }
  90420. }
  90421. else { // 64
  90422. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90423. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90424. if (sphericalPolynomialFaces && i == 0) {
  90425. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90426. }
  90427. }
  90428. }
  90429. if (floatArray) {
  90430. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  90431. }
  90432. }
  90433. else if (info.isRGB) {
  90434. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90435. if (bpp === 24) {
  90436. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  90437. dataLength = width * height * 3;
  90438. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  90439. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  90440. }
  90441. else { // 32
  90442. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90443. dataLength = width * height * 4;
  90444. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  90445. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  90446. }
  90447. }
  90448. else if (info.isLuminance) {
  90449. var unpackAlignment = engine._getUnpackAlignement();
  90450. var unpaddedRowSize = width;
  90451. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  90452. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  90453. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  90454. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  90455. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90456. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  90457. }
  90458. else {
  90459. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  90460. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  90461. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90462. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  90463. }
  90464. }
  90465. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  90466. width *= 0.5;
  90467. height *= 0.5;
  90468. width = Math.max(1.0, width);
  90469. height = Math.max(1.0, height);
  90470. }
  90471. if (currentFace !== undefined) {
  90472. // Loading a single face
  90473. break;
  90474. }
  90475. }
  90476. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  90477. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  90478. size: header[off_width],
  90479. right: sphericalPolynomialFaces[0],
  90480. left: sphericalPolynomialFaces[1],
  90481. up: sphericalPolynomialFaces[2],
  90482. down: sphericalPolynomialFaces[3],
  90483. front: sphericalPolynomialFaces[4],
  90484. back: sphericalPolynomialFaces[5],
  90485. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  90486. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  90487. gammaSpace: false,
  90488. });
  90489. }
  90490. else {
  90491. info.sphericalPolynomial = undefined;
  90492. }
  90493. };
  90494. DDSTools.StoreLODInAlphaChannel = false;
  90495. return DDSTools;
  90496. }());
  90497. BABYLON.DDSTools = DDSTools;
  90498. })(BABYLON || (BABYLON = {}));
  90499. //# sourceMappingURL=babylon.dds.js.map
  90500. var BABYLON;
  90501. (function (BABYLON) {
  90502. /**
  90503. * Implementation of the DDS Texture Loader.
  90504. */
  90505. var DDSTextureLoader = /** @class */ (function () {
  90506. function DDSTextureLoader() {
  90507. /**
  90508. * Defines wether the loader supports cascade loading the different faces.
  90509. */
  90510. this.supportCascades = true;
  90511. }
  90512. /**
  90513. * This returns if the loader support the current file information.
  90514. * @param extension defines the file extension of the file being loaded
  90515. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90516. * @param fallback defines the fallback internal texture if any
  90517. * @param isBase64 defines whether the texture is encoded as a base64
  90518. * @param isBuffer defines whether the texture data are stored as a buffer
  90519. * @returns true if the loader can load the specified file
  90520. */
  90521. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90522. return extension.indexOf(".dds") === 0;
  90523. };
  90524. /**
  90525. * Transform the url before loading if required.
  90526. * @param rootUrl the url of the texture
  90527. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90528. * @returns the transformed texture
  90529. */
  90530. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90531. return rootUrl;
  90532. };
  90533. /**
  90534. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90535. * @param rootUrl the url of the texture
  90536. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90537. * @returns the fallback texture
  90538. */
  90539. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90540. return null;
  90541. };
  90542. /**
  90543. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90544. * @param data contains the texture data
  90545. * @param texture defines the BabylonJS internal texture
  90546. * @param createPolynomials will be true if polynomials have been requested
  90547. * @param onLoad defines the callback to trigger once the texture is ready
  90548. * @param onError defines the callback to trigger in case of error
  90549. */
  90550. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  90551. var engine = texture.getEngine();
  90552. var info;
  90553. var loadMipmap = false;
  90554. if (Array.isArray(imgs)) {
  90555. for (var index = 0; index < imgs.length; index++) {
  90556. var data_1 = imgs[index];
  90557. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  90558. texture.width = info.width;
  90559. texture.height = info.height;
  90560. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  90561. engine._unpackFlipY(info.isCompressed);
  90562. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  90563. if (!info.isFourCC && info.mipmapCount === 1) {
  90564. engine.generateMipMapsForCubemap(texture);
  90565. }
  90566. }
  90567. }
  90568. else {
  90569. var data = imgs;
  90570. info = BABYLON.DDSTools.GetDDSInfo(data);
  90571. texture.width = info.width;
  90572. texture.height = info.height;
  90573. if (createPolynomials) {
  90574. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  90575. }
  90576. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  90577. engine._unpackFlipY(info.isCompressed);
  90578. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  90579. if (!info.isFourCC && info.mipmapCount === 1) {
  90580. engine.generateMipMapsForCubemap(texture);
  90581. }
  90582. }
  90583. engine._setCubeMapTextureParams(loadMipmap);
  90584. texture.isReady = true;
  90585. if (onLoad) {
  90586. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  90587. }
  90588. };
  90589. /**
  90590. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90591. * @param data contains the texture data
  90592. * @param texture defines the BabylonJS internal texture
  90593. * @param callback defines the method to call once ready to upload
  90594. */
  90595. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  90596. var info = BABYLON.DDSTools.GetDDSInfo(data);
  90597. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  90598. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  90599. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  90600. });
  90601. };
  90602. return DDSTextureLoader;
  90603. }());
  90604. // Register the loader.
  90605. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  90606. })(BABYLON || (BABYLON = {}));
  90607. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  90608. var BABYLON;
  90609. (function (BABYLON) {
  90610. /*
  90611. * Based on jsTGALoader - Javascript loader for TGA file
  90612. * By Vincent Thibault
  90613. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  90614. */
  90615. var TGATools = /** @class */ (function () {
  90616. function TGATools() {
  90617. }
  90618. TGATools.GetTGAHeader = function (data) {
  90619. var offset = 0;
  90620. var header = {
  90621. id_length: data[offset++],
  90622. colormap_type: data[offset++],
  90623. image_type: data[offset++],
  90624. colormap_index: data[offset++] | data[offset++] << 8,
  90625. colormap_length: data[offset++] | data[offset++] << 8,
  90626. colormap_size: data[offset++],
  90627. origin: [
  90628. data[offset++] | data[offset++] << 8,
  90629. data[offset++] | data[offset++] << 8
  90630. ],
  90631. width: data[offset++] | data[offset++] << 8,
  90632. height: data[offset++] | data[offset++] << 8,
  90633. pixel_size: data[offset++],
  90634. flags: data[offset++]
  90635. };
  90636. return header;
  90637. };
  90638. /**
  90639. * Uploads TGA content to a Babylon Texture
  90640. * @hidden
  90641. */
  90642. TGATools.UploadContent = function (texture, data) {
  90643. // Not enough data to contain header ?
  90644. if (data.length < 19) {
  90645. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  90646. return;
  90647. }
  90648. // Read Header
  90649. var offset = 18;
  90650. var header = TGATools.GetTGAHeader(data);
  90651. // Assume it's a valid Targa file.
  90652. if (header.id_length + offset > data.length) {
  90653. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  90654. return;
  90655. }
  90656. // Skip not needed data
  90657. offset += header.id_length;
  90658. var use_rle = false;
  90659. var use_pal = false;
  90660. var use_grey = false;
  90661. // Get some informations.
  90662. switch (header.image_type) {
  90663. case TGATools._TYPE_RLE_INDEXED:
  90664. use_rle = true;
  90665. case TGATools._TYPE_INDEXED:
  90666. use_pal = true;
  90667. break;
  90668. case TGATools._TYPE_RLE_RGB:
  90669. use_rle = true;
  90670. case TGATools._TYPE_RGB:
  90671. // use_rgb = true;
  90672. break;
  90673. case TGATools._TYPE_RLE_GREY:
  90674. use_rle = true;
  90675. case TGATools._TYPE_GREY:
  90676. use_grey = true;
  90677. break;
  90678. }
  90679. var pixel_data;
  90680. // var numAlphaBits = header.flags & 0xf;
  90681. var pixel_size = header.pixel_size >> 3;
  90682. var pixel_total = header.width * header.height * pixel_size;
  90683. // Read palettes
  90684. var palettes;
  90685. if (use_pal) {
  90686. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  90687. }
  90688. // Read LRE
  90689. if (use_rle) {
  90690. pixel_data = new Uint8Array(pixel_total);
  90691. var c, count, i;
  90692. var localOffset = 0;
  90693. var pixels = new Uint8Array(pixel_size);
  90694. while (offset < pixel_total && localOffset < pixel_total) {
  90695. c = data[offset++];
  90696. count = (c & 0x7f) + 1;
  90697. // RLE pixels
  90698. if (c & 0x80) {
  90699. // Bind pixel tmp array
  90700. for (i = 0; i < pixel_size; ++i) {
  90701. pixels[i] = data[offset++];
  90702. }
  90703. // Copy pixel array
  90704. for (i = 0; i < count; ++i) {
  90705. pixel_data.set(pixels, localOffset + i * pixel_size);
  90706. }
  90707. localOffset += pixel_size * count;
  90708. }
  90709. // Raw pixels
  90710. else {
  90711. count *= pixel_size;
  90712. for (i = 0; i < count; ++i) {
  90713. pixel_data[localOffset + i] = data[offset++];
  90714. }
  90715. localOffset += count;
  90716. }
  90717. }
  90718. }
  90719. // RAW Pixels
  90720. else {
  90721. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  90722. }
  90723. // Load to texture
  90724. var x_start, y_start, x_step, y_step, y_end, x_end;
  90725. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  90726. default:
  90727. case TGATools._ORIGIN_UL:
  90728. x_start = 0;
  90729. x_step = 1;
  90730. x_end = header.width;
  90731. y_start = 0;
  90732. y_step = 1;
  90733. y_end = header.height;
  90734. break;
  90735. case TGATools._ORIGIN_BL:
  90736. x_start = 0;
  90737. x_step = 1;
  90738. x_end = header.width;
  90739. y_start = header.height - 1;
  90740. y_step = -1;
  90741. y_end = -1;
  90742. break;
  90743. case TGATools._ORIGIN_UR:
  90744. x_start = header.width - 1;
  90745. x_step = -1;
  90746. x_end = -1;
  90747. y_start = 0;
  90748. y_step = 1;
  90749. y_end = header.height;
  90750. break;
  90751. case TGATools._ORIGIN_BR:
  90752. x_start = header.width - 1;
  90753. x_step = -1;
  90754. x_end = -1;
  90755. y_start = header.height - 1;
  90756. y_step = -1;
  90757. y_end = -1;
  90758. break;
  90759. }
  90760. // Load the specify method
  90761. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  90762. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  90763. var engine = texture.getEngine();
  90764. engine._uploadDataToTextureDirectly(texture, imageData);
  90765. };
  90766. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90767. var image = pixel_data, colormap = palettes;
  90768. var width = header.width, height = header.height;
  90769. var color, i = 0, x, y;
  90770. var imageData = new Uint8Array(width * height * 4);
  90771. for (y = y_start; y !== y_end; y += y_step) {
  90772. for (x = x_start; x !== x_end; x += x_step, i++) {
  90773. color = image[i];
  90774. imageData[(x + width * y) * 4 + 3] = 255;
  90775. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  90776. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  90777. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  90778. }
  90779. }
  90780. return imageData;
  90781. };
  90782. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90783. var image = pixel_data;
  90784. var width = header.width, height = header.height;
  90785. var color, i = 0, x, y;
  90786. var imageData = new Uint8Array(width * height * 4);
  90787. for (y = y_start; y !== y_end; y += y_step) {
  90788. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  90789. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  90790. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  90791. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  90792. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  90793. imageData[(x + width * y) * 4 + 0] = r;
  90794. imageData[(x + width * y) * 4 + 1] = g;
  90795. imageData[(x + width * y) * 4 + 2] = b;
  90796. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  90797. }
  90798. }
  90799. return imageData;
  90800. };
  90801. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90802. var image = pixel_data;
  90803. var width = header.width, height = header.height;
  90804. var i = 0, x, y;
  90805. var imageData = new Uint8Array(width * height * 4);
  90806. for (y = y_start; y !== y_end; y += y_step) {
  90807. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  90808. imageData[(x + width * y) * 4 + 3] = 255;
  90809. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  90810. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  90811. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  90812. }
  90813. }
  90814. return imageData;
  90815. };
  90816. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90817. var image = pixel_data;
  90818. var width = header.width, height = header.height;
  90819. var i = 0, x, y;
  90820. var imageData = new Uint8Array(width * height * 4);
  90821. for (y = y_start; y !== y_end; y += y_step) {
  90822. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  90823. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  90824. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  90825. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  90826. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  90827. }
  90828. }
  90829. return imageData;
  90830. };
  90831. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90832. var image = pixel_data;
  90833. var width = header.width, height = header.height;
  90834. var color, i = 0, x, y;
  90835. var imageData = new Uint8Array(width * height * 4);
  90836. for (y = y_start; y !== y_end; y += y_step) {
  90837. for (x = x_start; x !== x_end; x += x_step, i++) {
  90838. color = image[i];
  90839. imageData[(x + width * y) * 4 + 0] = color;
  90840. imageData[(x + width * y) * 4 + 1] = color;
  90841. imageData[(x + width * y) * 4 + 2] = color;
  90842. imageData[(x + width * y) * 4 + 3] = 255;
  90843. }
  90844. }
  90845. return imageData;
  90846. };
  90847. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90848. var image = pixel_data;
  90849. var width = header.width, height = header.height;
  90850. var i = 0, x, y;
  90851. var imageData = new Uint8Array(width * height * 4);
  90852. for (y = y_start; y !== y_end; y += y_step) {
  90853. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  90854. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  90855. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  90856. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  90857. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  90858. }
  90859. }
  90860. return imageData;
  90861. };
  90862. //private static _TYPE_NO_DATA = 0;
  90863. TGATools._TYPE_INDEXED = 1;
  90864. TGATools._TYPE_RGB = 2;
  90865. TGATools._TYPE_GREY = 3;
  90866. TGATools._TYPE_RLE_INDEXED = 9;
  90867. TGATools._TYPE_RLE_RGB = 10;
  90868. TGATools._TYPE_RLE_GREY = 11;
  90869. TGATools._ORIGIN_MASK = 0x30;
  90870. TGATools._ORIGIN_SHIFT = 0x04;
  90871. TGATools._ORIGIN_BL = 0x00;
  90872. TGATools._ORIGIN_BR = 0x01;
  90873. TGATools._ORIGIN_UL = 0x02;
  90874. TGATools._ORIGIN_UR = 0x03;
  90875. return TGATools;
  90876. }());
  90877. BABYLON.TGATools = TGATools;
  90878. })(BABYLON || (BABYLON = {}));
  90879. //# sourceMappingURL=babylon.tga.js.map
  90880. var BABYLON;
  90881. (function (BABYLON) {
  90882. /**
  90883. * Implementation of the TGA Texture Loader.
  90884. */
  90885. var TGATextureLoader = /** @class */ (function () {
  90886. function TGATextureLoader() {
  90887. /**
  90888. * Defines wether the loader supports cascade loading the different faces.
  90889. */
  90890. this.supportCascades = false;
  90891. }
  90892. /**
  90893. * This returns if the loader support the current file information.
  90894. * @param extension defines the file extension of the file being loaded
  90895. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90896. * @param fallback defines the fallback internal texture if any
  90897. * @param isBase64 defines whether the texture is encoded as a base64
  90898. * @param isBuffer defines whether the texture data are stored as a buffer
  90899. * @returns true if the loader can load the specified file
  90900. */
  90901. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90902. return extension.indexOf(".tga") === 0;
  90903. };
  90904. /**
  90905. * Transform the url before loading if required.
  90906. * @param rootUrl the url of the texture
  90907. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90908. * @returns the transformed texture
  90909. */
  90910. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90911. return rootUrl;
  90912. };
  90913. /**
  90914. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90915. * @param rootUrl the url of the texture
  90916. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90917. * @returns the fallback texture
  90918. */
  90919. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90920. return null;
  90921. };
  90922. /**
  90923. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90924. * @param data contains the texture data
  90925. * @param texture defines the BabylonJS internal texture
  90926. * @param createPolynomials will be true if polynomials have been requested
  90927. * @param onLoad defines the callback to trigger once the texture is ready
  90928. * @param onError defines the callback to trigger in case of error
  90929. */
  90930. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90931. throw ".env not supported in Cube.";
  90932. };
  90933. /**
  90934. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90935. * @param data contains the texture data
  90936. * @param texture defines the BabylonJS internal texture
  90937. * @param callback defines the method to call once ready to upload
  90938. */
  90939. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  90940. var uintData = new Uint8Array(data);
  90941. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  90942. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  90943. BABYLON.TGATools.UploadContent(texture, uintData);
  90944. });
  90945. };
  90946. return TGATextureLoader;
  90947. }());
  90948. // Register the loader.
  90949. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  90950. })(BABYLON || (BABYLON = {}));
  90951. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  90952. var BABYLON;
  90953. (function (BABYLON) {
  90954. /**
  90955. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  90956. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  90957. */
  90958. var KhronosTextureContainer = /** @class */ (function () {
  90959. /**
  90960. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  90961. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  90962. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  90963. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  90964. */
  90965. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  90966. this.arrayBuffer = arrayBuffer;
  90967. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  90968. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  90969. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  90970. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  90971. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  90972. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  90973. BABYLON.Tools.Error("texture missing KTX identifier");
  90974. return;
  90975. }
  90976. // load the reset of the header in native 32 bit int
  90977. var header = new Int32Array(this.arrayBuffer, 12, 13);
  90978. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  90979. var oppositeEndianess = header[0] === 0x01020304;
  90980. // read all the header elements in order they exist in the file, without modification (sans endainness)
  90981. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  90982. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  90983. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  90984. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  90985. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  90986. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  90987. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  90988. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  90989. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  90990. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  90991. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  90992. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  90993. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  90994. if (this.glType !== 0) {
  90995. BABYLON.Tools.Error("only compressed formats currently supported");
  90996. return;
  90997. }
  90998. else {
  90999. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  91000. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  91001. }
  91002. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  91003. BABYLON.Tools.Error("only 2D textures currently supported");
  91004. return;
  91005. }
  91006. if (this.numberOfArrayElements !== 0) {
  91007. BABYLON.Tools.Error("texture arrays not currently supported");
  91008. return;
  91009. }
  91010. if (this.numberOfFaces !== facesExpected) {
  91011. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  91012. return;
  91013. }
  91014. // we now have a completely validated file, so could use existence of loadType as success
  91015. // would need to make this more elaborate & adjust checks above to support more than one load type
  91016. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  91017. }
  91018. // not as fast hardware based, but will probably never need to use
  91019. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  91020. return ((val & 0xFF) << 24)
  91021. | ((val & 0xFF00) << 8)
  91022. | ((val >> 8) & 0xFF00)
  91023. | ((val >> 24) & 0xFF);
  91024. };
  91025. /**
  91026. * Uploads KTX content to a Babylon Texture.
  91027. * It is assumed that the texture has already been created & is currently bound
  91028. * @hidden
  91029. */
  91030. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  91031. switch (this.loadType) {
  91032. case KhronosTextureContainer.COMPRESSED_2D:
  91033. this._upload2DCompressedLevels(texture, loadMipmaps);
  91034. break;
  91035. case KhronosTextureContainer.TEX_2D:
  91036. case KhronosTextureContainer.COMPRESSED_3D:
  91037. case KhronosTextureContainer.TEX_3D:
  91038. }
  91039. };
  91040. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  91041. // initialize width & height for level 1
  91042. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  91043. var width = this.pixelWidth;
  91044. var height = this.pixelHeight;
  91045. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  91046. for (var level = 0; level < mipmapCount; level++) {
  91047. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  91048. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  91049. for (var face = 0; face < this.numberOfFaces; face++) {
  91050. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  91051. var engine = texture.getEngine();
  91052. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  91053. dataOffset += imageSize; // add size of the image for the next face/mipmap
  91054. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  91055. }
  91056. width = Math.max(1.0, width * 0.5);
  91057. height = Math.max(1.0, height * 0.5);
  91058. }
  91059. };
  91060. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  91061. // load types
  91062. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  91063. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  91064. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  91065. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  91066. return KhronosTextureContainer;
  91067. }());
  91068. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  91069. })(BABYLON || (BABYLON = {}));
  91070. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  91071. var BABYLON;
  91072. (function (BABYLON) {
  91073. /**
  91074. * Implementation of the KTX Texture Loader.
  91075. */
  91076. var KTXTextureLoader = /** @class */ (function () {
  91077. function KTXTextureLoader() {
  91078. /**
  91079. * Defines wether the loader supports cascade loading the different faces.
  91080. */
  91081. this.supportCascades = false;
  91082. }
  91083. /**
  91084. * This returns if the loader support the current file information.
  91085. * @param extension defines the file extension of the file being loaded
  91086. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91087. * @param fallback defines the fallback internal texture if any
  91088. * @param isBase64 defines whether the texture is encoded as a base64
  91089. * @param isBuffer defines whether the texture data are stored as a buffer
  91090. * @returns true if the loader can load the specified file
  91091. */
  91092. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91093. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  91094. return true;
  91095. }
  91096. return false;
  91097. };
  91098. /**
  91099. * Transform the url before loading if required.
  91100. * @param rootUrl the url of the texture
  91101. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91102. * @returns the transformed texture
  91103. */
  91104. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91105. var lastDot = rootUrl.lastIndexOf('.');
  91106. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  91107. };
  91108. /**
  91109. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91110. * @param rootUrl the url of the texture
  91111. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91112. * @returns the fallback texture
  91113. */
  91114. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91115. // remove the format appended to the rootUrl in the original createCubeTexture call.
  91116. var exp = new RegExp("" + textureFormatInUse + "$");
  91117. return rootUrl.replace(exp, "");
  91118. };
  91119. /**
  91120. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91121. * @param data contains the texture data
  91122. * @param texture defines the BabylonJS internal texture
  91123. * @param createPolynomials will be true if polynomials have been requested
  91124. * @param onLoad defines the callback to trigger once the texture is ready
  91125. * @param onError defines the callback to trigger in case of error
  91126. */
  91127. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  91128. if (Array.isArray(data)) {
  91129. return;
  91130. }
  91131. var engine = texture.getEngine();
  91132. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  91133. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  91134. engine._unpackFlipY(true);
  91135. ktx.uploadLevels(texture, texture.generateMipMaps);
  91136. texture.width = ktx.pixelWidth;
  91137. texture.height = ktx.pixelHeight;
  91138. engine._setCubeMapTextureParams(loadMipmap);
  91139. texture.isReady = true;
  91140. };
  91141. /**
  91142. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91143. * @param data contains the texture data
  91144. * @param texture defines the BabylonJS internal texture
  91145. * @param callback defines the method to call once ready to upload
  91146. */
  91147. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  91148. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  91149. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  91150. ktx.uploadLevels(texture, texture.generateMipMaps);
  91151. });
  91152. };
  91153. return KTXTextureLoader;
  91154. }());
  91155. // Register the loader.
  91156. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  91157. })(BABYLON || (BABYLON = {}));
  91158. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  91159. var BABYLON;
  91160. (function (BABYLON) {
  91161. /**
  91162. * Sets of helpers addressing the serialization and deserialization of environment texture
  91163. * stored in a BabylonJS env file.
  91164. * Those files are usually stored as .env files.
  91165. */
  91166. var EnvironmentTextureTools = /** @class */ (function () {
  91167. function EnvironmentTextureTools() {
  91168. }
  91169. /**
  91170. * Gets the environment info from an env file.
  91171. * @param data The array buffer containing the .env bytes.
  91172. * @returns the environment file info (the json header) if successfully parsed.
  91173. */
  91174. EnvironmentTextureTools.GetEnvInfo = function (data) {
  91175. var dataView = new DataView(data);
  91176. var pos = 0;
  91177. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  91178. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  91179. BABYLON.Tools.Error('Not a babylon environment map');
  91180. return null;
  91181. }
  91182. }
  91183. // Read json manifest - collect characters up to null terminator
  91184. var manifestString = '';
  91185. var charCode = 0x00;
  91186. while ((charCode = dataView.getUint8(pos++))) {
  91187. manifestString += String.fromCharCode(charCode);
  91188. }
  91189. var manifest = JSON.parse(manifestString);
  91190. if (manifest.specular) {
  91191. // Extend the header with the position of the payload.
  91192. manifest.specular.specularDataPosition = pos;
  91193. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  91194. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  91195. }
  91196. return manifest;
  91197. };
  91198. /**
  91199. * Creates an environment texture from a loaded cube texture.
  91200. * @param texture defines the cube texture to convert in env file
  91201. * @return a promise containing the environment data if succesfull.
  91202. */
  91203. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  91204. var _this = this;
  91205. var internalTexture = texture.getInternalTexture();
  91206. if (!internalTexture) {
  91207. return Promise.reject("The cube texture is invalid.");
  91208. }
  91209. if (!texture._prefiltered) {
  91210. return Promise.reject("The cube texture is invalid (not prefiltered).");
  91211. }
  91212. var engine = internalTexture.getEngine();
  91213. if (engine && engine.premultipliedAlpha) {
  91214. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  91215. }
  91216. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  91217. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  91218. }
  91219. var canvas = engine.getRenderingCanvas();
  91220. if (!canvas) {
  91221. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  91222. }
  91223. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91224. if (!engine.getCaps().textureFloatRender) {
  91225. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91226. if (!engine.getCaps().textureHalfFloatRender) {
  91227. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  91228. }
  91229. }
  91230. var cubeWidth = internalTexture.width;
  91231. var hostingScene = new BABYLON.Scene(engine);
  91232. var specularTextures = {};
  91233. var promises = [];
  91234. // Read and collect all mipmaps data from the cube.
  91235. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  91236. mipmapsCount = Math.round(mipmapsCount);
  91237. var _loop_1 = function (i) {
  91238. var faceWidth = Math.pow(2, mipmapsCount - i);
  91239. var _loop_2 = function (face) {
  91240. var data = texture.readPixels(face, i);
  91241. // Creates a temp texture with the face data.
  91242. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  91243. // And rgbdEncode them.
  91244. var promise = new Promise(function (resolve, reject) {
  91245. 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);
  91246. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  91247. rgbdPostProcess.onApply = function (effect) {
  91248. effect._bindTexture("textureSampler", tempTexture);
  91249. };
  91250. // As the process needs to happen on the main canvas, keep track of the current size
  91251. var currentW = engine.getRenderWidth();
  91252. var currentH = engine.getRenderHeight();
  91253. // Set the desired size for the texture
  91254. engine.setSize(faceWidth, faceWidth);
  91255. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  91256. // Reading datas from WebGL
  91257. BABYLON.Tools.ToBlob(canvas, function (blob) {
  91258. var fileReader = new FileReader();
  91259. fileReader.onload = function (event) {
  91260. var arrayBuffer = event.target.result;
  91261. specularTextures[i * 6 + face] = arrayBuffer;
  91262. resolve();
  91263. };
  91264. fileReader.readAsArrayBuffer(blob);
  91265. });
  91266. // Reapply the previous canvas size
  91267. engine.setSize(currentW, currentH);
  91268. });
  91269. });
  91270. promises.push(promise);
  91271. };
  91272. // All faces of the cube.
  91273. for (var face = 0; face < 6; face++) {
  91274. _loop_2(face);
  91275. }
  91276. };
  91277. for (var i = 0; i <= mipmapsCount; i++) {
  91278. _loop_1(i);
  91279. }
  91280. // Once all the textures haves been collected as RGBD stored in PNGs
  91281. return Promise.all(promises).then(function () {
  91282. // We can delete the hosting scene keeping track of all the creation objects
  91283. hostingScene.dispose();
  91284. // Creates the json header for the env texture
  91285. var info = {
  91286. version: 1,
  91287. width: cubeWidth,
  91288. irradiance: _this._CreateEnvTextureIrradiance(texture),
  91289. specular: {
  91290. mipmaps: [],
  91291. lodGenerationScale: texture.lodGenerationScale
  91292. }
  91293. };
  91294. // Sets the specular image data information
  91295. var position = 0;
  91296. for (var i = 0; i <= mipmapsCount; i++) {
  91297. for (var face = 0; face < 6; face++) {
  91298. var byteLength = specularTextures[i * 6 + face].byteLength;
  91299. info.specular.mipmaps.push({
  91300. length: byteLength,
  91301. position: position
  91302. });
  91303. position += byteLength;
  91304. }
  91305. }
  91306. // Encode the JSON as an array buffer
  91307. var infoString = JSON.stringify(info);
  91308. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  91309. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  91310. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  91311. infoView[i] = infoString.charCodeAt(i);
  91312. }
  91313. // Ends up with a null terminator for easier parsing
  91314. infoView[infoString.length] = 0x00;
  91315. // Computes the final required size and creates the storage
  91316. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  91317. var finalBuffer = new ArrayBuffer(totalSize);
  91318. var finalBufferView = new Uint8Array(finalBuffer);
  91319. var dataView = new DataView(finalBuffer);
  91320. // Copy the magic bytes identifying the file in
  91321. var pos = 0;
  91322. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  91323. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  91324. }
  91325. // Add the json info
  91326. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  91327. pos += infoBuffer.byteLength;
  91328. // Finally inserts the texture data
  91329. for (var i = 0; i <= mipmapsCount; i++) {
  91330. for (var face = 0; face < 6; face++) {
  91331. var dataBuffer = specularTextures[i * 6 + face];
  91332. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  91333. pos += dataBuffer.byteLength;
  91334. }
  91335. }
  91336. // Voila
  91337. return finalBuffer;
  91338. });
  91339. };
  91340. /**
  91341. * Creates a JSON representation of the spherical data.
  91342. * @param texture defines the texture containing the polynomials
  91343. * @return the JSON representation of the spherical info
  91344. */
  91345. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  91346. var polynmials = texture.sphericalPolynomial;
  91347. if (polynmials == null) {
  91348. return null;
  91349. }
  91350. return {
  91351. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  91352. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  91353. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  91354. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  91355. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  91356. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  91357. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  91358. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  91359. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  91360. };
  91361. };
  91362. /**
  91363. * Uploads the texture info contained in the env file to the GPU.
  91364. * @param texture defines the internal texture to upload to
  91365. * @param arrayBuffer defines the buffer cotaining the data to load
  91366. * @param info defines the texture info retrieved through the GetEnvInfo method
  91367. * @returns a promise
  91368. */
  91369. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  91370. if (info.version !== 1) {
  91371. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  91372. }
  91373. var specularInfo = info.specular;
  91374. if (!specularInfo) {
  91375. // Nothing else parsed so far
  91376. return Promise.resolve();
  91377. }
  91378. // Double checks the enclosed info
  91379. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  91380. mipmapsCount = Math.round(mipmapsCount) + 1;
  91381. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  91382. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  91383. }
  91384. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  91385. var imageData = new Array(mipmapsCount);
  91386. for (var i = 0; i < mipmapsCount; i++) {
  91387. imageData[i] = new Array(6);
  91388. for (var face = 0; face < 6; face++) {
  91389. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  91390. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  91391. }
  91392. }
  91393. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  91394. };
  91395. /**
  91396. * Uploads the levels of image data to the GPU.
  91397. * @param texture defines the internal texture to upload to
  91398. * @param imageData defines the array buffer views of image data [mipmap][face]
  91399. * @returns a promise
  91400. */
  91401. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  91402. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  91403. throw new Error("Texture size must be a power of two");
  91404. }
  91405. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  91406. // Gets everything ready.
  91407. var engine = texture.getEngine();
  91408. var expandTexture = false;
  91409. var generateNonLODTextures = false;
  91410. var rgbdPostProcess = null;
  91411. var cubeRtt = null;
  91412. var lodTextures = null;
  91413. var caps = engine.getCaps();
  91414. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91415. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91416. texture.generateMipMaps = true;
  91417. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  91418. // Add extra process if texture lod is not supported
  91419. if (!caps.textureLOD) {
  91420. expandTexture = false;
  91421. generateNonLODTextures = true;
  91422. lodTextures = {};
  91423. }
  91424. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  91425. else if (engine.webGLVersion < 2) {
  91426. expandTexture = false;
  91427. }
  91428. // If half float available we can uncompress the texture
  91429. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  91430. expandTexture = true;
  91431. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91432. }
  91433. // If full float available we can uncompress the texture
  91434. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  91435. expandTexture = true;
  91436. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91437. }
  91438. // Expand the texture if possible
  91439. if (expandTexture) {
  91440. // Simply run through the decode PP
  91441. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  91442. texture._isRGBD = false;
  91443. texture.invertY = false;
  91444. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  91445. generateDepthBuffer: false,
  91446. generateMipMaps: true,
  91447. generateStencilBuffer: false,
  91448. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  91449. type: texture.type,
  91450. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  91451. });
  91452. }
  91453. else {
  91454. texture._isRGBD = true;
  91455. texture.invertY = true;
  91456. // In case of missing support, applies the same patch than DDS files.
  91457. if (generateNonLODTextures) {
  91458. var mipSlices = 3;
  91459. var scale = texture._lodGenerationScale;
  91460. var offset = texture._lodGenerationOffset;
  91461. for (var i = 0; i < mipSlices; i++) {
  91462. //compute LOD from even spacing in smoothness (matching shader calculation)
  91463. var smoothness = i / (mipSlices - 1);
  91464. var roughness = 1 - smoothness;
  91465. var minLODIndex = offset; // roughness = 0
  91466. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  91467. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  91468. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  91469. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  91470. glTextureFromLod.isCube = true;
  91471. glTextureFromLod.invertY = true;
  91472. glTextureFromLod.generateMipMaps = false;
  91473. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  91474. // Wrap in a base texture for easy binding.
  91475. var lodTexture = new BABYLON.BaseTexture(null);
  91476. lodTexture.isCube = true;
  91477. lodTexture._texture = glTextureFromLod;
  91478. lodTextures[mipmapIndex] = lodTexture;
  91479. switch (i) {
  91480. case 0:
  91481. texture._lodTextureLow = lodTexture;
  91482. break;
  91483. case 1:
  91484. texture._lodTextureMid = lodTexture;
  91485. break;
  91486. case 2:
  91487. texture._lodTextureHigh = lodTexture;
  91488. break;
  91489. }
  91490. }
  91491. }
  91492. }
  91493. var promises = [];
  91494. var _loop_3 = function (i) {
  91495. var _loop_4 = function (face) {
  91496. // Constructs an image element from image data
  91497. var bytes = imageData[i][face];
  91498. var blob = new Blob([bytes], { type: 'image/png' });
  91499. var url = URL.createObjectURL(blob);
  91500. var image = new Image();
  91501. image.src = url;
  91502. // Enqueue promise to upload to the texture.
  91503. var promise = new Promise(function (resolve, reject) {
  91504. image.onload = function () {
  91505. if (expandTexture) {
  91506. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  91507. reject(message);
  91508. }, image);
  91509. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  91510. // Uncompress the data to a RTT
  91511. rgbdPostProcess.onApply = function (effect) {
  91512. effect._bindTexture("textureSampler", tempTexture_1);
  91513. effect.setFloat2("scale", 1, 1);
  91514. };
  91515. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  91516. // Cleanup
  91517. engine.restoreDefaultFramebuffer();
  91518. tempTexture_1.dispose();
  91519. window.URL.revokeObjectURL(url);
  91520. resolve();
  91521. });
  91522. }
  91523. else {
  91524. engine._uploadImageToTexture(texture, image, face, i);
  91525. // Upload the face to the non lod texture support
  91526. if (generateNonLODTextures) {
  91527. var lodTexture = lodTextures[i];
  91528. if (lodTexture) {
  91529. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  91530. }
  91531. }
  91532. resolve();
  91533. }
  91534. };
  91535. image.onerror = function (error) {
  91536. reject(error);
  91537. };
  91538. });
  91539. promises.push(promise);
  91540. };
  91541. // All faces
  91542. for (var face = 0; face < 6; face++) {
  91543. _loop_4(face);
  91544. }
  91545. };
  91546. // All mipmaps up to provided number of images
  91547. for (var i = 0; i < imageData.length; i++) {
  91548. _loop_3(i);
  91549. }
  91550. // Fill remaining mipmaps with black textures.
  91551. if (imageData.length < mipmapsCount) {
  91552. var data = void 0;
  91553. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  91554. var dataLength = size * size * 4;
  91555. switch (texture.type) {
  91556. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  91557. data = new Uint8Array(dataLength);
  91558. break;
  91559. }
  91560. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  91561. data = new Uint16Array(dataLength);
  91562. break;
  91563. }
  91564. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  91565. data = new Float32Array(dataLength);
  91566. break;
  91567. }
  91568. }
  91569. for (var i = imageData.length; i < mipmapsCount; i++) {
  91570. for (var face = 0; face < 6; face++) {
  91571. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  91572. }
  91573. }
  91574. }
  91575. // Once all done, finishes the cleanup and return
  91576. return Promise.all(promises).then(function () {
  91577. // Release temp RTT.
  91578. if (cubeRtt) {
  91579. engine._releaseFramebufferObjects(cubeRtt);
  91580. cubeRtt._swapAndDie(texture);
  91581. }
  91582. // Release temp Post Process.
  91583. if (rgbdPostProcess) {
  91584. rgbdPostProcess.dispose();
  91585. }
  91586. // Flag internal texture as ready in case they are in use.
  91587. if (generateNonLODTextures) {
  91588. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  91589. texture._lodTextureHigh._texture.isReady = true;
  91590. }
  91591. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  91592. texture._lodTextureMid._texture.isReady = true;
  91593. }
  91594. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  91595. texture._lodTextureLow._texture.isReady = true;
  91596. }
  91597. }
  91598. });
  91599. };
  91600. /**
  91601. * Uploads spherical polynomials information to the texture.
  91602. * @param texture defines the texture we are trying to upload the information to
  91603. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  91604. */
  91605. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  91606. if (info.version !== 1) {
  91607. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  91608. }
  91609. var irradianceInfo = info.irradiance;
  91610. if (!irradianceInfo) {
  91611. return;
  91612. }
  91613. var sp = new BABYLON.SphericalPolynomial();
  91614. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  91615. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  91616. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  91617. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  91618. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  91619. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  91620. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  91621. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  91622. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  91623. texture._sphericalPolynomial = sp;
  91624. };
  91625. /**
  91626. * Magic number identifying the env file.
  91627. */
  91628. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  91629. return EnvironmentTextureTools;
  91630. }());
  91631. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  91632. })(BABYLON || (BABYLON = {}));
  91633. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  91634. var BABYLON;
  91635. (function (BABYLON) {
  91636. /**
  91637. * Implementation of the ENV Texture Loader.
  91638. */
  91639. var ENVTextureLoader = /** @class */ (function () {
  91640. function ENVTextureLoader() {
  91641. /**
  91642. * Defines wether the loader supports cascade loading the different faces.
  91643. */
  91644. this.supportCascades = false;
  91645. }
  91646. /**
  91647. * This returns if the loader support the current file information.
  91648. * @param extension defines the file extension of the file being loaded
  91649. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91650. * @param fallback defines the fallback internal texture if any
  91651. * @param isBase64 defines whether the texture is encoded as a base64
  91652. * @param isBuffer defines whether the texture data are stored as a buffer
  91653. * @returns true if the loader can load the specified file
  91654. */
  91655. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91656. return extension.indexOf(".env") === 0;
  91657. };
  91658. /**
  91659. * Transform the url before loading if required.
  91660. * @param rootUrl the url of the texture
  91661. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91662. * @returns the transformed texture
  91663. */
  91664. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91665. return rootUrl;
  91666. };
  91667. /**
  91668. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91669. * @param rootUrl the url of the texture
  91670. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91671. * @returns the fallback texture
  91672. */
  91673. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91674. return null;
  91675. };
  91676. /**
  91677. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91678. * @param data contains the texture data
  91679. * @param texture defines the BabylonJS internal texture
  91680. * @param createPolynomials will be true if polynomials have been requested
  91681. * @param onLoad defines the callback to trigger once the texture is ready
  91682. * @param onError defines the callback to trigger in case of error
  91683. */
  91684. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  91685. if (Array.isArray(data)) {
  91686. return;
  91687. }
  91688. data = data;
  91689. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  91690. if (info) {
  91691. texture.width = info.width;
  91692. texture.height = info.width;
  91693. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  91694. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  91695. texture.isReady = true;
  91696. if (onLoad) {
  91697. onLoad();
  91698. }
  91699. });
  91700. }
  91701. else if (onError) {
  91702. onError("Can not parse the environment file", null);
  91703. }
  91704. };
  91705. /**
  91706. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91707. * @param data contains the texture data
  91708. * @param texture defines the BabylonJS internal texture
  91709. * @param callback defines the method to call once ready to upload
  91710. */
  91711. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  91712. throw ".env not supported in 2d.";
  91713. };
  91714. return ENVTextureLoader;
  91715. }());
  91716. // Register the loader.
  91717. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  91718. })(BABYLON || (BABYLON = {}));
  91719. //# sourceMappingURL=babylon.envTextureLoader.js.map
  91720. var BABYLON;
  91721. (function (BABYLON) {
  91722. /**
  91723. * Renders a layer on top of an existing scene
  91724. */
  91725. var UtilityLayerRenderer = /** @class */ (function () {
  91726. /**
  91727. * Instantiates a UtilityLayerRenderer
  91728. * @param originalScene the original scene that will be rendered on top of
  91729. */
  91730. function UtilityLayerRenderer(
  91731. /** the original scene that will be rendered on top of */
  91732. originalScene) {
  91733. var _this = this;
  91734. this.originalScene = originalScene;
  91735. this._pointerCaptures = {};
  91736. this._lastPointerEvents = {};
  91737. /**
  91738. * If the utility layer should automatically be rendered on top of existing scene
  91739. */
  91740. this.shouldRender = true;
  91741. /**
  91742. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  91743. */
  91744. this.onlyCheckPointerDownEvents = true;
  91745. /**
  91746. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  91747. */
  91748. this.processAllEvents = false;
  91749. /**
  91750. * Observable raised when the pointer move from the utility layer scene to the main scene
  91751. */
  91752. this.onPointerOutObservable = new BABYLON.Observable();
  91753. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  91754. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  91755. this.utilityLayerScene._allowPostProcessClearColor = false;
  91756. originalScene.getEngine().scenes.pop();
  91757. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  91758. this.utilityLayerScene.detachControl();
  91759. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  91760. if (!_this.processAllEvents) {
  91761. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  91762. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  91763. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  91764. return;
  91765. }
  91766. }
  91767. var pointerEvent = (prePointerInfo.event);
  91768. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  91769. _this._pointerCaptures[pointerEvent.pointerId] = false;
  91770. return;
  91771. }
  91772. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  91773. if (!prePointerInfo.ray && utilityScenePick) {
  91774. prePointerInfo.ray = utilityScenePick.ray;
  91775. }
  91776. // always fire the prepointer oversvable
  91777. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  91778. // allow every non pointer down event to flow to the utility layer
  91779. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  91780. if (!prePointerInfo.skipOnPointerObservable) {
  91781. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  91782. }
  91783. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  91784. _this._pointerCaptures[pointerEvent.pointerId] = false;
  91785. }
  91786. return;
  91787. }
  91788. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  91789. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  91790. if (utilityScenePick && utilityScenePick.hit) {
  91791. if (!prePointerInfo.skipOnPointerObservable) {
  91792. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  91793. }
  91794. prePointerInfo.skipOnPointerObservable = true;
  91795. }
  91796. }
  91797. else {
  91798. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  91799. var pointerEvent_1 = (prePointerInfo.event);
  91800. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  91801. if (originalScenePick && utilityScenePick) {
  91802. // No pick in utility scene
  91803. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  91804. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  91805. // We touched an utility mesh present in the main scene
  91806. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  91807. prePointerInfo.skipOnPointerObservable = true;
  91808. }
  91809. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  91810. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  91811. }
  91812. }
  91813. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  91814. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  91815. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  91816. // If a previous utility layer set this, do not unset this
  91817. if (!prePointerInfo.skipOnPointerObservable) {
  91818. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  91819. }
  91820. }
  91821. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  91822. // We have a pick in both scenes but main is closer than utility
  91823. // We touched an utility mesh present in the main scene
  91824. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  91825. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  91826. prePointerInfo.skipOnPointerObservable = true;
  91827. }
  91828. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  91829. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  91830. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  91831. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  91832. }
  91833. }
  91834. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  91835. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  91836. }
  91837. }
  91838. }
  91839. });
  91840. // Render directly on top of existing scene without clearing
  91841. this.utilityLayerScene.autoClear = false;
  91842. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  91843. if (_this.shouldRender) {
  91844. _this.render();
  91845. }
  91846. });
  91847. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  91848. _this.dispose();
  91849. });
  91850. this._updateCamera();
  91851. }
  91852. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  91853. /**
  91854. * 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)
  91855. */
  91856. get: function () {
  91857. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  91858. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  91859. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  91860. UtilityLayerRenderer._DefaultUtilityLayer = null;
  91861. });
  91862. }
  91863. return UtilityLayerRenderer._DefaultUtilityLayer;
  91864. },
  91865. enumerable: true,
  91866. configurable: true
  91867. });
  91868. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  91869. /**
  91870. * 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)
  91871. */
  91872. get: function () {
  91873. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  91874. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  91875. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  91876. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  91877. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  91878. });
  91879. }
  91880. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  91881. },
  91882. enumerable: true,
  91883. configurable: true
  91884. });
  91885. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  91886. if (!prePointerInfo.skipOnPointerObservable) {
  91887. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  91888. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  91889. }
  91890. };
  91891. /**
  91892. * Renders the utility layers scene on top of the original scene
  91893. */
  91894. UtilityLayerRenderer.prototype.render = function () {
  91895. this._updateCamera();
  91896. if (this.utilityLayerScene.activeCamera) {
  91897. // Set the camera's scene to utility layers scene
  91898. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  91899. var camera = this.utilityLayerScene.activeCamera;
  91900. camera._scene = this.utilityLayerScene;
  91901. if (camera.leftCamera) {
  91902. camera.leftCamera._scene = this.utilityLayerScene;
  91903. }
  91904. if (camera.rightCamera) {
  91905. camera.rightCamera._scene = this.utilityLayerScene;
  91906. }
  91907. this.utilityLayerScene.render(false);
  91908. // Reset camera's scene back to original
  91909. camera._scene = oldScene;
  91910. if (camera.leftCamera) {
  91911. camera.leftCamera._scene = oldScene;
  91912. }
  91913. if (camera.rightCamera) {
  91914. camera.rightCamera._scene = oldScene;
  91915. }
  91916. }
  91917. };
  91918. /**
  91919. * Disposes of the renderer
  91920. */
  91921. UtilityLayerRenderer.prototype.dispose = function () {
  91922. this.onPointerOutObservable.clear();
  91923. if (this._afterRenderObserver) {
  91924. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  91925. }
  91926. if (this._sceneDisposeObserver) {
  91927. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91928. }
  91929. if (this._originalPointerObserver) {
  91930. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  91931. }
  91932. this.utilityLayerScene.dispose();
  91933. };
  91934. UtilityLayerRenderer.prototype._updateCamera = function () {
  91935. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  91936. };
  91937. UtilityLayerRenderer._DefaultUtilityLayer = null;
  91938. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  91939. return UtilityLayerRenderer;
  91940. }());
  91941. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  91942. })(BABYLON || (BABYLON = {}));
  91943. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  91944. //# sourceMappingURL=babylon.behavior.js.map
  91945. var BABYLON;
  91946. (function (BABYLON) {
  91947. /**
  91948. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  91949. */
  91950. var PointerDragBehavior = /** @class */ (function () {
  91951. /**
  91952. * Creates a pointer drag behavior that can be attached to a mesh
  91953. * @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)
  91954. */
  91955. function PointerDragBehavior(options) {
  91956. /**
  91957. * 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)
  91958. */
  91959. this.maxDragAngle = 0;
  91960. /**
  91961. * @hidden
  91962. */
  91963. this._useAlternatePickedPointAboveMaxDragAngle = false;
  91964. /**
  91965. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  91966. */
  91967. this.currentDraggingPointerID = -1;
  91968. /**
  91969. * If the behavior is currently in a dragging state
  91970. */
  91971. this.dragging = false;
  91972. /**
  91973. * 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)
  91974. */
  91975. this.dragDeltaRatio = 0.2;
  91976. /**
  91977. * If the drag plane orientation should be updated during the dragging (Default: true)
  91978. */
  91979. this.updateDragPlane = true;
  91980. // Debug mode will display drag planes to help visualize behavior
  91981. this._debugMode = false;
  91982. this._moving = false;
  91983. /**
  91984. * Fires each time the attached mesh is dragged with the pointer
  91985. * * delta between last drag position and current drag position in world space
  91986. * * dragDistance along the drag axis
  91987. * * dragPlaneNormal normal of the current drag plane used during the drag
  91988. * * dragPlanePoint in world space where the drag intersects the drag plane
  91989. */
  91990. this.onDragObservable = new BABYLON.Observable();
  91991. /**
  91992. * Fires each time a drag begins (eg. mouse down on mesh)
  91993. */
  91994. this.onDragStartObservable = new BABYLON.Observable();
  91995. /**
  91996. * Fires each time a drag ends (eg. mouse release after drag)
  91997. */
  91998. this.onDragEndObservable = new BABYLON.Observable();
  91999. /**
  92000. * If the attached mesh should be moved when dragged
  92001. */
  92002. this.moveAttached = true;
  92003. /**
  92004. * If the drag behavior will react to drag events (Default: true)
  92005. */
  92006. this.enabled = true;
  92007. /**
  92008. * If camera controls should be detached during the drag
  92009. */
  92010. this.detachCameraControls = true;
  92011. /**
  92012. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  92013. */
  92014. this.useObjectOrienationForDragging = true;
  92015. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  92016. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  92017. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  92018. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  92019. this._attachedElement = null;
  92020. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  92021. this._lastPointerRay = {};
  92022. this._dragDelta = new BABYLON.Vector3();
  92023. // Variables to avoid instantiation in the below method
  92024. this._pointA = new BABYLON.Vector3(0, 0, 0);
  92025. this._pointB = new BABYLON.Vector3(0, 0, 0);
  92026. this._pointC = new BABYLON.Vector3(0, 0, 0);
  92027. this._lineA = new BABYLON.Vector3(0, 0, 0);
  92028. this._lineB = new BABYLON.Vector3(0, 0, 0);
  92029. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  92030. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  92031. this._options = options ? options : {};
  92032. var optionCount = 0;
  92033. if (this._options.dragAxis) {
  92034. optionCount++;
  92035. }
  92036. if (this._options.dragPlaneNormal) {
  92037. optionCount++;
  92038. }
  92039. if (optionCount > 1) {
  92040. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  92041. }
  92042. }
  92043. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  92044. /**
  92045. * The name of the behavior
  92046. */
  92047. get: function () {
  92048. return "PointerDrag";
  92049. },
  92050. enumerable: true,
  92051. configurable: true
  92052. });
  92053. /**
  92054. * Initializes the behavior
  92055. */
  92056. PointerDragBehavior.prototype.init = function () { };
  92057. /**
  92058. * Attaches the drag behavior the passed in mesh
  92059. * @param ownerNode The mesh that will be dragged around once attached
  92060. */
  92061. PointerDragBehavior.prototype.attach = function (ownerNode) {
  92062. var _this = this;
  92063. this._scene = ownerNode.getScene();
  92064. this._attachedNode = ownerNode;
  92065. // Initialize drag plane to not interfere with existing scene
  92066. if (!PointerDragBehavior._planeScene) {
  92067. if (this._debugMode) {
  92068. PointerDragBehavior._planeScene = this._scene;
  92069. }
  92070. else {
  92071. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  92072. PointerDragBehavior._planeScene.detachControl();
  92073. this._scene.getEngine().scenes.pop();
  92074. this._scene.onDisposeObservable.addOnce(function () {
  92075. PointerDragBehavior._planeScene.dispose();
  92076. PointerDragBehavior._planeScene = null;
  92077. });
  92078. }
  92079. }
  92080. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  92081. // State of the drag
  92082. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  92083. var pickPredicate = function (m) {
  92084. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  92085. };
  92086. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  92087. if (!_this.enabled) {
  92088. return;
  92089. }
  92090. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  92091. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  92092. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  92093. }
  92094. }
  92095. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  92096. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  92097. _this.releaseDrag();
  92098. }
  92099. }
  92100. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  92101. var pointerId = pointerInfo.event.pointerId;
  92102. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  92103. if (!_this._lastPointerRay[pointerId]) {
  92104. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  92105. }
  92106. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  92107. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  92108. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  92109. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  92110. _this._moveDrag(pointerInfo.pickInfo.ray);
  92111. }
  92112. }
  92113. }
  92114. });
  92115. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  92116. if (_this._moving && _this.moveAttached) {
  92117. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  92118. // Slowly move mesh to avoid jitter
  92119. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  92120. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  92121. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  92122. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  92123. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  92124. }
  92125. });
  92126. };
  92127. PointerDragBehavior.prototype.releaseDrag = function () {
  92128. this.dragging = false;
  92129. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  92130. this.currentDraggingPointerID = -1;
  92131. this._moving = false;
  92132. // Reattach camera controls
  92133. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  92134. this._scene.activeCamera.attachControl(this._attachedElement, true);
  92135. }
  92136. };
  92137. /**
  92138. * Simulates the start of a pointer drag event on the behavior
  92139. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  92140. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  92141. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  92142. */
  92143. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  92144. if (pointerId === void 0) { pointerId = 1; }
  92145. this._startDrag(pointerId, fromRay, startPickedPoint);
  92146. if (this._lastPointerRay[pointerId]) {
  92147. // if there was a last pointer ray drag the object there
  92148. this._moveDrag(this._lastPointerRay[pointerId]);
  92149. }
  92150. };
  92151. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  92152. if (pointerId === void 0) { pointerId = 1; }
  92153. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  92154. return;
  92155. }
  92156. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  92157. // Create start ray from the camera to the object
  92158. if (fromRay) {
  92159. this._startDragRay.direction.copyFrom(fromRay.direction);
  92160. this._startDragRay.origin.copyFrom(fromRay.origin);
  92161. }
  92162. else {
  92163. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  92164. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  92165. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  92166. }
  92167. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  92168. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  92169. if (pickedPoint) {
  92170. this.dragging = true;
  92171. this.currentDraggingPointerID = 1;
  92172. this.lastDragPosition.copyFrom(pickedPoint);
  92173. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  92174. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  92175. // Detatch camera controls
  92176. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  92177. if (this._scene.activeCamera.inputs.attachedElement) {
  92178. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  92179. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  92180. }
  92181. else {
  92182. this._attachedElement = null;
  92183. }
  92184. }
  92185. }
  92186. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  92187. };
  92188. PointerDragBehavior.prototype._moveDrag = function (ray) {
  92189. this._moving = true;
  92190. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  92191. if (pickedPoint) {
  92192. if (this.updateDragPlane) {
  92193. this._updateDragPlanePosition(ray, pickedPoint);
  92194. }
  92195. var dragLength = 0;
  92196. // depending on the drag mode option drag accordingly
  92197. if (this._options.dragAxis) {
  92198. // Convert local drag axis to world
  92199. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  92200. // Project delta drag from the drag plane onto the drag axis
  92201. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  92202. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  92203. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  92204. }
  92205. else {
  92206. dragLength = this._dragDelta.length();
  92207. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  92208. }
  92209. this._targetPosition.addInPlace(this._dragDelta);
  92210. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  92211. this.lastDragPosition.copyFrom(pickedPoint);
  92212. }
  92213. };
  92214. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  92215. var _this = this;
  92216. if (!ray) {
  92217. return null;
  92218. }
  92219. // Calculate angle between plane normal and ray
  92220. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  92221. // Correct if ray is casted from oposite side
  92222. if (angle > Math.PI / 2) {
  92223. angle = Math.PI - angle;
  92224. }
  92225. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  92226. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  92227. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  92228. // Invert ray direction along the towards object axis
  92229. this._tmpVector.copyFrom(ray.direction);
  92230. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  92231. this._alternatePickedPoint.normalize();
  92232. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  92233. this._tmpVector.addInPlace(this._alternatePickedPoint);
  92234. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  92235. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  92236. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  92237. this._alternatePickedPoint.addInPlace(this._tmpVector);
  92238. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  92239. return this._alternatePickedPoint;
  92240. }
  92241. else {
  92242. return null;
  92243. }
  92244. }
  92245. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  92246. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  92247. return pickResult.pickedPoint;
  92248. }
  92249. else {
  92250. return null;
  92251. }
  92252. };
  92253. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  92254. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  92255. this._pointA.copyFrom(dragPlanePosition);
  92256. if (this._options.dragAxis) {
  92257. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  92258. // Calculate plane normal in direction of camera but perpendicular to drag axis
  92259. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  92260. ray.origin.subtractToRef(this._pointA, this._pointC);
  92261. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  92262. // Get perpendicular line from direction to camera and drag axis
  92263. this._pointB.subtractToRef(this._pointA, this._lineA);
  92264. this._pointC.subtractToRef(this._pointA, this._lineB);
  92265. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  92266. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  92267. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  92268. this._lookAt.normalize();
  92269. this._dragPlane.position.copyFrom(this._pointA);
  92270. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  92271. this._dragPlane.lookAt(this._lookAt);
  92272. }
  92273. else if (this._options.dragPlaneNormal) {
  92274. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  92275. this._dragPlane.position.copyFrom(this._pointA);
  92276. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  92277. this._dragPlane.lookAt(this._lookAt);
  92278. }
  92279. else {
  92280. this._dragPlane.position.copyFrom(this._pointA);
  92281. this._dragPlane.lookAt(ray.origin);
  92282. }
  92283. this._dragPlane.computeWorldMatrix(true);
  92284. };
  92285. /**
  92286. * Detaches the behavior from the mesh
  92287. */
  92288. PointerDragBehavior.prototype.detach = function () {
  92289. if (this._pointerObserver) {
  92290. this._scene.onPointerObservable.remove(this._pointerObserver);
  92291. }
  92292. if (this._beforeRenderObserver) {
  92293. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  92294. }
  92295. };
  92296. return PointerDragBehavior;
  92297. }());
  92298. BABYLON.PointerDragBehavior = PointerDragBehavior;
  92299. })(BABYLON || (BABYLON = {}));
  92300. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  92301. var BABYLON;
  92302. (function (BABYLON) {
  92303. /**
  92304. * A behavior that when attached to a mesh will allow the mesh to be scaled
  92305. */
  92306. var MultiPointerScaleBehavior = /** @class */ (function () {
  92307. function MultiPointerScaleBehavior() {
  92308. this._startDistance = 0;
  92309. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  92310. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  92311. this._sceneRenderObserver = null;
  92312. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  92313. this._dragBehaviorA.moveAttached = false;
  92314. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  92315. this._dragBehaviorB.moveAttached = false;
  92316. }
  92317. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  92318. /**
  92319. * The name of the behavior
  92320. */
  92321. get: function () {
  92322. return "MultiPointerScale";
  92323. },
  92324. enumerable: true,
  92325. configurable: true
  92326. });
  92327. /**
  92328. * Initializes the behavior
  92329. */
  92330. MultiPointerScaleBehavior.prototype.init = function () { };
  92331. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  92332. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  92333. };
  92334. /**
  92335. * Attaches the scale behavior the passed in mesh
  92336. * @param ownerNode The mesh that will be scaled around once attached
  92337. */
  92338. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  92339. var _this = this;
  92340. this._ownerNode = ownerNode;
  92341. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  92342. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  92343. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92344. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  92345. _this._dragBehaviorA.releaseDrag();
  92346. }
  92347. else {
  92348. _this._initialScale.copyFrom(ownerNode.scaling);
  92349. _this._startDistance = _this._getCurrentDistance();
  92350. }
  92351. }
  92352. });
  92353. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  92354. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92355. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  92356. _this._dragBehaviorB.releaseDrag();
  92357. }
  92358. else {
  92359. _this._initialScale.copyFrom(ownerNode.scaling);
  92360. _this._startDistance = _this._getCurrentDistance();
  92361. }
  92362. }
  92363. });
  92364. // Once both drag behaviors are active scale based on the distance between the two pointers
  92365. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  92366. behavior.onDragObservable.add(function () {
  92367. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92368. var ratio = _this._getCurrentDistance() / _this._startDistance;
  92369. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  92370. }
  92371. });
  92372. });
  92373. ownerNode.addBehavior(this._dragBehaviorA);
  92374. ownerNode.addBehavior(this._dragBehaviorB);
  92375. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  92376. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  92377. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92378. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  92379. if (change.length() > 0.01) {
  92380. ownerNode.scaling.addInPlace(change);
  92381. }
  92382. }
  92383. });
  92384. };
  92385. /**
  92386. * Detaches the behavior from the mesh
  92387. */
  92388. MultiPointerScaleBehavior.prototype.detach = function () {
  92389. var _this = this;
  92390. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  92391. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  92392. behavior.onDragStartObservable.clear();
  92393. behavior.onDragObservable.clear();
  92394. _this._ownerNode.removeBehavior(behavior);
  92395. });
  92396. };
  92397. return MultiPointerScaleBehavior;
  92398. }());
  92399. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  92400. })(BABYLON || (BABYLON = {}));
  92401. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  92402. var BABYLON;
  92403. (function (BABYLON) {
  92404. /**
  92405. * 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
  92406. */
  92407. var SixDofDragBehavior = /** @class */ (function () {
  92408. function SixDofDragBehavior() {
  92409. this._sceneRenderObserver = null;
  92410. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  92411. this._moving = false;
  92412. this._startingOrientation = new BABYLON.Quaternion();
  92413. /**
  92414. * 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)
  92415. */
  92416. this.zDragFactor = 3;
  92417. /**
  92418. * If the behavior is currently in a dragging state
  92419. */
  92420. this.dragging = false;
  92421. /**
  92422. * 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)
  92423. */
  92424. this.dragDeltaRatio = 0.2;
  92425. /**
  92426. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  92427. */
  92428. this.currentDraggingPointerID = -1;
  92429. /**
  92430. * If camera controls should be detached during the drag
  92431. */
  92432. this.detachCameraControls = true;
  92433. }
  92434. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  92435. /**
  92436. * The name of the behavior
  92437. */
  92438. get: function () {
  92439. return "SixDofDrag";
  92440. },
  92441. enumerable: true,
  92442. configurable: true
  92443. });
  92444. /**
  92445. * Initializes the behavior
  92446. */
  92447. SixDofDragBehavior.prototype.init = function () { };
  92448. /**
  92449. * Attaches the scale behavior the passed in mesh
  92450. * @param ownerNode The mesh that will be scaled around once attached
  92451. */
  92452. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  92453. var _this = this;
  92454. this._ownerNode = ownerNode;
  92455. this._scene = this._ownerNode.getScene();
  92456. if (!SixDofDragBehavior._virtualScene) {
  92457. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  92458. this._scene.getEngine().scenes.pop();
  92459. }
  92460. var pickedMesh = null;
  92461. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  92462. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  92463. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  92464. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  92465. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  92466. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  92467. var pickPredicate = function (m) {
  92468. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  92469. };
  92470. var attachedElement = null;
  92471. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  92472. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  92473. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  92474. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  92475. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  92476. }
  92477. pickedMesh = _this._ownerNode;
  92478. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  92479. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  92480. // Set position and orientation of the controller
  92481. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  92482. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  92483. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  92484. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  92485. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  92486. if (!pickedMesh.rotationQuaternion) {
  92487. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  92488. }
  92489. var oldParent = pickedMesh.parent;
  92490. pickedMesh.setParent(null);
  92491. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  92492. pickedMesh.setParent(oldParent);
  92493. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  92494. // Update state
  92495. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  92496. _this.dragging = true;
  92497. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  92498. // Detatch camera controls
  92499. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  92500. if (_this._scene.activeCamera.inputs.attachedElement) {
  92501. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  92502. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  92503. }
  92504. else {
  92505. attachedElement = null;
  92506. }
  92507. }
  92508. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  92509. }
  92510. }
  92511. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  92512. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  92513. _this.dragging = false;
  92514. _this._moving = false;
  92515. _this.currentDraggingPointerID = -1;
  92516. pickedMesh = null;
  92517. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  92518. // Reattach camera controls
  92519. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  92520. _this._scene.activeCamera.attachControl(attachedElement, true);
  92521. }
  92522. }
  92523. }
  92524. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  92525. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  92526. var zDragFactor = _this.zDragFactor;
  92527. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  92528. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  92529. zDragFactor = 0;
  92530. }
  92531. // Calculate controller drag distance in controller space
  92532. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  92533. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  92534. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  92535. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  92536. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  92537. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  92538. if (_this._virtualDragMesh.position.z < 0) {
  92539. _this._virtualDragMesh.position.z = 0;
  92540. }
  92541. // Update the controller position
  92542. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  92543. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  92544. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  92545. // Move the virtualObjectsPosition into the picked mesh's space if needed
  92546. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  92547. if (pickedMesh.parent) {
  92548. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  92549. }
  92550. if (!_this._moving) {
  92551. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  92552. }
  92553. _this._moving = true;
  92554. }
  92555. }
  92556. });
  92557. var tmpQuaternion = new BABYLON.Quaternion();
  92558. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  92559. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  92560. if (_this.dragging && _this._moving && pickedMesh) {
  92561. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  92562. // Slowly move mesh to avoid jitter
  92563. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  92564. // Get change in rotation
  92565. tmpQuaternion.copyFrom(_this._startingOrientation);
  92566. tmpQuaternion.x = -tmpQuaternion.x;
  92567. tmpQuaternion.y = -tmpQuaternion.y;
  92568. tmpQuaternion.z = -tmpQuaternion.z;
  92569. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  92570. // Convert change in rotation to only y axis rotation
  92571. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  92572. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  92573. // Slowly move mesh to avoid jitter
  92574. var oldParent = pickedMesh.parent;
  92575. pickedMesh.setParent(null);
  92576. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  92577. pickedMesh.setParent(oldParent);
  92578. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  92579. }
  92580. });
  92581. };
  92582. /**
  92583. * Detaches the behavior from the mesh
  92584. */
  92585. SixDofDragBehavior.prototype.detach = function () {
  92586. if (this._scene) {
  92587. this._scene.onPointerObservable.remove(this._pointerObserver);
  92588. }
  92589. if (this._ownerNode) {
  92590. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  92591. }
  92592. if (this._virtualOriginMesh) {
  92593. this._virtualOriginMesh.dispose();
  92594. }
  92595. if (this._virtualDragMesh) {
  92596. this._virtualDragMesh.dispose();
  92597. }
  92598. };
  92599. return SixDofDragBehavior;
  92600. }());
  92601. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  92602. })(BABYLON || (BABYLON = {}));
  92603. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  92604. var BABYLON;
  92605. (function (BABYLON) {
  92606. /**
  92607. * @hidden
  92608. */
  92609. var FaceDirectionInfo = /** @class */ (function () {
  92610. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  92611. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  92612. if (diff === void 0) { diff = 0; }
  92613. if (ignore === void 0) { ignore = false; }
  92614. this.direction = direction;
  92615. this.rotatedDirection = rotatedDirection;
  92616. this.diff = diff;
  92617. this.ignore = ignore;
  92618. }
  92619. return FaceDirectionInfo;
  92620. }());
  92621. /**
  92622. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  92623. */
  92624. var AttachToBoxBehavior = /** @class */ (function () {
  92625. /**
  92626. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  92627. * @param ui The transform node that should be attched to the mesh
  92628. */
  92629. function AttachToBoxBehavior(ui) {
  92630. this.ui = ui;
  92631. /**
  92632. * The name of the behavior
  92633. */
  92634. this.name = "AttachToBoxBehavior";
  92635. /**
  92636. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  92637. */
  92638. this.distanceAwayFromFace = 0.15;
  92639. /**
  92640. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  92641. */
  92642. this.distanceAwayFromBottomOfFace = 0.15;
  92643. 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))];
  92644. this._tmpMatrix = new BABYLON.Matrix();
  92645. this._tmpVector = new BABYLON.Vector3();
  92646. this._zeroVector = BABYLON.Vector3.Zero();
  92647. this._lookAtTmpMatrix = new BABYLON.Matrix();
  92648. /* Does nothing */
  92649. }
  92650. /**
  92651. * Initializes the behavior
  92652. */
  92653. AttachToBoxBehavior.prototype.init = function () {
  92654. /* Does nothing */
  92655. };
  92656. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  92657. var _this = this;
  92658. // Go over each face and calculate the angle between the face's normal and targetDirection
  92659. this._faceVectors.forEach(function (v) {
  92660. if (!_this._target.rotationQuaternion) {
  92661. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  92662. }
  92663. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  92664. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  92665. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  92666. });
  92667. // Return the face information of the one with the normal closeset to target direction
  92668. return this._faceVectors.reduce(function (min, p) {
  92669. if (min.ignore) {
  92670. return p;
  92671. }
  92672. else if (p.ignore) {
  92673. return min;
  92674. }
  92675. else {
  92676. return min.diff < p.diff ? min : p;
  92677. }
  92678. }, this._faceVectors[0]);
  92679. };
  92680. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  92681. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  92682. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  92683. this._lookAtTmpMatrix.invert();
  92684. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  92685. };
  92686. /**
  92687. * Attaches the AttachToBoxBehavior to the passed in mesh
  92688. * @param target The mesh that the specified node will be attached to
  92689. */
  92690. AttachToBoxBehavior.prototype.attach = function (target) {
  92691. var _this = this;
  92692. this._target = target;
  92693. this._scene = this._target.getScene();
  92694. // Every frame, update the app bars position
  92695. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  92696. if (!_this._scene.activeCamera) {
  92697. return;
  92698. }
  92699. // Find the face closest to the cameras position
  92700. var cameraPos = _this._scene.activeCamera.position;
  92701. if (_this._scene.activeCamera.devicePosition) {
  92702. cameraPos = _this._scene.activeCamera.devicePosition;
  92703. }
  92704. var facing = _this._closestFace(cameraPos.subtract(target.position));
  92705. if (_this._scene.activeCamera.leftCamera) {
  92706. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  92707. }
  92708. else {
  92709. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  92710. }
  92711. // Get camera up direction
  92712. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  92713. // Ignore faces to not select a parrelel face for the up vector of the UI
  92714. _this._faceVectors.forEach(function (v) {
  92715. if (facing.direction.x && v.direction.x) {
  92716. v.ignore = true;
  92717. }
  92718. if (facing.direction.y && v.direction.y) {
  92719. v.ignore = true;
  92720. }
  92721. if (facing.direction.z && v.direction.z) {
  92722. v.ignore = true;
  92723. }
  92724. });
  92725. var facingUp = _this._closestFace(_this._tmpVector);
  92726. // Unignore faces
  92727. _this._faceVectors.forEach(function (v) {
  92728. v.ignore = false;
  92729. });
  92730. // Position the app bar on that face
  92731. _this.ui.position.copyFrom(target.position);
  92732. if (facing.direction.x) {
  92733. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  92734. _this.ui.position.addInPlace(_this._tmpVector);
  92735. }
  92736. if (facing.direction.y) {
  92737. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  92738. _this.ui.position.addInPlace(_this._tmpVector);
  92739. }
  92740. if (facing.direction.z) {
  92741. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  92742. _this.ui.position.addInPlace(_this._tmpVector);
  92743. }
  92744. // Rotate to be oriented properly to the camera
  92745. if (!_this.ui.rotationQuaternion) {
  92746. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  92747. }
  92748. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  92749. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  92750. // Place ui the correct distance from the bottom of the mesh
  92751. if (facingUp.direction.x) {
  92752. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  92753. }
  92754. if (facingUp.direction.y) {
  92755. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  92756. }
  92757. if (facingUp.direction.z) {
  92758. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  92759. }
  92760. _this.ui.position.addInPlace(_this._tmpVector);
  92761. });
  92762. };
  92763. /**
  92764. * Detaches the behavior from the mesh
  92765. */
  92766. AttachToBoxBehavior.prototype.detach = function () {
  92767. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  92768. };
  92769. return AttachToBoxBehavior;
  92770. }());
  92771. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  92772. })(BABYLON || (BABYLON = {}));
  92773. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  92774. var BABYLON;
  92775. (function (BABYLON) {
  92776. /**
  92777. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  92778. */
  92779. var FadeInOutBehavior = /** @class */ (function () {
  92780. /**
  92781. * Instatiates the FadeInOutBehavior
  92782. */
  92783. function FadeInOutBehavior() {
  92784. var _this = this;
  92785. /**
  92786. * Time in milliseconds to delay before fading in (Default: 0)
  92787. */
  92788. this.delay = 0;
  92789. /**
  92790. * Time in milliseconds for the mesh to fade in (Default: 300)
  92791. */
  92792. this.fadeInTime = 300;
  92793. this._millisecondsPerFrame = 1000 / 60;
  92794. this._hovered = false;
  92795. this._hoverValue = 0;
  92796. this._ownerNode = null;
  92797. this._update = function () {
  92798. if (_this._ownerNode) {
  92799. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  92800. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  92801. if (_this._ownerNode.visibility > 1) {
  92802. _this._setAllVisibility(_this._ownerNode, 1);
  92803. _this._hoverValue = _this.fadeInTime + _this.delay;
  92804. return;
  92805. }
  92806. else if (_this._ownerNode.visibility < 0) {
  92807. _this._setAllVisibility(_this._ownerNode, 0);
  92808. if (_this._hoverValue < 0) {
  92809. _this._hoverValue = 0;
  92810. return;
  92811. }
  92812. }
  92813. setTimeout(_this._update, _this._millisecondsPerFrame);
  92814. }
  92815. };
  92816. }
  92817. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  92818. /**
  92819. * The name of the behavior
  92820. */
  92821. get: function () {
  92822. return "FadeInOut";
  92823. },
  92824. enumerable: true,
  92825. configurable: true
  92826. });
  92827. /**
  92828. * Initializes the behavior
  92829. */
  92830. FadeInOutBehavior.prototype.init = function () {
  92831. };
  92832. /**
  92833. * Attaches the fade behavior on the passed in mesh
  92834. * @param ownerNode The mesh that will be faded in/out once attached
  92835. */
  92836. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  92837. this._ownerNode = ownerNode;
  92838. this._setAllVisibility(this._ownerNode, 0);
  92839. };
  92840. /**
  92841. * Detaches the behavior from the mesh
  92842. */
  92843. FadeInOutBehavior.prototype.detach = function () {
  92844. this._ownerNode = null;
  92845. };
  92846. /**
  92847. * Triggers the mesh to begin fading in or out
  92848. * @param value if the object should fade in or out (true to fade in)
  92849. */
  92850. FadeInOutBehavior.prototype.fadeIn = function (value) {
  92851. this._hovered = value;
  92852. this._update();
  92853. };
  92854. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  92855. var _this = this;
  92856. mesh.visibility = value;
  92857. mesh.getChildMeshes().forEach(function (c) {
  92858. _this._setAllVisibility(c, value);
  92859. });
  92860. };
  92861. return FadeInOutBehavior;
  92862. }());
  92863. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  92864. })(BABYLON || (BABYLON = {}));
  92865. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  92866. var BABYLON;
  92867. (function (BABYLON) {
  92868. /**
  92869. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  92870. */
  92871. var Gizmo = /** @class */ (function () {
  92872. /**
  92873. * Creates a gizmo
  92874. * @param gizmoLayer The utility layer the gizmo will be added to
  92875. */
  92876. function Gizmo(
  92877. /** The utility layer the gizmo will be added to */
  92878. gizmoLayer) {
  92879. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92880. var _this = this;
  92881. this.gizmoLayer = gizmoLayer;
  92882. /**
  92883. * Ratio for the scale of the gizmo (Default: 1)
  92884. */
  92885. this.scaleRatio = 1;
  92886. this._tmpMatrix = new BABYLON.Matrix();
  92887. /**
  92888. * If a custom mesh has been set (Default: false)
  92889. */
  92890. this._customMeshSet = false;
  92891. /**
  92892. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  92893. */
  92894. this.updateGizmoRotationToMatchAttachedMesh = true;
  92895. /**
  92896. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  92897. */
  92898. this.updateGizmoPositionToMatchAttachedMesh = true;
  92899. /**
  92900. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  92901. */
  92902. this._updateScale = true;
  92903. this._interactionsEnabled = true;
  92904. this._tempVector = new BABYLON.Vector3();
  92905. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  92906. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  92907. _this._update();
  92908. });
  92909. this.attachedMesh = null;
  92910. }
  92911. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  92912. /**
  92913. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  92914. * * When set, interactions will be enabled
  92915. */
  92916. get: function () {
  92917. return this._attachedMesh;
  92918. },
  92919. set: function (value) {
  92920. this._attachedMesh = value;
  92921. this._rootMesh.setEnabled(value ? true : false);
  92922. this._attachedMeshChanged(value);
  92923. },
  92924. enumerable: true,
  92925. configurable: true
  92926. });
  92927. /**
  92928. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  92929. * @param mesh The mesh to replace the default mesh of the gizmo
  92930. */
  92931. Gizmo.prototype.setCustomMesh = function (mesh) {
  92932. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  92933. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  92934. }
  92935. this._rootMesh.getChildMeshes().forEach(function (c) {
  92936. c.dispose();
  92937. });
  92938. mesh.parent = this._rootMesh;
  92939. this._customMeshSet = true;
  92940. };
  92941. Gizmo.prototype._attachedMeshChanged = function (value) {
  92942. };
  92943. /**
  92944. * @hidden
  92945. * Updates the gizmo to match the attached mesh's position/rotation
  92946. */
  92947. Gizmo.prototype._update = function () {
  92948. if (this.attachedMesh) {
  92949. if (this.updateGizmoRotationToMatchAttachedMesh) {
  92950. if (!this._rootMesh.rotationQuaternion) {
  92951. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  92952. }
  92953. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  92954. this._tempVector.copyFrom(this.attachedMesh.scaling);
  92955. if (this.attachedMesh.scaling.x < 0) {
  92956. this.attachedMesh.scaling.x *= -1;
  92957. }
  92958. if (this.attachedMesh.scaling.y < 0) {
  92959. this.attachedMesh.scaling.y *= -1;
  92960. }
  92961. if (this.attachedMesh.scaling.z < 0) {
  92962. this.attachedMesh.scaling.z *= -1;
  92963. }
  92964. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  92965. this.attachedMesh.scaling.copyFrom(this._tempVector);
  92966. this.attachedMesh.computeWorldMatrix();
  92967. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  92968. }
  92969. else if (this._rootMesh.rotationQuaternion) {
  92970. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  92971. }
  92972. if (this.updateGizmoPositionToMatchAttachedMesh) {
  92973. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  92974. }
  92975. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  92976. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  92977. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  92978. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  92979. }
  92980. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  92981. var dist = this._tempVector.length() * this.scaleRatio;
  92982. this._rootMesh.scaling.set(dist, dist, dist);
  92983. }
  92984. }
  92985. };
  92986. /**
  92987. * Disposes of the gizmo
  92988. */
  92989. Gizmo.prototype.dispose = function () {
  92990. this._rootMesh.dispose();
  92991. if (this._beforeRenderObserver) {
  92992. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  92993. }
  92994. };
  92995. return Gizmo;
  92996. }());
  92997. BABYLON.Gizmo = Gizmo;
  92998. })(BABYLON || (BABYLON = {}));
  92999. //# sourceMappingURL=babylon.gizmo.js.map
  93000. var BABYLON;
  93001. (function (BABYLON) {
  93002. /**
  93003. * Single axis drag gizmo
  93004. */
  93005. var AxisDragGizmo = /** @class */ (function (_super) {
  93006. __extends(AxisDragGizmo, _super);
  93007. /**
  93008. * Creates an AxisDragGizmo
  93009. * @param gizmoLayer The utility layer the gizmo will be added to
  93010. * @param dragAxis The axis which the gizmo will be able to drag on
  93011. * @param color The color of the gizmo
  93012. */
  93013. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  93014. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93015. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93016. var _this = _super.call(this, gizmoLayer) || this;
  93017. _this._pointerObserver = null;
  93018. /**
  93019. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93020. */
  93021. _this.snapDistance = 0;
  93022. /**
  93023. * Event that fires each time the gizmo snaps to a new location.
  93024. * * snapDistance is the the change in distance
  93025. */
  93026. _this.onSnapObservable = new BABYLON.Observable();
  93027. // Create Material
  93028. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93029. coloredMaterial.disableLighting = true;
  93030. coloredMaterial.emissiveColor = color;
  93031. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93032. hoverMaterial.disableLighting = true;
  93033. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93034. // Build mesh on root node
  93035. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93036. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  93037. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  93038. arrowTail.color = coloredMaterial.emissiveColor;
  93039. arrow.addChild(arrowMesh);
  93040. arrow.addChild(arrowTail);
  93041. // Position arrow pointing in its drag axis
  93042. arrowMesh.scaling.scaleInPlace(0.05);
  93043. arrowMesh.material = coloredMaterial;
  93044. arrowMesh.rotation.x = Math.PI / 2;
  93045. arrowMesh.position.z += 0.3;
  93046. arrowTail.scaling.scaleInPlace(0.26);
  93047. arrowTail.rotation.x = Math.PI / 2;
  93048. arrowTail.material = coloredMaterial;
  93049. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  93050. arrow.scaling.scaleInPlace(1 / 3);
  93051. _this._rootMesh.addChild(arrow);
  93052. var currentSnapDragDistance = 0;
  93053. var tmpVector = new BABYLON.Vector3();
  93054. var tmpSnapEvent = { snapDistance: 0 };
  93055. // Add drag behavior to handle events when the gizmo is dragged
  93056. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93057. _this.dragBehavior.moveAttached = false;
  93058. _this._rootMesh.addBehavior(_this.dragBehavior);
  93059. var localDelta = new BABYLON.Vector3();
  93060. var tmpMatrix = new BABYLON.Matrix();
  93061. _this.dragBehavior.onDragObservable.add(function (event) {
  93062. if (_this.attachedMesh) {
  93063. // Convert delta to local translation if it has a parent
  93064. if (_this.attachedMesh.parent) {
  93065. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  93066. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  93067. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  93068. }
  93069. else {
  93070. localDelta.copyFrom(event.delta);
  93071. }
  93072. // Snapping logic
  93073. if (_this.snapDistance == 0) {
  93074. _this.attachedMesh.position.addInPlace(localDelta);
  93075. }
  93076. else {
  93077. currentSnapDragDistance += event.dragDistance;
  93078. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  93079. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  93080. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  93081. localDelta.normalizeToRef(tmpVector);
  93082. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  93083. _this.attachedMesh.position.addInPlace(tmpVector);
  93084. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  93085. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  93086. }
  93087. }
  93088. }
  93089. });
  93090. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93091. if (_this._customMeshSet) {
  93092. return;
  93093. }
  93094. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  93095. var material = isHovered ? hoverMaterial : coloredMaterial;
  93096. _this._rootMesh.getChildMeshes().forEach(function (m) {
  93097. m.material = material;
  93098. if (m.color) {
  93099. m.color = material.emissiveColor;
  93100. }
  93101. });
  93102. });
  93103. return _this;
  93104. }
  93105. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  93106. if (this.dragBehavior) {
  93107. this.dragBehavior.enabled = value ? true : false;
  93108. }
  93109. };
  93110. /**
  93111. * Disposes of the gizmo
  93112. */
  93113. AxisDragGizmo.prototype.dispose = function () {
  93114. this.onSnapObservable.clear();
  93115. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93116. this.dragBehavior.detach();
  93117. _super.prototype.dispose.call(this);
  93118. };
  93119. return AxisDragGizmo;
  93120. }(BABYLON.Gizmo));
  93121. BABYLON.AxisDragGizmo = AxisDragGizmo;
  93122. })(BABYLON || (BABYLON = {}));
  93123. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  93124. var BABYLON;
  93125. (function (BABYLON) {
  93126. /**
  93127. * Single axis scale gizmo
  93128. */
  93129. var AxisScaleGizmo = /** @class */ (function (_super) {
  93130. __extends(AxisScaleGizmo, _super);
  93131. /**
  93132. * Creates an AxisScaleGizmo
  93133. * @param gizmoLayer The utility layer the gizmo will be added to
  93134. * @param dragAxis The axis which the gizmo will be able to scale on
  93135. * @param color The color of the gizmo
  93136. */
  93137. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  93138. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93139. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93140. var _this = _super.call(this, gizmoLayer) || this;
  93141. _this._pointerObserver = null;
  93142. /**
  93143. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93144. */
  93145. _this.snapDistance = 0;
  93146. /**
  93147. * Event that fires each time the gizmo snaps to a new location.
  93148. * * snapDistance is the the change in distance
  93149. */
  93150. _this.onSnapObservable = new BABYLON.Observable();
  93151. /**
  93152. * If the scaling operation should be done on all axis (default: false)
  93153. */
  93154. _this.uniformScaling = false;
  93155. // Create Material
  93156. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93157. _this._coloredMaterial.disableLighting = true;
  93158. _this._coloredMaterial.emissiveColor = color;
  93159. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93160. hoverMaterial.disableLighting = true;
  93161. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93162. // Build mesh on root node
  93163. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93164. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  93165. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  93166. arrowTail.color = _this._coloredMaterial.emissiveColor;
  93167. arrow.addChild(arrowMesh);
  93168. arrow.addChild(arrowTail);
  93169. // Position arrow pointing in its drag axis
  93170. arrowMesh.scaling.scaleInPlace(0.1);
  93171. arrowMesh.material = _this._coloredMaterial;
  93172. arrowMesh.rotation.x = Math.PI / 2;
  93173. arrowMesh.position.z += 0.3;
  93174. arrowTail.scaling.scaleInPlace(0.26);
  93175. arrowTail.rotation.x = Math.PI / 2;
  93176. arrowTail.material = _this._coloredMaterial;
  93177. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  93178. _this._rootMesh.addChild(arrow);
  93179. arrow.scaling.scaleInPlace(1 / 3);
  93180. // Add drag behavior to handle events when the gizmo is dragged
  93181. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93182. _this.dragBehavior.moveAttached = false;
  93183. _this._rootMesh.addBehavior(_this.dragBehavior);
  93184. var currentSnapDragDistance = 0;
  93185. var tmpVector = new BABYLON.Vector3();
  93186. var tmpSnapEvent = { snapDistance: 0 };
  93187. _this.dragBehavior.onDragObservable.add(function (event) {
  93188. if (_this.attachedMesh) {
  93189. // Snapping logic
  93190. var snapped = false;
  93191. var dragSteps = 0;
  93192. if (_this.uniformScaling) {
  93193. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  93194. if (tmpVector.y < 0) {
  93195. tmpVector.scaleInPlace(-1);
  93196. }
  93197. }
  93198. else {
  93199. tmpVector.copyFrom(dragAxis);
  93200. }
  93201. if (_this.snapDistance == 0) {
  93202. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  93203. }
  93204. else {
  93205. currentSnapDragDistance += event.dragDistance;
  93206. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  93207. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  93208. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  93209. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  93210. snapped = true;
  93211. }
  93212. else {
  93213. tmpVector.scaleInPlace(0);
  93214. }
  93215. }
  93216. _this.attachedMesh.scaling.addInPlace(tmpVector);
  93217. if (snapped) {
  93218. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  93219. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  93220. }
  93221. }
  93222. });
  93223. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93224. if (_this._customMeshSet) {
  93225. return;
  93226. }
  93227. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  93228. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  93229. _this._rootMesh.getChildMeshes().forEach(function (m) {
  93230. m.material = material;
  93231. if (m.color) {
  93232. m.color = material.emissiveColor;
  93233. }
  93234. });
  93235. });
  93236. return _this;
  93237. }
  93238. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  93239. if (this.dragBehavior) {
  93240. this.dragBehavior.enabled = value ? true : false;
  93241. }
  93242. };
  93243. /**
  93244. * Disposes of the gizmo
  93245. */
  93246. AxisScaleGizmo.prototype.dispose = function () {
  93247. this.onSnapObservable.clear();
  93248. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93249. this.dragBehavior.detach();
  93250. _super.prototype.dispose.call(this);
  93251. };
  93252. /**
  93253. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  93254. * @param mesh The mesh to replace the default mesh of the gizmo
  93255. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  93256. */
  93257. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  93258. var _this = this;
  93259. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  93260. _super.prototype.setCustomMesh.call(this, mesh);
  93261. if (useGizmoMaterial) {
  93262. this._rootMesh.getChildMeshes().forEach(function (m) {
  93263. m.material = _this._coloredMaterial;
  93264. if (m.color) {
  93265. m.color = _this._coloredMaterial.emissiveColor;
  93266. }
  93267. });
  93268. this._customMeshSet = false;
  93269. }
  93270. };
  93271. return AxisScaleGizmo;
  93272. }(BABYLON.Gizmo));
  93273. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  93274. })(BABYLON || (BABYLON = {}));
  93275. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  93276. var BABYLON;
  93277. (function (BABYLON) {
  93278. /**
  93279. * Single plane rotation gizmo
  93280. */
  93281. var PlaneRotationGizmo = /** @class */ (function (_super) {
  93282. __extends(PlaneRotationGizmo, _super);
  93283. /**
  93284. * Creates a PlaneRotationGizmo
  93285. * @param gizmoLayer The utility layer the gizmo will be added to
  93286. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  93287. * @param color The color of the gizmo
  93288. */
  93289. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  93290. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93291. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93292. var _this = _super.call(this, gizmoLayer) || this;
  93293. _this._pointerObserver = null;
  93294. /**
  93295. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  93296. */
  93297. _this.snapDistance = 0;
  93298. /**
  93299. * Event that fires each time the gizmo snaps to a new location.
  93300. * * snapDistance is the the change in distance
  93301. */
  93302. _this.onSnapObservable = new BABYLON.Observable();
  93303. // Create Material
  93304. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93305. coloredMaterial.disableLighting = true;
  93306. coloredMaterial.emissiveColor = color;
  93307. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93308. hoverMaterial.disableLighting = true;
  93309. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93310. // Build mesh on root node
  93311. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93312. // Create circle out of lines
  93313. var tessellation = 20;
  93314. var radius = 0.8;
  93315. var points = new Array();
  93316. for (var i = 0; i < tessellation; i++) {
  93317. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  93318. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  93319. }
  93320. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  93321. rotationMesh.color = coloredMaterial.emissiveColor;
  93322. // Position arrow pointing in its drag axis
  93323. rotationMesh.scaling.scaleInPlace(0.26);
  93324. rotationMesh.material = coloredMaterial;
  93325. rotationMesh.rotation.x = Math.PI / 2;
  93326. parentMesh.addChild(rotationMesh);
  93327. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  93328. _this._rootMesh.addChild(parentMesh);
  93329. parentMesh.scaling.scaleInPlace(1 / 3);
  93330. // Add drag behavior to handle events when the gizmo is dragged
  93331. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  93332. _this.dragBehavior.moveAttached = false;
  93333. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  93334. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  93335. _this._rootMesh.addBehavior(_this.dragBehavior);
  93336. var lastDragPosition = new BABYLON.Vector3();
  93337. _this.dragBehavior.onDragStartObservable.add(function (e) {
  93338. if (_this.attachedMesh) {
  93339. lastDragPosition.copyFrom(e.dragPlanePoint);
  93340. }
  93341. });
  93342. var rotationMatrix = new BABYLON.Matrix();
  93343. var planeNormalTowardsCamera = new BABYLON.Vector3();
  93344. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  93345. var tmpSnapEvent = { snapDistance: 0 };
  93346. var currentSnapDragDistance = 0;
  93347. var tmpMatrix = new BABYLON.Matrix();
  93348. var tmpVector = new BABYLON.Vector3();
  93349. var amountToRotate = new BABYLON.Quaternion();
  93350. _this.dragBehavior.onDragObservable.add(function (event) {
  93351. if (_this.attachedMesh) {
  93352. if (!_this.attachedMesh.rotationQuaternion) {
  93353. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  93354. }
  93355. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  93356. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  93357. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  93358. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  93359. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  93360. var angle = Math.atan2(cross.length(), dot);
  93361. planeNormalTowardsCamera.copyFrom(planeNormal);
  93362. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  93363. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  93364. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  93365. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  93366. }
  93367. // Flip up vector depending on which side the camera is on
  93368. if (gizmoLayer.utilityLayerScene.activeCamera) {
  93369. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  93370. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  93371. planeNormalTowardsCamera.scaleInPlace(-1);
  93372. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  93373. }
  93374. }
  93375. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  93376. if (halfCircleSide)
  93377. angle = -angle;
  93378. // Snapping logic
  93379. var snapped = false;
  93380. if (_this.snapDistance != 0) {
  93381. currentSnapDragDistance += angle;
  93382. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  93383. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  93384. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  93385. angle = _this.snapDistance * dragSteps;
  93386. snapped = true;
  93387. }
  93388. else {
  93389. angle = 0;
  93390. }
  93391. }
  93392. // If the mesh has a parent, convert needed world rotation to local rotation
  93393. tmpMatrix.reset();
  93394. if (_this.attachedMesh.parent) {
  93395. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  93396. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  93397. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  93398. }
  93399. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  93400. var quaternionCoefficient = Math.sin(angle / 2);
  93401. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  93402. // 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
  93403. if (tmpMatrix.determinant() > 0) {
  93404. amountToRotate.toEulerAnglesToRef(tmpVector);
  93405. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  93406. }
  93407. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  93408. // Rotate selected mesh quaternion over fixed axis
  93409. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  93410. }
  93411. else {
  93412. // Rotate selected mesh quaternion over rotated axis
  93413. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  93414. }
  93415. lastDragPosition.copyFrom(event.dragPlanePoint);
  93416. if (snapped) {
  93417. tmpSnapEvent.snapDistance = angle;
  93418. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  93419. }
  93420. }
  93421. });
  93422. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93423. if (_this._customMeshSet) {
  93424. return;
  93425. }
  93426. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  93427. var material = isHovered ? hoverMaterial : coloredMaterial;
  93428. _this._rootMesh.getChildMeshes().forEach(function (m) {
  93429. m.material = material;
  93430. if (m.color) {
  93431. m.color = material.emissiveColor;
  93432. }
  93433. });
  93434. });
  93435. return _this;
  93436. }
  93437. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  93438. if (this.dragBehavior) {
  93439. this.dragBehavior.enabled = value ? true : false;
  93440. }
  93441. };
  93442. /**
  93443. * Disposes of the gizmo
  93444. */
  93445. PlaneRotationGizmo.prototype.dispose = function () {
  93446. this.onSnapObservable.clear();
  93447. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93448. this.dragBehavior.detach();
  93449. _super.prototype.dispose.call(this);
  93450. };
  93451. return PlaneRotationGizmo;
  93452. }(BABYLON.Gizmo));
  93453. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  93454. })(BABYLON || (BABYLON = {}));
  93455. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  93456. var BABYLON;
  93457. (function (BABYLON) {
  93458. /**
  93459. * Gizmo that enables dragging a mesh along 3 axis
  93460. */
  93461. var PositionGizmo = /** @class */ (function (_super) {
  93462. __extends(PositionGizmo, _super);
  93463. /**
  93464. * Creates a PositionGizmo
  93465. * @param gizmoLayer The utility layer the gizmo will be added to
  93466. */
  93467. function PositionGizmo(gizmoLayer) {
  93468. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93469. var _this = _super.call(this, gizmoLayer) || this;
  93470. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  93471. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  93472. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  93473. _this.attachedMesh = null;
  93474. return _this;
  93475. }
  93476. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  93477. set: function (mesh) {
  93478. if (this.xGizmo) {
  93479. this.xGizmo.attachedMesh = mesh;
  93480. this.yGizmo.attachedMesh = mesh;
  93481. this.zGizmo.attachedMesh = mesh;
  93482. }
  93483. },
  93484. enumerable: true,
  93485. configurable: true
  93486. });
  93487. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  93488. get: function () {
  93489. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  93490. },
  93491. set: function (value) {
  93492. if (this.xGizmo) {
  93493. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93494. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93495. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93496. }
  93497. },
  93498. enumerable: true,
  93499. configurable: true
  93500. });
  93501. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  93502. get: function () {
  93503. return this.xGizmo.snapDistance;
  93504. },
  93505. /**
  93506. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93507. */
  93508. set: function (value) {
  93509. if (this.xGizmo) {
  93510. this.xGizmo.snapDistance = value;
  93511. this.yGizmo.snapDistance = value;
  93512. this.zGizmo.snapDistance = value;
  93513. }
  93514. },
  93515. enumerable: true,
  93516. configurable: true
  93517. });
  93518. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  93519. get: function () {
  93520. return this.xGizmo.scaleRatio;
  93521. },
  93522. /**
  93523. * Ratio for the scale of the gizmo (Default: 1)
  93524. */
  93525. set: function (value) {
  93526. if (this.xGizmo) {
  93527. this.xGizmo.scaleRatio = value;
  93528. this.yGizmo.scaleRatio = value;
  93529. this.zGizmo.scaleRatio = value;
  93530. }
  93531. },
  93532. enumerable: true,
  93533. configurable: true
  93534. });
  93535. /**
  93536. * Disposes of the gizmo
  93537. */
  93538. PositionGizmo.prototype.dispose = function () {
  93539. this.xGizmo.dispose();
  93540. this.yGizmo.dispose();
  93541. this.zGizmo.dispose();
  93542. };
  93543. /**
  93544. * CustomMeshes are not supported by this gizmo
  93545. * @param mesh The mesh to replace the default mesh of the gizmo
  93546. */
  93547. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  93548. 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)");
  93549. };
  93550. return PositionGizmo;
  93551. }(BABYLON.Gizmo));
  93552. BABYLON.PositionGizmo = PositionGizmo;
  93553. })(BABYLON || (BABYLON = {}));
  93554. //# sourceMappingURL=babylon.positionGizmo.js.map
  93555. var BABYLON;
  93556. (function (BABYLON) {
  93557. /**
  93558. * Gizmo that enables rotating a mesh along 3 axis
  93559. */
  93560. var RotationGizmo = /** @class */ (function (_super) {
  93561. __extends(RotationGizmo, _super);
  93562. /**
  93563. * Creates a RotationGizmo
  93564. * @param gizmoLayer The utility layer the gizmo will be added to
  93565. */
  93566. function RotationGizmo(gizmoLayer) {
  93567. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93568. var _this = _super.call(this, gizmoLayer) || this;
  93569. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  93570. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  93571. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  93572. _this.attachedMesh = null;
  93573. return _this;
  93574. }
  93575. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  93576. set: function (mesh) {
  93577. if (this.xGizmo) {
  93578. this.xGizmo.attachedMesh = mesh;
  93579. this.yGizmo.attachedMesh = mesh;
  93580. this.zGizmo.attachedMesh = mesh;
  93581. }
  93582. },
  93583. enumerable: true,
  93584. configurable: true
  93585. });
  93586. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  93587. get: function () {
  93588. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  93589. },
  93590. set: function (value) {
  93591. if (this.xGizmo) {
  93592. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93593. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93594. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93595. }
  93596. },
  93597. enumerable: true,
  93598. configurable: true
  93599. });
  93600. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  93601. get: function () {
  93602. return this.xGizmo.snapDistance;
  93603. },
  93604. /**
  93605. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93606. */
  93607. set: function (value) {
  93608. if (this.xGizmo) {
  93609. this.xGizmo.snapDistance = value;
  93610. this.yGizmo.snapDistance = value;
  93611. this.zGizmo.snapDistance = value;
  93612. }
  93613. },
  93614. enumerable: true,
  93615. configurable: true
  93616. });
  93617. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  93618. get: function () {
  93619. return this.xGizmo.scaleRatio;
  93620. },
  93621. /**
  93622. * Ratio for the scale of the gizmo (Default: 1)
  93623. */
  93624. set: function (value) {
  93625. if (this.xGizmo) {
  93626. this.xGizmo.scaleRatio = value;
  93627. this.yGizmo.scaleRatio = value;
  93628. this.zGizmo.scaleRatio = value;
  93629. }
  93630. },
  93631. enumerable: true,
  93632. configurable: true
  93633. });
  93634. /**
  93635. * Disposes of the gizmo
  93636. */
  93637. RotationGizmo.prototype.dispose = function () {
  93638. this.xGizmo.dispose();
  93639. this.yGizmo.dispose();
  93640. this.zGizmo.dispose();
  93641. };
  93642. /**
  93643. * CustomMeshes are not supported by this gizmo
  93644. * @param mesh The mesh to replace the default mesh of the gizmo
  93645. */
  93646. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  93647. 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)");
  93648. };
  93649. return RotationGizmo;
  93650. }(BABYLON.Gizmo));
  93651. BABYLON.RotationGizmo = RotationGizmo;
  93652. })(BABYLON || (BABYLON = {}));
  93653. //# sourceMappingURL=babylon.rotationGizmo.js.map
  93654. var BABYLON;
  93655. (function (BABYLON) {
  93656. /**
  93657. * Gizmo that enables scaling a mesh along 3 axis
  93658. */
  93659. var ScaleGizmo = /** @class */ (function (_super) {
  93660. __extends(ScaleGizmo, _super);
  93661. /**
  93662. * Creates a ScaleGizmo
  93663. * @param gizmoLayer The utility layer the gizmo will be added to
  93664. */
  93665. function ScaleGizmo(gizmoLayer) {
  93666. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93667. var _this = _super.call(this, gizmoLayer) || this;
  93668. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  93669. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  93670. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  93671. // Create uniform scale gizmo
  93672. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  93673. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  93674. _this._uniformGizmo.uniformScaling = true;
  93675. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  93676. octahedron.scaling.scaleInPlace(0.007);
  93677. _this._uniformGizmo.setCustomMesh(octahedron, true);
  93678. _this.attachedMesh = null;
  93679. return _this;
  93680. }
  93681. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  93682. set: function (mesh) {
  93683. if (this.xGizmo) {
  93684. this.xGizmo.attachedMesh = mesh;
  93685. this.yGizmo.attachedMesh = mesh;
  93686. this.zGizmo.attachedMesh = mesh;
  93687. this._uniformGizmo.attachedMesh = mesh;
  93688. }
  93689. },
  93690. enumerable: true,
  93691. configurable: true
  93692. });
  93693. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  93694. get: function () {
  93695. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  93696. },
  93697. set: function (value) {
  93698. if (this.xGizmo) {
  93699. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93700. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93701. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93702. }
  93703. },
  93704. enumerable: true,
  93705. configurable: true
  93706. });
  93707. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  93708. get: function () {
  93709. return this.xGizmo.snapDistance;
  93710. },
  93711. /**
  93712. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93713. */
  93714. set: function (value) {
  93715. if (this.xGizmo) {
  93716. this.xGizmo.snapDistance = value;
  93717. this.yGizmo.snapDistance = value;
  93718. this.zGizmo.snapDistance = value;
  93719. this._uniformGizmo.snapDistance = value;
  93720. }
  93721. },
  93722. enumerable: true,
  93723. configurable: true
  93724. });
  93725. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  93726. get: function () {
  93727. return this.xGizmo.scaleRatio;
  93728. },
  93729. /**
  93730. * Ratio for the scale of the gizmo (Default: 1)
  93731. */
  93732. set: function (value) {
  93733. if (this.xGizmo) {
  93734. this.xGizmo.scaleRatio = value;
  93735. this.yGizmo.scaleRatio = value;
  93736. this.zGizmo.scaleRatio = value;
  93737. this._uniformGizmo.scaleRatio = value;
  93738. }
  93739. },
  93740. enumerable: true,
  93741. configurable: true
  93742. });
  93743. /**
  93744. * Disposes of the gizmo
  93745. */
  93746. ScaleGizmo.prototype.dispose = function () {
  93747. this.xGizmo.dispose();
  93748. this.yGizmo.dispose();
  93749. this.zGizmo.dispose();
  93750. this._uniformGizmo.dispose();
  93751. };
  93752. return ScaleGizmo;
  93753. }(BABYLON.Gizmo));
  93754. BABYLON.ScaleGizmo = ScaleGizmo;
  93755. })(BABYLON || (BABYLON = {}));
  93756. //# sourceMappingURL=babylon.scaleGizmo.js.map
  93757. var BABYLON;
  93758. (function (BABYLON) {
  93759. /**
  93760. * Bounding box gizmo
  93761. */
  93762. var BoundingBoxGizmo = /** @class */ (function (_super) {
  93763. __extends(BoundingBoxGizmo, _super);
  93764. /**
  93765. * Creates an BoundingBoxGizmo
  93766. * @param gizmoLayer The utility layer the gizmo will be added to
  93767. * @param color The color of the gizmo
  93768. */
  93769. function BoundingBoxGizmo(color, gizmoLayer) {
  93770. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93771. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  93772. var _this = _super.call(this, gizmoLayer) || this;
  93773. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  93774. _this._renderObserver = null;
  93775. _this._pointerObserver = null;
  93776. _this._scaleDragSpeed = 0.2;
  93777. _this._tmpQuaternion = new BABYLON.Quaternion();
  93778. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  93779. _this._tmpRotationMatrix = new BABYLON.Matrix();
  93780. /**
  93781. * 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)
  93782. */
  93783. _this.ignoreChildren = false;
  93784. /**
  93785. * 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)
  93786. */
  93787. _this.includeChildPredicate = null;
  93788. /**
  93789. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  93790. */
  93791. _this.rotationSphereSize = 0.1;
  93792. /**
  93793. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  93794. */
  93795. _this.scaleBoxSize = 0.1;
  93796. /**
  93797. * 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)
  93798. */
  93799. _this.fixedDragMeshScreenSize = false;
  93800. /**
  93801. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  93802. */
  93803. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  93804. /**
  93805. * Fired when a rotation sphere or scale box is dragged
  93806. */
  93807. _this.onDragStartObservable = new BABYLON.Observable();
  93808. /**
  93809. * Fired when a scale box is dragged
  93810. */
  93811. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  93812. /**
  93813. * Fired when a scale box drag is ended
  93814. */
  93815. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  93816. /**
  93817. * Fired when a rotation sphere is dragged
  93818. */
  93819. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  93820. /**
  93821. * Fired when a rotation sphere drag is ended
  93822. */
  93823. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  93824. /**
  93825. * 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)
  93826. */
  93827. _this.scalePivot = null;
  93828. _this._existingMeshScale = new BABYLON.Vector3();
  93829. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  93830. _this._updateScale = false;
  93831. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  93832. // Create Materials
  93833. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93834. coloredMaterial.disableLighting = true;
  93835. coloredMaterial.emissiveColor = color;
  93836. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93837. hoverColoredMaterial.disableLighting = true;
  93838. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93839. // Build bounding box out of lines
  93840. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93841. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  93842. var lines = [];
  93843. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  93844. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  93845. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  93846. 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));
  93847. 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));
  93848. 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));
  93849. 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));
  93850. 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));
  93851. 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));
  93852. 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));
  93853. 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));
  93854. 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));
  93855. lines.forEach(function (l) {
  93856. l.color = color;
  93857. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  93858. l.isPickable = false;
  93859. _this._lineBoundingBox.addChild(l);
  93860. });
  93861. _this._rootMesh.addChild(_this._lineBoundingBox);
  93862. // Create rotation spheres
  93863. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93864. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  93865. var _loop_1 = function (i_1) {
  93866. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  93867. sphere.rotationQuaternion = new BABYLON.Quaternion();
  93868. sphere.material = coloredMaterial;
  93869. // Drag behavior
  93870. _dragBehavior = new BABYLON.PointerDragBehavior({});
  93871. _dragBehavior.moveAttached = false;
  93872. _dragBehavior.updateDragPlane = false;
  93873. sphere.addBehavior(_dragBehavior);
  93874. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  93875. var totalTurnAmountOfDrag = 0;
  93876. _dragBehavior.onDragStartObservable.add(function (event) {
  93877. startingTurnDirection.copyFrom(sphere.forward);
  93878. totalTurnAmountOfDrag = 0;
  93879. });
  93880. _dragBehavior.onDragObservable.add(function (event) {
  93881. _this.onRotationSphereDragObservable.notifyObservers({});
  93882. if (_this.attachedMesh) {
  93883. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  93884. var worldDragDirection = startingTurnDirection;
  93885. // Project the world right on to the drag plane
  93886. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  93887. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  93888. // project drag delta on to the resulting drag axis and rotate based on that
  93889. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  93890. // Make rotation relative to size of mesh.
  93891. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  93892. // Rotate based on axis
  93893. if (!_this.attachedMesh.rotationQuaternion) {
  93894. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  93895. }
  93896. if (!_this._anchorMesh.rotationQuaternion) {
  93897. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  93898. }
  93899. // Do not allow the object to turn more than a full circle
  93900. totalTurnAmountOfDrag += projectDist;
  93901. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  93902. if (i_1 >= 8) {
  93903. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  93904. }
  93905. else if (i_1 >= 4) {
  93906. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  93907. }
  93908. else {
  93909. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  93910. }
  93911. // Rotate around center of bounding box
  93912. _this._anchorMesh.addChild(_this.attachedMesh);
  93913. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  93914. _this._anchorMesh.removeChild(_this.attachedMesh);
  93915. }
  93916. _this.updateBoundingBox();
  93917. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  93918. }
  93919. });
  93920. // Selection/deselection
  93921. _dragBehavior.onDragStartObservable.add(function () {
  93922. _this.onDragStartObservable.notifyObservers({});
  93923. _this._selectNode(sphere);
  93924. });
  93925. _dragBehavior.onDragEndObservable.add(function () {
  93926. _this.onRotationSphereDragEndObservable.notifyObservers({});
  93927. _this._selectNode(null);
  93928. });
  93929. this_1._rotateSpheresParent.addChild(sphere);
  93930. };
  93931. var this_1 = this, _dragBehavior;
  93932. for (var i_1 = 0; i_1 < 12; i_1++) {
  93933. _loop_1(i_1);
  93934. }
  93935. _this._rootMesh.addChild(_this._rotateSpheresParent);
  93936. // Create scale cubes
  93937. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93938. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  93939. for (var i = 0; i < 2; i++) {
  93940. for (var j = 0; j < 2; j++) {
  93941. var _loop_2 = function () {
  93942. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  93943. box.material = coloredMaterial;
  93944. // Dragging logic
  93945. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  93946. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93947. _dragBehavior.moveAttached = false;
  93948. box.addBehavior(_dragBehavior);
  93949. _dragBehavior.onDragObservable.add(function (event) {
  93950. _this.onScaleBoxDragObservable.notifyObservers({});
  93951. if (_this.attachedMesh) {
  93952. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  93953. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  93954. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  93955. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  93956. _this.updateBoundingBox();
  93957. if (_this.scalePivot) {
  93958. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  93959. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  93960. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  93961. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  93962. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  93963. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  93964. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  93965. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  93966. }
  93967. else {
  93968. // Scale from the position of the opposite corner
  93969. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  93970. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  93971. }
  93972. _this._anchorMesh.addChild(_this.attachedMesh);
  93973. _this._anchorMesh.scaling.addInPlace(deltaScale);
  93974. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  93975. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  93976. }
  93977. _this._anchorMesh.removeChild(_this.attachedMesh);
  93978. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  93979. }
  93980. });
  93981. // Selection/deselection
  93982. _dragBehavior.onDragStartObservable.add(function () {
  93983. _this.onDragStartObservable.notifyObservers({});
  93984. _this._selectNode(box);
  93985. });
  93986. _dragBehavior.onDragEndObservable.add(function () {
  93987. _this.onScaleBoxDragEndObservable.notifyObservers({});
  93988. _this._selectNode(null);
  93989. });
  93990. this_2._scaleBoxesParent.addChild(box);
  93991. };
  93992. var this_2 = this, _dragBehavior;
  93993. for (var k = 0; k < 2; k++) {
  93994. _loop_2();
  93995. }
  93996. }
  93997. }
  93998. _this._rootMesh.addChild(_this._scaleBoxesParent);
  93999. // Hover color change
  94000. var pointerIds = new Array();
  94001. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94002. if (!pointerIds[pointerInfo.event.pointerId]) {
  94003. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  94004. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  94005. pointerIds[pointerInfo.event.pointerId] = mesh;
  94006. mesh.material = hoverColoredMaterial;
  94007. }
  94008. });
  94009. }
  94010. else {
  94011. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  94012. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  94013. delete pointerIds[pointerInfo.event.pointerId];
  94014. }
  94015. }
  94016. });
  94017. // Update bounding box positions
  94018. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  94019. // Only update the bouding box if scaling has changed
  94020. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  94021. _this.updateBoundingBox();
  94022. }
  94023. });
  94024. _this.updateBoundingBox();
  94025. return _this;
  94026. }
  94027. /** @hidden */
  94028. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  94029. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  94030. // Save old pivot and set pivot to 0,0,0
  94031. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  94032. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  94033. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  94034. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  94035. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  94036. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  94037. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  94038. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  94039. }
  94040. }
  94041. BoundingBoxGizmo._PivotCached++;
  94042. };
  94043. /** @hidden */
  94044. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  94045. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  94046. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  94047. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  94048. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  94049. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  94050. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  94051. }
  94052. this._PivotCached--;
  94053. };
  94054. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  94055. if (value) {
  94056. // Reset anchor mesh to match attached mesh's scale
  94057. // This is needed to avoid invalid box/sphere position on first drag
  94058. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  94059. this._anchorMesh.addChild(value);
  94060. this._anchorMesh.removeChild(value);
  94061. BoundingBoxGizmo._RestorePivotPoint(value);
  94062. this.updateBoundingBox();
  94063. }
  94064. };
  94065. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  94066. this._rotateSpheresParent.getChildMeshes()
  94067. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  94068. m.isVisible = (!selectedMesh || m == selectedMesh);
  94069. });
  94070. };
  94071. /**
  94072. * Updates the bounding box information for the Gizmo
  94073. */
  94074. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  94075. if (this.attachedMesh) {
  94076. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  94077. this._update();
  94078. // Rotate based on axis
  94079. if (!this.attachedMesh.rotationQuaternion) {
  94080. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  94081. }
  94082. if (!this._anchorMesh.rotationQuaternion) {
  94083. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  94084. }
  94085. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  94086. // Store original position and reset mesh to origin before computing the bounding box
  94087. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  94088. this._tmpVector.copyFrom(this.attachedMesh.position);
  94089. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  94090. this.attachedMesh.position.set(0, 0, 0);
  94091. // Update bounding dimensions/positions
  94092. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  94093. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  94094. // Update gizmo to match bounding box scaling and rotation
  94095. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  94096. 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);
  94097. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  94098. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  94099. this._lineBoundingBox.computeWorldMatrix();
  94100. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  94101. // restore position/rotation values
  94102. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  94103. this.attachedMesh.position.copyFrom(this._tmpVector);
  94104. }
  94105. // Update rotation sphere locations
  94106. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  94107. for (var i = 0; i < 3; i++) {
  94108. for (var j = 0; j < 2; j++) {
  94109. for (var k = 0; k < 2; k++) {
  94110. var index = ((i * 4) + (j * 2)) + k;
  94111. if (i == 0) {
  94112. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  94113. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94114. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  94115. }
  94116. if (i == 1) {
  94117. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  94118. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94119. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  94120. }
  94121. if (i == 2) {
  94122. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  94123. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94124. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  94125. }
  94126. if (this.fixedDragMeshScreenSize) {
  94127. this._rootMesh.computeWorldMatrix();
  94128. this._rotateSpheresParent.computeWorldMatrix();
  94129. rotateSpheres[index].computeWorldMatrix();
  94130. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  94131. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  94132. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  94133. }
  94134. else {
  94135. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  94136. }
  94137. }
  94138. }
  94139. }
  94140. // Update scale box locations
  94141. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  94142. for (var i = 0; i < 2; i++) {
  94143. for (var j = 0; j < 2; j++) {
  94144. for (var k = 0; k < 2; k++) {
  94145. var index = ((i * 4) + (j * 2)) + k;
  94146. if (scaleBoxes[index]) {
  94147. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  94148. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94149. if (this.fixedDragMeshScreenSize) {
  94150. this._rootMesh.computeWorldMatrix();
  94151. this._scaleBoxesParent.computeWorldMatrix();
  94152. scaleBoxes[index].computeWorldMatrix();
  94153. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  94154. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  94155. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  94156. }
  94157. else {
  94158. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  94159. }
  94160. }
  94161. }
  94162. }
  94163. }
  94164. if (this.attachedMesh) {
  94165. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  94166. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  94167. }
  94168. };
  94169. /**
  94170. * Enables rotation on the specified axis and disables rotation on the others
  94171. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  94172. */
  94173. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  94174. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  94175. if (i < 4) {
  94176. m.setEnabled(axis.indexOf("x") != -1);
  94177. }
  94178. else if (i < 8) {
  94179. m.setEnabled(axis.indexOf("y") != -1);
  94180. }
  94181. else {
  94182. m.setEnabled(axis.indexOf("z") != -1);
  94183. }
  94184. });
  94185. };
  94186. /**
  94187. * Disposes of the gizmo
  94188. */
  94189. BoundingBoxGizmo.prototype.dispose = function () {
  94190. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94191. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  94192. this._lineBoundingBox.dispose();
  94193. this._rotateSpheresParent.dispose();
  94194. this._scaleBoxesParent.dispose();
  94195. _super.prototype.dispose.call(this);
  94196. };
  94197. /**
  94198. * 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)
  94199. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  94200. * @returns the bounding box mesh with the passed in mesh as a child
  94201. */
  94202. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  94203. var makeNotPickable = function (root) {
  94204. root.isPickable = false;
  94205. root.getChildMeshes().forEach(function (c) {
  94206. makeNotPickable(c);
  94207. });
  94208. };
  94209. makeNotPickable(mesh);
  94210. // Reset position to get boudning box from origin with no rotation
  94211. if (!mesh.rotationQuaternion) {
  94212. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  94213. }
  94214. var oldPos = mesh.position.clone();
  94215. var oldRot = mesh.rotationQuaternion.clone();
  94216. mesh.rotationQuaternion.set(0, 0, 0, 1);
  94217. mesh.position.set(0, 0, 0);
  94218. // Update bounding dimensions/positions
  94219. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  94220. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  94221. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  94222. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  94223. // Restore original positions
  94224. mesh.addChild(box);
  94225. mesh.rotationQuaternion.copyFrom(oldRot);
  94226. mesh.position.copyFrom(oldPos);
  94227. // Reverse parenting
  94228. mesh.removeChild(box);
  94229. box.addChild(mesh);
  94230. box.visibility = 0;
  94231. return box;
  94232. };
  94233. /**
  94234. * CustomMeshes are not supported by this gizmo
  94235. * @param mesh The mesh to replace the default mesh of the gizmo
  94236. */
  94237. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  94238. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  94239. };
  94240. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  94241. // store/remove pivot point should only be applied during their outermost calls
  94242. BoundingBoxGizmo._PivotCached = 0;
  94243. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  94244. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  94245. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  94246. return BoundingBoxGizmo;
  94247. }(BABYLON.Gizmo));
  94248. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  94249. })(BABYLON || (BABYLON = {}));
  94250. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  94251. var BABYLON;
  94252. (function (BABYLON) {
  94253. /**
  94254. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  94255. */
  94256. var GizmoManager = /** @class */ (function () {
  94257. /**
  94258. * Instatiates a gizmo manager
  94259. * @param scene the scene to overlay the gizmos on top of
  94260. */
  94261. function GizmoManager(scene) {
  94262. var _this = this;
  94263. this.scene = scene;
  94264. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  94265. this._pointerObserver = null;
  94266. this._attachedMesh = null;
  94267. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  94268. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  94269. /**
  94270. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  94271. */
  94272. this.attachableMeshes = null;
  94273. /**
  94274. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  94275. */
  94276. this.usePointerToAttachGizmos = true;
  94277. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  94278. // Instatiate/dispose gizmos based on pointer actions
  94279. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  94280. if (!_this.usePointerToAttachGizmos) {
  94281. return;
  94282. }
  94283. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  94284. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  94285. var node = pointerInfo.pickInfo.pickedMesh;
  94286. if (_this.attachableMeshes == null) {
  94287. // Attach to the most parent node
  94288. while (node && node.parent != null) {
  94289. node = node.parent;
  94290. }
  94291. }
  94292. else {
  94293. // Attach to the parent node that is an attachableMesh
  94294. var found = false;
  94295. _this.attachableMeshes.forEach(function (mesh) {
  94296. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  94297. node = mesh;
  94298. found = true;
  94299. }
  94300. });
  94301. if (!found) {
  94302. node = null;
  94303. }
  94304. }
  94305. if (node instanceof BABYLON.AbstractMesh) {
  94306. _this.attachToMesh(node);
  94307. }
  94308. else {
  94309. _this.attachToMesh(null);
  94310. }
  94311. }
  94312. else {
  94313. _this.attachToMesh(null);
  94314. }
  94315. }
  94316. });
  94317. }
  94318. /**
  94319. * Attaches a set of gizmos to the specified mesh
  94320. * @param mesh The mesh the gizmo's should be attached to
  94321. */
  94322. GizmoManager.prototype.attachToMesh = function (mesh) {
  94323. if (this._attachedMesh) {
  94324. this._attachedMesh.removeBehavior(this._dragBehavior);
  94325. }
  94326. this._attachedMesh = mesh;
  94327. for (var key in this.gizmos) {
  94328. var gizmo = (this.gizmos[key]);
  94329. if (gizmo && this._gizmosEnabled[key]) {
  94330. gizmo.attachedMesh = mesh;
  94331. }
  94332. }
  94333. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  94334. this._attachedMesh.addBehavior(this._dragBehavior);
  94335. }
  94336. };
  94337. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  94338. get: function () {
  94339. return this._gizmosEnabled.positionGizmo;
  94340. },
  94341. /**
  94342. * If the position gizmo is enabled
  94343. */
  94344. set: function (value) {
  94345. if (value) {
  94346. if (!this.gizmos.positionGizmo) {
  94347. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  94348. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94349. }
  94350. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  94351. }
  94352. else if (this.gizmos.positionGizmo) {
  94353. this.gizmos.positionGizmo.attachedMesh = null;
  94354. }
  94355. this._gizmosEnabled.positionGizmo = value;
  94356. },
  94357. enumerable: true,
  94358. configurable: true
  94359. });
  94360. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  94361. get: function () {
  94362. return this._gizmosEnabled.rotationGizmo;
  94363. },
  94364. /**
  94365. * If the rotation gizmo is enabled
  94366. */
  94367. set: function (value) {
  94368. if (value) {
  94369. if (!this.gizmos.rotationGizmo) {
  94370. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  94371. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94372. }
  94373. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  94374. }
  94375. else if (this.gizmos.rotationGizmo) {
  94376. this.gizmos.rotationGizmo.attachedMesh = null;
  94377. }
  94378. this._gizmosEnabled.rotationGizmo = value;
  94379. },
  94380. enumerable: true,
  94381. configurable: true
  94382. });
  94383. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  94384. get: function () {
  94385. return this._gizmosEnabled.scaleGizmo;
  94386. },
  94387. /**
  94388. * If the scale gizmo is enabled
  94389. */
  94390. set: function (value) {
  94391. if (value) {
  94392. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  94393. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  94394. }
  94395. else if (this.gizmos.scaleGizmo) {
  94396. this.gizmos.scaleGizmo.attachedMesh = null;
  94397. }
  94398. this._gizmosEnabled.scaleGizmo = value;
  94399. },
  94400. enumerable: true,
  94401. configurable: true
  94402. });
  94403. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  94404. get: function () {
  94405. return this._gizmosEnabled.boundingBoxGizmo;
  94406. },
  94407. /**
  94408. * If the boundingBox gizmo is enabled
  94409. */
  94410. set: function (value) {
  94411. if (value) {
  94412. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  94413. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  94414. if (this._attachedMesh) {
  94415. this._attachedMesh.removeBehavior(this._dragBehavior);
  94416. this._attachedMesh.addBehavior(this._dragBehavior);
  94417. }
  94418. }
  94419. else if (this.gizmos.boundingBoxGizmo) {
  94420. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  94421. }
  94422. this._gizmosEnabled.boundingBoxGizmo = value;
  94423. },
  94424. enumerable: true,
  94425. configurable: true
  94426. });
  94427. /**
  94428. * Disposes of the gizmo manager
  94429. */
  94430. GizmoManager.prototype.dispose = function () {
  94431. this.scene.onPointerObservable.remove(this._pointerObserver);
  94432. for (var key in this.gizmos) {
  94433. var gizmo = (this.gizmos[key]);
  94434. if (gizmo) {
  94435. gizmo.dispose();
  94436. }
  94437. }
  94438. this._dragBehavior.detach();
  94439. };
  94440. return GizmoManager;
  94441. }());
  94442. BABYLON.GizmoManager = GizmoManager;
  94443. })(BABYLON || (BABYLON = {}));
  94444. //# sourceMappingURL=babylon.gizmoManager.js.map
  94445. var BABYLON;
  94446. (function (BABYLON) {
  94447. /**
  94448. * Defines a target to use with MorphTargetManager
  94449. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  94450. */
  94451. var MorphTarget = /** @class */ (function () {
  94452. /**
  94453. * Creates a new MorphTarget
  94454. * @param name defines the name of the target
  94455. * @param influence defines the influence to use
  94456. */
  94457. function MorphTarget(
  94458. /** defines the name of the target */
  94459. name, influence, scene) {
  94460. if (influence === void 0) { influence = 0; }
  94461. if (scene === void 0) { scene = null; }
  94462. this.name = name;
  94463. /**
  94464. * Gets or sets the list of animations
  94465. */
  94466. this.animations = new Array();
  94467. this._positions = null;
  94468. this._normals = null;
  94469. this._tangents = null;
  94470. /**
  94471. * Observable raised when the influence changes
  94472. */
  94473. this.onInfluenceChanged = new BABYLON.Observable();
  94474. this._animationPropertiesOverride = null;
  94475. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94476. this.influence = influence;
  94477. }
  94478. Object.defineProperty(MorphTarget.prototype, "influence", {
  94479. /**
  94480. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  94481. */
  94482. get: function () {
  94483. return this._influence;
  94484. },
  94485. set: function (influence) {
  94486. if (this._influence === influence) {
  94487. return;
  94488. }
  94489. var previous = this._influence;
  94490. this._influence = influence;
  94491. if (this.onInfluenceChanged.hasObservers) {
  94492. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  94493. }
  94494. },
  94495. enumerable: true,
  94496. configurable: true
  94497. });
  94498. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  94499. /**
  94500. * Gets or sets the animation properties override
  94501. */
  94502. get: function () {
  94503. if (!this._animationPropertiesOverride && this._scene) {
  94504. return this._scene.animationPropertiesOverride;
  94505. }
  94506. return this._animationPropertiesOverride;
  94507. },
  94508. set: function (value) {
  94509. this._animationPropertiesOverride = value;
  94510. },
  94511. enumerable: true,
  94512. configurable: true
  94513. });
  94514. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  94515. /**
  94516. * Gets a boolean defining if the target contains position data
  94517. */
  94518. get: function () {
  94519. return !!this._positions;
  94520. },
  94521. enumerable: true,
  94522. configurable: true
  94523. });
  94524. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  94525. /**
  94526. * Gets a boolean defining if the target contains normal data
  94527. */
  94528. get: function () {
  94529. return !!this._normals;
  94530. },
  94531. enumerable: true,
  94532. configurable: true
  94533. });
  94534. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  94535. /**
  94536. * Gets a boolean defining if the target contains tangent data
  94537. */
  94538. get: function () {
  94539. return !!this._tangents;
  94540. },
  94541. enumerable: true,
  94542. configurable: true
  94543. });
  94544. /**
  94545. * Affects position data to this target
  94546. * @param data defines the position data to use
  94547. */
  94548. MorphTarget.prototype.setPositions = function (data) {
  94549. this._positions = data;
  94550. };
  94551. /**
  94552. * Gets the position data stored in this target
  94553. * @returns a FloatArray containing the position data (or null if not present)
  94554. */
  94555. MorphTarget.prototype.getPositions = function () {
  94556. return this._positions;
  94557. };
  94558. /**
  94559. * Affects normal data to this target
  94560. * @param data defines the normal data to use
  94561. */
  94562. MorphTarget.prototype.setNormals = function (data) {
  94563. this._normals = data;
  94564. };
  94565. /**
  94566. * Gets the normal data stored in this target
  94567. * @returns a FloatArray containing the normal data (or null if not present)
  94568. */
  94569. MorphTarget.prototype.getNormals = function () {
  94570. return this._normals;
  94571. };
  94572. /**
  94573. * Affects tangent data to this target
  94574. * @param data defines the tangent data to use
  94575. */
  94576. MorphTarget.prototype.setTangents = function (data) {
  94577. this._tangents = data;
  94578. };
  94579. /**
  94580. * Gets the tangent data stored in this target
  94581. * @returns a FloatArray containing the tangent data (or null if not present)
  94582. */
  94583. MorphTarget.prototype.getTangents = function () {
  94584. return this._tangents;
  94585. };
  94586. /**
  94587. * Serializes the current target into a Serialization object
  94588. * @returns the serialized object
  94589. */
  94590. MorphTarget.prototype.serialize = function () {
  94591. var serializationObject = {};
  94592. serializationObject.name = this.name;
  94593. serializationObject.influence = this.influence;
  94594. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  94595. if (this.hasNormals) {
  94596. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  94597. }
  94598. if (this.hasTangents) {
  94599. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  94600. }
  94601. // Animations
  94602. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  94603. return serializationObject;
  94604. };
  94605. // Statics
  94606. /**
  94607. * Creates a new target from serialized data
  94608. * @param serializationObject defines the serialized data to use
  94609. * @returns a new MorphTarget
  94610. */
  94611. MorphTarget.Parse = function (serializationObject) {
  94612. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  94613. result.setPositions(serializationObject.positions);
  94614. if (serializationObject.normals) {
  94615. result.setNormals(serializationObject.normals);
  94616. }
  94617. if (serializationObject.tangents) {
  94618. result.setTangents(serializationObject.tangents);
  94619. }
  94620. // Animations
  94621. if (serializationObject.animations) {
  94622. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  94623. var parsedAnimation = serializationObject.animations[animationIndex];
  94624. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  94625. }
  94626. }
  94627. return result;
  94628. };
  94629. /**
  94630. * Creates a MorphTarget from mesh data
  94631. * @param mesh defines the source mesh
  94632. * @param name defines the name to use for the new target
  94633. * @param influence defines the influence to attach to the target
  94634. * @returns a new MorphTarget
  94635. */
  94636. MorphTarget.FromMesh = function (mesh, name, influence) {
  94637. if (!name) {
  94638. name = mesh.name;
  94639. }
  94640. var result = new MorphTarget(name, influence, mesh.getScene());
  94641. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  94642. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  94643. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  94644. }
  94645. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  94646. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  94647. }
  94648. return result;
  94649. };
  94650. return MorphTarget;
  94651. }());
  94652. BABYLON.MorphTarget = MorphTarget;
  94653. })(BABYLON || (BABYLON = {}));
  94654. //# sourceMappingURL=babylon.morphTarget.js.map
  94655. var BABYLON;
  94656. (function (BABYLON) {
  94657. /**
  94658. * This class is used to deform meshes using morphing between different targets
  94659. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  94660. */
  94661. var MorphTargetManager = /** @class */ (function () {
  94662. /**
  94663. * Creates a new MorphTargetManager
  94664. * @param scene defines the current scene
  94665. */
  94666. function MorphTargetManager(scene) {
  94667. if (scene === void 0) { scene = null; }
  94668. this._targets = new Array();
  94669. this._targetObservable = new Array();
  94670. this._activeTargets = new BABYLON.SmartArray(16);
  94671. this._supportsNormals = false;
  94672. this._supportsTangents = false;
  94673. this._vertexCount = 0;
  94674. this._uniqueId = 0;
  94675. this._tempInfluences = new Array();
  94676. if (!scene) {
  94677. scene = BABYLON.Engine.LastCreatedScene;
  94678. }
  94679. this._scene = scene;
  94680. if (this._scene) {
  94681. this._scene.morphTargetManagers.push(this);
  94682. this._uniqueId = this._scene.getUniqueId();
  94683. }
  94684. }
  94685. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  94686. /**
  94687. * Gets the unique ID of this manager
  94688. */
  94689. get: function () {
  94690. return this._uniqueId;
  94691. },
  94692. enumerable: true,
  94693. configurable: true
  94694. });
  94695. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  94696. /**
  94697. * Gets the number of vertices handled by this manager
  94698. */
  94699. get: function () {
  94700. return this._vertexCount;
  94701. },
  94702. enumerable: true,
  94703. configurable: true
  94704. });
  94705. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  94706. /**
  94707. * Gets a boolean indicating if this manager supports morphing of normals
  94708. */
  94709. get: function () {
  94710. return this._supportsNormals;
  94711. },
  94712. enumerable: true,
  94713. configurable: true
  94714. });
  94715. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  94716. /**
  94717. * Gets a boolean indicating if this manager supports morphing of tangents
  94718. */
  94719. get: function () {
  94720. return this._supportsTangents;
  94721. },
  94722. enumerable: true,
  94723. configurable: true
  94724. });
  94725. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  94726. /**
  94727. * Gets the number of targets stored in this manager
  94728. */
  94729. get: function () {
  94730. return this._targets.length;
  94731. },
  94732. enumerable: true,
  94733. configurable: true
  94734. });
  94735. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  94736. /**
  94737. * Gets the number of influencers (ie. the number of targets with influences > 0)
  94738. */
  94739. get: function () {
  94740. return this._activeTargets.length;
  94741. },
  94742. enumerable: true,
  94743. configurable: true
  94744. });
  94745. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  94746. /**
  94747. * Gets the list of influences (one per target)
  94748. */
  94749. get: function () {
  94750. return this._influences;
  94751. },
  94752. enumerable: true,
  94753. configurable: true
  94754. });
  94755. /**
  94756. * Gets the active target at specified index. An active target is a target with an influence > 0
  94757. * @param index defines the index to check
  94758. * @returns the requested target
  94759. */
  94760. MorphTargetManager.prototype.getActiveTarget = function (index) {
  94761. return this._activeTargets.data[index];
  94762. };
  94763. /**
  94764. * Gets the target at specified index
  94765. * @param index defines the index to check
  94766. * @returns the requested target
  94767. */
  94768. MorphTargetManager.prototype.getTarget = function (index) {
  94769. return this._targets[index];
  94770. };
  94771. /**
  94772. * Add a new target to this manager
  94773. * @param target defines the target to add
  94774. */
  94775. MorphTargetManager.prototype.addTarget = function (target) {
  94776. var _this = this;
  94777. this._targets.push(target);
  94778. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  94779. _this._syncActiveTargets(needUpdate);
  94780. }));
  94781. this._syncActiveTargets(true);
  94782. };
  94783. /**
  94784. * Removes a target from the manager
  94785. * @param target defines the target to remove
  94786. */
  94787. MorphTargetManager.prototype.removeTarget = function (target) {
  94788. var index = this._targets.indexOf(target);
  94789. if (index >= 0) {
  94790. this._targets.splice(index, 1);
  94791. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  94792. this._syncActiveTargets(true);
  94793. }
  94794. };
  94795. /**
  94796. * Serializes the current manager into a Serialization object
  94797. * @returns the serialized object
  94798. */
  94799. MorphTargetManager.prototype.serialize = function () {
  94800. var serializationObject = {};
  94801. serializationObject.id = this.uniqueId;
  94802. serializationObject.targets = [];
  94803. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  94804. var target = _a[_i];
  94805. serializationObject.targets.push(target.serialize());
  94806. }
  94807. return serializationObject;
  94808. };
  94809. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  94810. var influenceCount = 0;
  94811. this._activeTargets.reset();
  94812. this._supportsNormals = true;
  94813. this._supportsTangents = true;
  94814. this._vertexCount = 0;
  94815. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  94816. var target = _a[_i];
  94817. this._activeTargets.push(target);
  94818. this._tempInfluences[influenceCount++] = target.influence;
  94819. var positions = target.getPositions();
  94820. if (positions) {
  94821. this._supportsNormals = this._supportsNormals && target.hasNormals;
  94822. this._supportsTangents = this._supportsTangents && target.hasTangents;
  94823. var vertexCount = positions.length / 3;
  94824. if (this._vertexCount === 0) {
  94825. this._vertexCount = vertexCount;
  94826. }
  94827. else if (this._vertexCount !== vertexCount) {
  94828. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  94829. return;
  94830. }
  94831. }
  94832. }
  94833. if (!this._influences || this._influences.length !== influenceCount) {
  94834. this._influences = new Float32Array(influenceCount);
  94835. }
  94836. for (var index = 0; index < influenceCount; index++) {
  94837. this._influences[index] = this._tempInfluences[index];
  94838. }
  94839. if (needUpdate) {
  94840. this.synchronize();
  94841. }
  94842. };
  94843. /**
  94844. * Syncrhonize the targets with all the meshes using this morph target manager
  94845. */
  94846. MorphTargetManager.prototype.synchronize = function () {
  94847. if (!this._scene) {
  94848. return;
  94849. }
  94850. // Flag meshes as dirty to resync with the active targets
  94851. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  94852. var mesh = _a[_i];
  94853. if (mesh.morphTargetManager === this) {
  94854. mesh._syncGeometryWithMorphTargetManager();
  94855. }
  94856. }
  94857. };
  94858. // Statics
  94859. /**
  94860. * Creates a new MorphTargetManager from serialized data
  94861. * @param serializationObject defines the serialized data
  94862. * @param scene defines the hosting scene
  94863. * @returns the new MorphTargetManager
  94864. */
  94865. MorphTargetManager.Parse = function (serializationObject, scene) {
  94866. var result = new MorphTargetManager(scene);
  94867. result._uniqueId = serializationObject.id;
  94868. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  94869. var targetData = _a[_i];
  94870. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  94871. }
  94872. return result;
  94873. };
  94874. return MorphTargetManager;
  94875. }());
  94876. BABYLON.MorphTargetManager = MorphTargetManager;
  94877. })(BABYLON || (BABYLON = {}));
  94878. //# sourceMappingURL=babylon.morphTargetManager.js.map
  94879. var BABYLON;
  94880. (function (BABYLON) {
  94881. var Octree = /** @class */ (function () {
  94882. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  94883. if (maxDepth === void 0) { maxDepth = 2; }
  94884. this.maxDepth = maxDepth;
  94885. this.dynamicContent = new Array();
  94886. this._maxBlockCapacity = maxBlockCapacity || 64;
  94887. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  94888. this._creationFunc = creationFunc;
  94889. }
  94890. // Methods
  94891. Octree.prototype.update = function (worldMin, worldMax, entries) {
  94892. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  94893. };
  94894. Octree.prototype.addMesh = function (entry) {
  94895. for (var index = 0; index < this.blocks.length; index++) {
  94896. var block = this.blocks[index];
  94897. block.addEntry(entry);
  94898. }
  94899. };
  94900. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  94901. this._selectionContent.reset();
  94902. for (var index = 0; index < this.blocks.length; index++) {
  94903. var block = this.blocks[index];
  94904. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  94905. }
  94906. if (allowDuplicate) {
  94907. this._selectionContent.concat(this.dynamicContent);
  94908. }
  94909. else {
  94910. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94911. }
  94912. return this._selectionContent;
  94913. };
  94914. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  94915. this._selectionContent.reset();
  94916. for (var index = 0; index < this.blocks.length; index++) {
  94917. var block = this.blocks[index];
  94918. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  94919. }
  94920. if (allowDuplicate) {
  94921. this._selectionContent.concat(this.dynamicContent);
  94922. }
  94923. else {
  94924. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94925. }
  94926. return this._selectionContent;
  94927. };
  94928. Octree.prototype.intersectsRay = function (ray) {
  94929. this._selectionContent.reset();
  94930. for (var index = 0; index < this.blocks.length; index++) {
  94931. var block = this.blocks[index];
  94932. block.intersectsRay(ray, this._selectionContent);
  94933. }
  94934. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94935. return this._selectionContent;
  94936. };
  94937. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  94938. target.blocks = new Array();
  94939. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  94940. // Segmenting space
  94941. for (var x = 0; x < 2; x++) {
  94942. for (var y = 0; y < 2; y++) {
  94943. for (var z = 0; z < 2; z++) {
  94944. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  94945. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  94946. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  94947. block.addEntries(entries);
  94948. target.blocks.push(block);
  94949. }
  94950. }
  94951. }
  94952. };
  94953. Octree.CreationFuncForMeshes = function (entry, block) {
  94954. var boundingInfo = entry.getBoundingInfo();
  94955. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  94956. block.entries.push(entry);
  94957. }
  94958. };
  94959. Octree.CreationFuncForSubMeshes = function (entry, block) {
  94960. var boundingInfo = entry.getBoundingInfo();
  94961. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  94962. block.entries.push(entry);
  94963. }
  94964. };
  94965. return Octree;
  94966. }());
  94967. BABYLON.Octree = Octree;
  94968. })(BABYLON || (BABYLON = {}));
  94969. //# sourceMappingURL=babylon.octree.js.map
  94970. var BABYLON;
  94971. (function (BABYLON) {
  94972. var OctreeBlock = /** @class */ (function () {
  94973. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  94974. this.entries = new Array();
  94975. this._boundingVectors = new Array();
  94976. this._capacity = capacity;
  94977. this._depth = depth;
  94978. this._maxDepth = maxDepth;
  94979. this._creationFunc = creationFunc;
  94980. this._minPoint = minPoint;
  94981. this._maxPoint = maxPoint;
  94982. this._boundingVectors.push(minPoint.clone());
  94983. this._boundingVectors.push(maxPoint.clone());
  94984. this._boundingVectors.push(minPoint.clone());
  94985. this._boundingVectors[2].x = maxPoint.x;
  94986. this._boundingVectors.push(minPoint.clone());
  94987. this._boundingVectors[3].y = maxPoint.y;
  94988. this._boundingVectors.push(minPoint.clone());
  94989. this._boundingVectors[4].z = maxPoint.z;
  94990. this._boundingVectors.push(maxPoint.clone());
  94991. this._boundingVectors[5].z = minPoint.z;
  94992. this._boundingVectors.push(maxPoint.clone());
  94993. this._boundingVectors[6].x = minPoint.x;
  94994. this._boundingVectors.push(maxPoint.clone());
  94995. this._boundingVectors[7].y = minPoint.y;
  94996. }
  94997. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  94998. // Property
  94999. get: function () {
  95000. return this._capacity;
  95001. },
  95002. enumerable: true,
  95003. configurable: true
  95004. });
  95005. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  95006. get: function () {
  95007. return this._minPoint;
  95008. },
  95009. enumerable: true,
  95010. configurable: true
  95011. });
  95012. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  95013. get: function () {
  95014. return this._maxPoint;
  95015. },
  95016. enumerable: true,
  95017. configurable: true
  95018. });
  95019. // Methods
  95020. OctreeBlock.prototype.addEntry = function (entry) {
  95021. if (this.blocks) {
  95022. for (var index = 0; index < this.blocks.length; index++) {
  95023. var block = this.blocks[index];
  95024. block.addEntry(entry);
  95025. }
  95026. return;
  95027. }
  95028. this._creationFunc(entry, this);
  95029. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  95030. this.createInnerBlocks();
  95031. }
  95032. };
  95033. OctreeBlock.prototype.addEntries = function (entries) {
  95034. for (var index = 0; index < entries.length; index++) {
  95035. var mesh = entries[index];
  95036. this.addEntry(mesh);
  95037. }
  95038. };
  95039. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  95040. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  95041. if (this.blocks) {
  95042. for (var index = 0; index < this.blocks.length; index++) {
  95043. var block = this.blocks[index];
  95044. block.select(frustumPlanes, selection, allowDuplicate);
  95045. }
  95046. return;
  95047. }
  95048. if (allowDuplicate) {
  95049. selection.concat(this.entries);
  95050. }
  95051. else {
  95052. selection.concatWithNoDuplicate(this.entries);
  95053. }
  95054. }
  95055. };
  95056. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  95057. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  95058. if (this.blocks) {
  95059. for (var index = 0; index < this.blocks.length; index++) {
  95060. var block = this.blocks[index];
  95061. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  95062. }
  95063. return;
  95064. }
  95065. if (allowDuplicate) {
  95066. selection.concat(this.entries);
  95067. }
  95068. else {
  95069. selection.concatWithNoDuplicate(this.entries);
  95070. }
  95071. }
  95072. };
  95073. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  95074. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  95075. if (this.blocks) {
  95076. for (var index = 0; index < this.blocks.length; index++) {
  95077. var block = this.blocks[index];
  95078. block.intersectsRay(ray, selection);
  95079. }
  95080. return;
  95081. }
  95082. selection.concatWithNoDuplicate(this.entries);
  95083. }
  95084. };
  95085. OctreeBlock.prototype.createInnerBlocks = function () {
  95086. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  95087. };
  95088. return OctreeBlock;
  95089. }());
  95090. BABYLON.OctreeBlock = OctreeBlock;
  95091. })(BABYLON || (BABYLON = {}));
  95092. //# sourceMappingURL=babylon.octreeBlock.js.map
  95093. var BABYLON;
  95094. (function (BABYLON) {
  95095. /**
  95096. * Postprocess used to generate anaglyphic rendering
  95097. */
  95098. var AnaglyphPostProcess = /** @class */ (function (_super) {
  95099. __extends(AnaglyphPostProcess, _super);
  95100. /**
  95101. * Creates a new AnaglyphPostProcess
  95102. * @param name defines postprocess name
  95103. * @param options defines creation options or target ratio scale
  95104. * @param rigCameras defines cameras using this postprocess
  95105. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  95106. * @param engine defines hosting engine
  95107. * @param reusable defines if the postprocess will be reused multiple times per frame
  95108. */
  95109. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  95110. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  95111. _this._passedProcess = rigCameras[0]._rigPostProcess;
  95112. _this.onApplyObservable.add(function (effect) {
  95113. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  95114. });
  95115. return _this;
  95116. }
  95117. return AnaglyphPostProcess;
  95118. }(BABYLON.PostProcess));
  95119. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  95120. })(BABYLON || (BABYLON = {}));
  95121. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  95122. var BABYLON;
  95123. (function (BABYLON) {
  95124. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  95125. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95126. });
  95127. /**
  95128. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  95129. */
  95130. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  95131. __extends(AnaglyphArcRotateCamera, _super);
  95132. /**
  95133. * Creates a new AnaglyphArcRotateCamera
  95134. * @param name defines camera name
  95135. * @param alpha defines alpha angle (in radians)
  95136. * @param beta defines beta angle (in radians)
  95137. * @param radius defines radius
  95138. * @param target defines camera target
  95139. * @param interaxialDistance defines distance between each color axis
  95140. * @param scene defines the hosting scene
  95141. */
  95142. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  95143. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  95144. _this.interaxialDistance = interaxialDistance;
  95145. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95146. return _this;
  95147. }
  95148. /**
  95149. * Gets camera class name
  95150. * @returns AnaglyphArcRotateCamera
  95151. */
  95152. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  95153. return "AnaglyphArcRotateCamera";
  95154. };
  95155. return AnaglyphArcRotateCamera;
  95156. }(BABYLON.ArcRotateCamera));
  95157. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  95158. })(BABYLON || (BABYLON = {}));
  95159. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  95160. var BABYLON;
  95161. (function (BABYLON) {
  95162. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  95163. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95164. });
  95165. /**
  95166. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  95167. */
  95168. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  95169. __extends(AnaglyphFreeCamera, _super);
  95170. /**
  95171. * Creates a new AnaglyphFreeCamera
  95172. * @param name defines camera name
  95173. * @param position defines initial position
  95174. * @param interaxialDistance defines distance between each color axis
  95175. * @param scene defines the hosting scene
  95176. */
  95177. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  95178. var _this = _super.call(this, name, position, scene) || this;
  95179. _this.interaxialDistance = interaxialDistance;
  95180. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95181. return _this;
  95182. }
  95183. /**
  95184. * Gets camera class name
  95185. * @returns AnaglyphFreeCamera
  95186. */
  95187. AnaglyphFreeCamera.prototype.getClassName = function () {
  95188. return "AnaglyphFreeCamera";
  95189. };
  95190. return AnaglyphFreeCamera;
  95191. }(BABYLON.FreeCamera));
  95192. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  95193. })(BABYLON || (BABYLON = {}));
  95194. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  95195. var BABYLON;
  95196. (function (BABYLON) {
  95197. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  95198. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95199. });
  95200. /**
  95201. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  95202. */
  95203. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  95204. __extends(AnaglyphGamepadCamera, _super);
  95205. /**
  95206. * Creates a new AnaglyphGamepadCamera
  95207. * @param name defines camera name
  95208. * @param position defines initial position
  95209. * @param interaxialDistance defines distance between each color axis
  95210. * @param scene defines the hosting scene
  95211. */
  95212. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  95213. var _this = _super.call(this, name, position, scene) || this;
  95214. _this.interaxialDistance = interaxialDistance;
  95215. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95216. return _this;
  95217. }
  95218. /**
  95219. * Gets camera class name
  95220. * @returns AnaglyphGamepadCamera
  95221. */
  95222. AnaglyphGamepadCamera.prototype.getClassName = function () {
  95223. return "AnaglyphGamepadCamera";
  95224. };
  95225. return AnaglyphGamepadCamera;
  95226. }(BABYLON.GamepadCamera));
  95227. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  95228. })(BABYLON || (BABYLON = {}));
  95229. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  95230. var BABYLON;
  95231. (function (BABYLON) {
  95232. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  95233. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95234. });
  95235. /**
  95236. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  95237. */
  95238. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  95239. __extends(AnaglyphUniversalCamera, _super);
  95240. /**
  95241. * Creates a new AnaglyphUniversalCamera
  95242. * @param name defines camera name
  95243. * @param position defines initial position
  95244. * @param interaxialDistance defines distance between each color axis
  95245. * @param scene defines the hosting scene
  95246. */
  95247. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  95248. var _this = _super.call(this, name, position, scene) || this;
  95249. _this.interaxialDistance = interaxialDistance;
  95250. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95251. return _this;
  95252. }
  95253. /**
  95254. * Gets camera class name
  95255. * @returns AnaglyphUniversalCamera
  95256. */
  95257. AnaglyphUniversalCamera.prototype.getClassName = function () {
  95258. return "AnaglyphUniversalCamera";
  95259. };
  95260. return AnaglyphUniversalCamera;
  95261. }(BABYLON.UniversalCamera));
  95262. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  95263. })(BABYLON || (BABYLON = {}));
  95264. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  95265. var BABYLON;
  95266. (function (BABYLON) {
  95267. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  95268. __extends(StereoscopicInterlacePostProcess, _super);
  95269. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  95270. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  95271. _this._passedProcess = rigCameras[0]._rigPostProcess;
  95272. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  95273. _this.onSizeChangedObservable.add(function () {
  95274. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  95275. });
  95276. _this.onApplyObservable.add(function (effect) {
  95277. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  95278. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  95279. });
  95280. return _this;
  95281. }
  95282. return StereoscopicInterlacePostProcess;
  95283. }(BABYLON.PostProcess));
  95284. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  95285. })(BABYLON || (BABYLON = {}));
  95286. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  95287. var BABYLON;
  95288. (function (BABYLON) {
  95289. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  95290. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  95291. });
  95292. /**
  95293. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  95294. */
  95295. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  95296. __extends(StereoscopicArcRotateCamera, _super);
  95297. /**
  95298. * Creates a new StereoscopicArcRotateCamera
  95299. * @param name defines camera name
  95300. * @param alpha defines alpha angle (in radians)
  95301. * @param beta defines beta angle (in radians)
  95302. * @param radius defines radius
  95303. * @param target defines camera target
  95304. * @param interaxialDistance defines distance between each color axis
  95305. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  95306. * @param scene defines the hosting scene
  95307. */
  95308. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  95309. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  95310. _this.interaxialDistance = interaxialDistance;
  95311. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  95312. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  95313. return _this;
  95314. }
  95315. /**
  95316. * Gets camera class name
  95317. * @returns StereoscopicArcRotateCamera
  95318. */
  95319. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  95320. return "StereoscopicArcRotateCamera";
  95321. };
  95322. return StereoscopicArcRotateCamera;
  95323. }(BABYLON.ArcRotateCamera));
  95324. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  95325. })(BABYLON || (BABYLON = {}));
  95326. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  95327. var BABYLON;
  95328. (function (BABYLON) {
  95329. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  95330. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  95331. });
  95332. /**
  95333. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  95334. */
  95335. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  95336. __extends(StereoscopicFreeCamera, _super);
  95337. /**
  95338. * Creates a new StereoscopicFreeCamera
  95339. * @param name defines camera name
  95340. * @param position defines initial position
  95341. * @param interaxialDistance defines distance between each color axis
  95342. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  95343. * @param scene defines the hosting scene
  95344. */
  95345. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  95346. var _this = _super.call(this, name, position, scene) || this;
  95347. _this.interaxialDistance = interaxialDistance;
  95348. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  95349. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  95350. return _this;
  95351. }
  95352. /**
  95353. * Gets camera class name
  95354. * @returns StereoscopicFreeCamera
  95355. */
  95356. StereoscopicFreeCamera.prototype.getClassName = function () {
  95357. return "StereoscopicFreeCamera";
  95358. };
  95359. return StereoscopicFreeCamera;
  95360. }(BABYLON.FreeCamera));
  95361. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  95362. })(BABYLON || (BABYLON = {}));
  95363. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  95364. var BABYLON;
  95365. (function (BABYLON) {
  95366. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  95367. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  95368. });
  95369. /**
  95370. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  95371. */
  95372. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  95373. __extends(StereoscopicGamepadCamera, _super);
  95374. /**
  95375. * Creates a new StereoscopicGamepadCamera
  95376. * @param name defines camera name
  95377. * @param position defines initial position
  95378. * @param interaxialDistance defines distance between each color axis
  95379. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  95380. * @param scene defines the hosting scene
  95381. */
  95382. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  95383. var _this = _super.call(this, name, position, scene) || this;
  95384. _this.interaxialDistance = interaxialDistance;
  95385. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  95386. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  95387. return _this;
  95388. }
  95389. /**
  95390. * Gets camera class name
  95391. * @returns StereoscopicGamepadCamera
  95392. */
  95393. StereoscopicGamepadCamera.prototype.getClassName = function () {
  95394. return "StereoscopicGamepadCamera";
  95395. };
  95396. return StereoscopicGamepadCamera;
  95397. }(BABYLON.GamepadCamera));
  95398. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  95399. })(BABYLON || (BABYLON = {}));
  95400. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  95401. var BABYLON;
  95402. (function (BABYLON) {
  95403. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  95404. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  95405. });
  95406. /**
  95407. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  95408. */
  95409. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  95410. __extends(StereoscopicUniversalCamera, _super);
  95411. /**
  95412. * Creates a new StereoscopicUniversalCamera
  95413. * @param name defines camera name
  95414. * @param position defines initial position
  95415. * @param interaxialDistance defines distance between each color axis
  95416. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  95417. * @param scene defines the hosting scene
  95418. */
  95419. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  95420. var _this = _super.call(this, name, position, scene) || this;
  95421. _this.interaxialDistance = interaxialDistance;
  95422. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  95423. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  95424. return _this;
  95425. }
  95426. /**
  95427. * Gets camera class name
  95428. * @returns StereoscopicUniversalCamera
  95429. */
  95430. StereoscopicUniversalCamera.prototype.getClassName = function () {
  95431. return "StereoscopicUniversalCamera";
  95432. };
  95433. return StereoscopicUniversalCamera;
  95434. }(BABYLON.UniversalCamera));
  95435. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  95436. })(BABYLON || (BABYLON = {}));
  95437. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  95438. var BABYLON;
  95439. (function (BABYLON) {
  95440. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  95441. __extends(VRDistortionCorrectionPostProcess, _super);
  95442. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  95443. var _this = _super.call(this, name, "vrDistortionCorrection", [
  95444. 'LensCenter',
  95445. 'Scale',
  95446. 'ScaleIn',
  95447. 'HmdWarpParam'
  95448. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  95449. _this._isRightEye = isRightEye;
  95450. _this._distortionFactors = vrMetrics.distortionK;
  95451. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  95452. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  95453. _this.adaptScaleToCurrentViewport = true;
  95454. _this.onSizeChangedObservable.add(function () {
  95455. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  95456. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  95457. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  95458. });
  95459. _this.onApplyObservable.add(function (effect) {
  95460. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  95461. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  95462. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  95463. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  95464. });
  95465. return _this;
  95466. }
  95467. return VRDistortionCorrectionPostProcess;
  95468. }(BABYLON.PostProcess));
  95469. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  95470. })(BABYLON || (BABYLON = {}));
  95471. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  95472. var BABYLON;
  95473. (function (BABYLON) {
  95474. /**
  95475. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  95476. * Screen rotation is taken into account.
  95477. */
  95478. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  95479. function FreeCameraDeviceOrientationInput() {
  95480. var _this = this;
  95481. this._screenOrientationAngle = 0;
  95482. this._screenQuaternion = new BABYLON.Quaternion();
  95483. this._alpha = 0;
  95484. this._beta = 0;
  95485. this._gamma = 0;
  95486. this._orientationChanged = function () {
  95487. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  95488. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  95489. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  95490. };
  95491. this._deviceOrientation = function (evt) {
  95492. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  95493. _this._beta = evt.beta !== null ? evt.beta : 0;
  95494. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  95495. };
  95496. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  95497. this._orientationChanged();
  95498. }
  95499. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  95500. get: function () {
  95501. return this._camera;
  95502. },
  95503. set: function (camera) {
  95504. this._camera = camera;
  95505. if (this._camera != null && !this._camera.rotationQuaternion) {
  95506. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  95507. }
  95508. },
  95509. enumerable: true,
  95510. configurable: true
  95511. });
  95512. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  95513. window.addEventListener("orientationchange", this._orientationChanged);
  95514. window.addEventListener("deviceorientation", this._deviceOrientation);
  95515. //In certain cases, the attach control is called AFTER orientation was changed,
  95516. //So this is needed.
  95517. this._orientationChanged();
  95518. };
  95519. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  95520. window.removeEventListener("orientationchange", this._orientationChanged);
  95521. window.removeEventListener("deviceorientation", this._deviceOrientation);
  95522. };
  95523. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  95524. //if no device orientation provided, don't update the rotation.
  95525. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  95526. if (!this._alpha)
  95527. return;
  95528. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  95529. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  95530. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  95531. //Mirror on XY Plane
  95532. this._camera.rotationQuaternion.z *= -1;
  95533. this._camera.rotationQuaternion.w *= -1;
  95534. };
  95535. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  95536. return "FreeCameraDeviceOrientationInput";
  95537. };
  95538. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  95539. return "deviceOrientation";
  95540. };
  95541. return FreeCameraDeviceOrientationInput;
  95542. }());
  95543. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  95544. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  95545. })(BABYLON || (BABYLON = {}));
  95546. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  95547. var BABYLON;
  95548. (function (BABYLON) {
  95549. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  95550. function ArcRotateCameraVRDeviceOrientationInput() {
  95551. this.alphaCorrection = 1;
  95552. this.betaCorrection = 1;
  95553. this.gammaCorrection = 1;
  95554. this._alpha = 0;
  95555. this._gamma = 0;
  95556. this._dirty = false;
  95557. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  95558. }
  95559. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  95560. this.camera.attachControl(element, noPreventDefault);
  95561. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  95562. };
  95563. /** @hidden */
  95564. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  95565. if (evt.alpha !== null) {
  95566. this._alpha = +evt.alpha | 0;
  95567. }
  95568. if (evt.gamma !== null) {
  95569. this._gamma = +evt.gamma | 0;
  95570. }
  95571. this._dirty = true;
  95572. };
  95573. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  95574. if (this._dirty) {
  95575. this._dirty = false;
  95576. if (this._gamma < 0) {
  95577. this._gamma = 180 + this._gamma;
  95578. }
  95579. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  95580. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  95581. }
  95582. };
  95583. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  95584. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  95585. };
  95586. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  95587. return "ArcRotateCameraVRDeviceOrientationInput";
  95588. };
  95589. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  95590. return "VRDeviceOrientation";
  95591. };
  95592. return ArcRotateCameraVRDeviceOrientationInput;
  95593. }());
  95594. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  95595. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  95596. })(BABYLON || (BABYLON = {}));
  95597. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  95598. var BABYLON;
  95599. (function (BABYLON) {
  95600. var VRCameraMetrics = /** @class */ (function () {
  95601. function VRCameraMetrics() {
  95602. this.compensateDistortion = true;
  95603. }
  95604. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  95605. get: function () {
  95606. return this.hResolution / (2 * this.vResolution);
  95607. },
  95608. enumerable: true,
  95609. configurable: true
  95610. });
  95611. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  95612. get: function () {
  95613. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  95614. },
  95615. enumerable: true,
  95616. configurable: true
  95617. });
  95618. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  95619. get: function () {
  95620. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  95621. var h = (4 * meters) / this.hScreenSize;
  95622. return BABYLON.Matrix.Translation(h, 0, 0);
  95623. },
  95624. enumerable: true,
  95625. configurable: true
  95626. });
  95627. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  95628. get: function () {
  95629. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  95630. var h = (4 * meters) / this.hScreenSize;
  95631. return BABYLON.Matrix.Translation(-h, 0, 0);
  95632. },
  95633. enumerable: true,
  95634. configurable: true
  95635. });
  95636. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  95637. get: function () {
  95638. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  95639. },
  95640. enumerable: true,
  95641. configurable: true
  95642. });
  95643. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  95644. get: function () {
  95645. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  95646. },
  95647. enumerable: true,
  95648. configurable: true
  95649. });
  95650. VRCameraMetrics.GetDefault = function () {
  95651. var result = new VRCameraMetrics();
  95652. result.hResolution = 1280;
  95653. result.vResolution = 800;
  95654. result.hScreenSize = 0.149759993;
  95655. result.vScreenSize = 0.0935999975;
  95656. result.vScreenCenter = 0.0467999987;
  95657. result.eyeToScreenDistance = 0.0410000011;
  95658. result.lensSeparationDistance = 0.0635000020;
  95659. result.interpupillaryDistance = 0.0640000030;
  95660. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  95661. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  95662. result.postProcessScaleFactor = 1.714605507808412;
  95663. result.lensCenterOffset = 0.151976421;
  95664. return result;
  95665. };
  95666. return VRCameraMetrics;
  95667. }());
  95668. BABYLON.VRCameraMetrics = VRCameraMetrics;
  95669. })(BABYLON || (BABYLON = {}));
  95670. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  95671. var BABYLON;
  95672. (function (BABYLON) {
  95673. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  95674. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  95675. });
  95676. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  95677. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  95678. });
  95679. /**
  95680. * This represents a WebVR camera.
  95681. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  95682. * @example http://doc.babylonjs.com/how_to/webvr_camera
  95683. */
  95684. var WebVRFreeCamera = /** @class */ (function (_super) {
  95685. __extends(WebVRFreeCamera, _super);
  95686. /**
  95687. * Instantiates a WebVRFreeCamera.
  95688. * @param name The name of the WebVRFreeCamera
  95689. * @param position The starting anchor position for the camera
  95690. * @param scene The scene the camera belongs to
  95691. * @param webVROptions a set of customizable options for the webVRCamera
  95692. */
  95693. function WebVRFreeCamera(name, position, scene, webVROptions) {
  95694. if (webVROptions === void 0) { webVROptions = {}; }
  95695. var _this = _super.call(this, name, position, scene) || this;
  95696. _this.webVROptions = webVROptions;
  95697. /**
  95698. * @hidden
  95699. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  95700. */
  95701. _this._vrDevice = null;
  95702. /**
  95703. * The rawPose of the vrDevice.
  95704. */
  95705. _this.rawPose = null;
  95706. _this._specsVersion = "1.1";
  95707. _this._attached = false;
  95708. _this._descendants = [];
  95709. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  95710. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  95711. /** @hidden */
  95712. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  95713. _this._standingMatrix = null;
  95714. /**
  95715. * Represents device position in babylon space.
  95716. */
  95717. _this.devicePosition = BABYLON.Vector3.Zero();
  95718. /**
  95719. * Represents device rotation in babylon space.
  95720. */
  95721. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  95722. /**
  95723. * The scale of the device to be used when translating from device space to babylon space.
  95724. */
  95725. _this.deviceScaleFactor = 1;
  95726. _this._deviceToWorld = BABYLON.Matrix.Identity();
  95727. _this._worldToDevice = BABYLON.Matrix.Identity();
  95728. /**
  95729. * References to the webVR controllers for the vrDevice.
  95730. */
  95731. _this.controllers = [];
  95732. /**
  95733. * Emits an event when a controller is attached.
  95734. */
  95735. _this.onControllersAttachedObservable = new BABYLON.Observable();
  95736. /**
  95737. * Emits an event when a controller's mesh has been loaded;
  95738. */
  95739. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  95740. /**
  95741. * Emits an event when the HMD's pose has been updated.
  95742. */
  95743. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  95744. _this._poseSet = false;
  95745. /**
  95746. * If the rig cameras be used as parent instead of this camera.
  95747. */
  95748. _this.rigParenting = true;
  95749. _this._defaultHeight = undefined;
  95750. _this._htmlElementAttached = null;
  95751. _this._detachIfAttached = function () {
  95752. var vrDisplay = _this.getEngine().getVRDevice();
  95753. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  95754. _this.detachControl(_this._htmlElementAttached);
  95755. }
  95756. };
  95757. _this._workingVector = BABYLON.Vector3.Zero();
  95758. _this._oneVector = BABYLON.Vector3.One();
  95759. _this._workingMatrix = BABYLON.Matrix.Identity();
  95760. _this._tmpMatrix = new BABYLON.Matrix();
  95761. _this._cache.position = BABYLON.Vector3.Zero();
  95762. if (webVROptions.defaultHeight) {
  95763. _this._defaultHeight = webVROptions.defaultHeight;
  95764. _this.position.y = _this._defaultHeight;
  95765. }
  95766. _this.minZ = 0.1;
  95767. //legacy support - the compensation boolean was removed.
  95768. if (arguments.length === 5) {
  95769. _this.webVROptions = arguments[4];
  95770. }
  95771. // default webVR options
  95772. if (_this.webVROptions.trackPosition == undefined) {
  95773. _this.webVROptions.trackPosition = true;
  95774. }
  95775. if (_this.webVROptions.controllerMeshes == undefined) {
  95776. _this.webVROptions.controllerMeshes = true;
  95777. }
  95778. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  95779. _this.webVROptions.defaultLightingOnControllers = true;
  95780. }
  95781. _this.rotationQuaternion = new BABYLON.Quaternion();
  95782. if (_this.webVROptions && _this.webVROptions.positionScale) {
  95783. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  95784. }
  95785. //enable VR
  95786. var engine = _this.getEngine();
  95787. _this._onVREnabled = function (success) { if (success) {
  95788. _this.initControllers();
  95789. } };
  95790. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  95791. engine.initWebVR().add(function (event) {
  95792. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  95793. return;
  95794. }
  95795. _this._vrDevice = event.vrDisplay;
  95796. //reset the rig parameters.
  95797. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  95798. if (_this._attached) {
  95799. _this.getEngine().enableVR();
  95800. }
  95801. });
  95802. if (typeof (VRFrameData) !== "undefined")
  95803. _this._frameData = new VRFrameData();
  95804. /**
  95805. * The idea behind the following lines:
  95806. * objects that have the camera as parent should actually have the rig cameras as a parent.
  95807. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  95808. * the second will not show it correctly.
  95809. *
  95810. * To solve this - each object that has the camera as parent will be added to a protected array.
  95811. * When the rig camera renders, it will take this array and set all of those to be its children.
  95812. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  95813. * Amazing!
  95814. */
  95815. scene.onBeforeCameraRenderObservable.add(function (camera) {
  95816. if (camera.parent === _this && _this.rigParenting) {
  95817. _this._descendants = _this.getDescendants(true, function (n) {
  95818. // don't take the cameras or the controllers!
  95819. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  95820. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  95821. return !isController && !isRigCamera;
  95822. });
  95823. _this._descendants.forEach(function (node) {
  95824. node.parent = camera;
  95825. });
  95826. }
  95827. });
  95828. scene.onAfterCameraRenderObservable.add(function (camera) {
  95829. if (camera.parent === _this && _this.rigParenting) {
  95830. _this._descendants.forEach(function (node) {
  95831. node.parent = _this;
  95832. });
  95833. }
  95834. });
  95835. return _this;
  95836. }
  95837. /**
  95838. * Gets the device distance from the ground in meters.
  95839. * @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.
  95840. */
  95841. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  95842. if (this._standingMatrix) {
  95843. // Add standing matrix offset to get real offset from ground in room
  95844. this._standingMatrix.getTranslationToRef(this._workingVector);
  95845. return this._deviceRoomPosition.y + this._workingVector.y;
  95846. }
  95847. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  95848. return this._defaultHeight || 0;
  95849. };
  95850. /**
  95851. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  95852. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  95853. */
  95854. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  95855. var _this = this;
  95856. if (callback === void 0) { callback = function (bool) { }; }
  95857. // Use standing matrix if available
  95858. this.getEngine().initWebVRAsync().then(function (result) {
  95859. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  95860. callback(false);
  95861. }
  95862. else {
  95863. _this._standingMatrix = new BABYLON.Matrix();
  95864. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  95865. if (!_this.getScene().useRightHandedSystem) {
  95866. [2, 6, 8, 9, 14].forEach(function (num) {
  95867. if (_this._standingMatrix) {
  95868. _this._standingMatrix.m[num] *= -1;
  95869. }
  95870. });
  95871. }
  95872. callback(true);
  95873. }
  95874. });
  95875. };
  95876. /**
  95877. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  95878. * @returns A promise with a boolean set to if the standing matrix is supported.
  95879. */
  95880. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  95881. var _this = this;
  95882. return new Promise(function (res, rej) {
  95883. _this.useStandingMatrix(function (supported) {
  95884. res(supported);
  95885. });
  95886. });
  95887. };
  95888. /**
  95889. * Disposes the camera
  95890. */
  95891. WebVRFreeCamera.prototype.dispose = function () {
  95892. this._detachIfAttached();
  95893. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  95894. _super.prototype.dispose.call(this);
  95895. };
  95896. /**
  95897. * Gets a vrController by name.
  95898. * @param name The name of the controller to retreive
  95899. * @returns the controller matching the name specified or null if not found
  95900. */
  95901. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  95902. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  95903. var gp = _a[_i];
  95904. if (gp.hand === name) {
  95905. return gp;
  95906. }
  95907. }
  95908. return null;
  95909. };
  95910. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  95911. /**
  95912. * The controller corrisponding to the users left hand.
  95913. */
  95914. get: function () {
  95915. if (!this._leftController) {
  95916. this._leftController = this.getControllerByName("left");
  95917. }
  95918. return this._leftController;
  95919. },
  95920. enumerable: true,
  95921. configurable: true
  95922. });
  95923. ;
  95924. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  95925. /**
  95926. * The controller corrisponding to the users right hand.
  95927. */
  95928. get: function () {
  95929. if (!this._rightController) {
  95930. this._rightController = this.getControllerByName("right");
  95931. }
  95932. return this._rightController;
  95933. },
  95934. enumerable: true,
  95935. configurable: true
  95936. });
  95937. ;
  95938. /**
  95939. * Casts a ray forward from the vrCamera's gaze.
  95940. * @param length Length of the ray (default: 100)
  95941. * @returns the ray corrisponding to the gaze
  95942. */
  95943. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  95944. if (length === void 0) { length = 100; }
  95945. if (this.leftCamera) {
  95946. // Use left eye to avoid computation to compute center on every call
  95947. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  95948. }
  95949. else {
  95950. return _super.prototype.getForwardRay.call(this, length);
  95951. }
  95952. };
  95953. /**
  95954. * @hidden
  95955. * Updates the camera based on device's frame data
  95956. */
  95957. WebVRFreeCamera.prototype._checkInputs = function () {
  95958. if (this._vrDevice && this._vrDevice.isPresenting) {
  95959. this._vrDevice.getFrameData(this._frameData);
  95960. this.updateFromDevice(this._frameData.pose);
  95961. }
  95962. _super.prototype._checkInputs.call(this);
  95963. };
  95964. /**
  95965. * Updates the poseControlled values based on the input device pose.
  95966. * @param poseData Pose coming from the device
  95967. */
  95968. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  95969. if (poseData && poseData.orientation) {
  95970. this.rawPose = poseData;
  95971. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  95972. if (this.getScene().useRightHandedSystem) {
  95973. this._deviceRoomRotationQuaternion.z *= -1;
  95974. this._deviceRoomRotationQuaternion.w *= -1;
  95975. }
  95976. if (this.webVROptions.trackPosition && this.rawPose.position) {
  95977. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  95978. if (this.getScene().useRightHandedSystem) {
  95979. this._deviceRoomPosition.z *= -1;
  95980. }
  95981. }
  95982. this._poseSet = true;
  95983. }
  95984. };
  95985. /**
  95986. * WebVR's attach control will start broadcasting frames to the device.
  95987. * Note that in certain browsers (chrome for example) this function must be called
  95988. * within a user-interaction callback. Example:
  95989. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  95990. *
  95991. * @param element html element to attach the vrDevice to
  95992. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  95993. */
  95994. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  95995. _super.prototype.attachControl.call(this, element, noPreventDefault);
  95996. this._attached = true;
  95997. this._htmlElementAttached = element;
  95998. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  95999. if (this._vrDevice) {
  96000. this.getEngine().enableVR();
  96001. }
  96002. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  96003. };
  96004. /**
  96005. * Detaches the camera from the html element and disables VR
  96006. *
  96007. * @param element html element to detach from
  96008. */
  96009. WebVRFreeCamera.prototype.detachControl = function (element) {
  96010. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  96011. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  96012. _super.prototype.detachControl.call(this, element);
  96013. this._attached = false;
  96014. this.getEngine().disableVR();
  96015. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  96016. };
  96017. /**
  96018. * @returns the name of this class
  96019. */
  96020. WebVRFreeCamera.prototype.getClassName = function () {
  96021. return "WebVRFreeCamera";
  96022. };
  96023. /**
  96024. * Calls resetPose on the vrDisplay
  96025. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  96026. */
  96027. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  96028. //uses the vrDisplay's "resetPose()".
  96029. //pitch and roll won't be affected.
  96030. this._vrDevice.resetPose();
  96031. };
  96032. /**
  96033. * @hidden
  96034. * Updates the rig cameras (left and right eye)
  96035. */
  96036. WebVRFreeCamera.prototype._updateRigCameras = function () {
  96037. var camLeft = this._rigCameras[0];
  96038. var camRight = this._rigCameras[1];
  96039. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  96040. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  96041. camLeft.position.copyFrom(this._deviceRoomPosition);
  96042. camRight.position.copyFrom(this._deviceRoomPosition);
  96043. };
  96044. // Remove translation from 6dof headset if trackposition is set to false
  96045. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  96046. if (isViewMatrix === void 0) { isViewMatrix = false; }
  96047. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  96048. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  96049. if (!isViewMatrix) {
  96050. this._tmpMatrix.invert();
  96051. }
  96052. this._tmpMatrix.multiplyToRef(matrix, matrix);
  96053. }
  96054. };
  96055. /**
  96056. * @hidden
  96057. * Updates the cached values of the camera
  96058. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  96059. */
  96060. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  96061. var _this = this;
  96062. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  96063. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  96064. if (!this.updateCacheCalled) {
  96065. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  96066. this.updateCacheCalled = true;
  96067. this.update();
  96068. }
  96069. // Set working vector to the device position in room space rotated by the new rotation
  96070. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  96071. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  96072. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  96073. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  96074. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  96075. // Add translation from anchor position
  96076. this._deviceToWorld.getTranslationToRef(this._workingVector);
  96077. this._workingVector.addInPlace(this.position);
  96078. this._workingVector.subtractInPlace(this._cache.position);
  96079. this._deviceToWorld.setTranslation(this._workingVector);
  96080. // Set an inverted matrix to be used when updating the camera
  96081. this._deviceToWorld.invertToRef(this._worldToDevice);
  96082. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  96083. this.controllers.forEach(function (controller) {
  96084. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  96085. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  96086. controller.update();
  96087. });
  96088. }
  96089. if (!ignoreParentClass) {
  96090. _super.prototype._updateCache.call(this);
  96091. }
  96092. this.updateCacheCalled = false;
  96093. };
  96094. /**
  96095. * Updates the current device position and rotation in the babylon world
  96096. */
  96097. WebVRFreeCamera.prototype.update = function () {
  96098. // Get current device position in babylon world
  96099. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  96100. // Get current device rotation in babylon world
  96101. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  96102. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  96103. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  96104. if (this._poseSet) {
  96105. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  96106. }
  96107. _super.prototype.update.call(this);
  96108. };
  96109. /**
  96110. * @hidden
  96111. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  96112. * @returns an identity matrix
  96113. */
  96114. WebVRFreeCamera.prototype._getViewMatrix = function () {
  96115. return BABYLON.Matrix.Identity();
  96116. };
  96117. /**
  96118. * This function is called by the two RIG cameras.
  96119. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  96120. */
  96121. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  96122. var _this = this;
  96123. // Update the parent camera prior to using a child camera to avoid desynchronization
  96124. var parentCamera = this._cameraRigParams["parentCamera"];
  96125. parentCamera._updateCache();
  96126. //WebVR 1.1
  96127. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  96128. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  96129. if (!this.getScene().useRightHandedSystem) {
  96130. [2, 6, 8, 9, 14].forEach(function (num) {
  96131. _this._webvrViewMatrix.m[num] *= -1;
  96132. });
  96133. }
  96134. // update the camera rotation matrix
  96135. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  96136. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  96137. // Computing target and final matrix
  96138. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  96139. // should the view matrix be updated with scale and position offset?
  96140. if (parentCamera.deviceScaleFactor !== 1) {
  96141. this._webvrViewMatrix.invert();
  96142. // scale the position, if set
  96143. if (parentCamera.deviceScaleFactor) {
  96144. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  96145. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  96146. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  96147. }
  96148. this._webvrViewMatrix.invert();
  96149. }
  96150. // Remove translation from 6dof headset if trackposition is set to false
  96151. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  96152. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  96153. // Compute global position
  96154. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  96155. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  96156. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  96157. this._workingMatrix.getTranslationToRef(this._globalPosition);
  96158. this._markSyncedWithParent();
  96159. return this._webvrViewMatrix;
  96160. };
  96161. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  96162. var _this = this;
  96163. var parentCamera = this.parent;
  96164. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  96165. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  96166. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  96167. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  96168. //babylon compatible matrix
  96169. if (!this.getScene().useRightHandedSystem) {
  96170. [8, 9, 10, 11].forEach(function (num) {
  96171. _this._projectionMatrix.m[num] *= -1;
  96172. });
  96173. }
  96174. return this._projectionMatrix;
  96175. };
  96176. /**
  96177. * Initializes the controllers and their meshes
  96178. */
  96179. WebVRFreeCamera.prototype.initControllers = function () {
  96180. var _this = this;
  96181. this.controllers = [];
  96182. var manager = this.getScene().gamepadManager;
  96183. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  96184. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  96185. var webVrController = gamepad;
  96186. if (webVrController.defaultModel) {
  96187. webVrController.defaultModel.setEnabled(false);
  96188. }
  96189. if (webVrController.hand === "right") {
  96190. _this._rightController = null;
  96191. }
  96192. if (webVrController.hand === "left") {
  96193. _this._leftController = null;
  96194. }
  96195. var controllerIndex = _this.controllers.indexOf(webVrController);
  96196. if (controllerIndex !== -1) {
  96197. _this.controllers.splice(controllerIndex, 1);
  96198. }
  96199. }
  96200. });
  96201. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  96202. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  96203. var webVrController_1 = gamepad;
  96204. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  96205. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  96206. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  96207. if (_this.webVROptions.controllerMeshes) {
  96208. if (webVrController_1.defaultModel) {
  96209. webVrController_1.defaultModel.setEnabled(true);
  96210. }
  96211. else {
  96212. // Load the meshes
  96213. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  96214. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  96215. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  96216. if (_this.webVROptions.defaultLightingOnControllers) {
  96217. if (!_this._lightOnControllers) {
  96218. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  96219. }
  96220. var activateLightOnSubMeshes_1 = function (mesh, light) {
  96221. var children = mesh.getChildren();
  96222. if (children.length !== 0) {
  96223. children.forEach(function (mesh) {
  96224. light.includedOnlyMeshes.push(mesh);
  96225. activateLightOnSubMeshes_1(mesh, light);
  96226. });
  96227. }
  96228. };
  96229. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  96230. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  96231. }
  96232. });
  96233. }
  96234. }
  96235. webVrController_1.attachToPoseControlledCamera(_this);
  96236. // since this is async - sanity check. Is the controller already stored?
  96237. if (_this.controllers.indexOf(webVrController_1) === -1) {
  96238. //add to the controllers array
  96239. _this.controllers.push(webVrController_1);
  96240. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  96241. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  96242. // So we're overriding setting left & right manually to be sure
  96243. var firstViveWandDetected = false;
  96244. for (var i = 0; i < _this.controllers.length; i++) {
  96245. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  96246. if (!firstViveWandDetected) {
  96247. firstViveWandDetected = true;
  96248. _this.controllers[i].hand = "left";
  96249. }
  96250. else {
  96251. _this.controllers[i].hand = "right";
  96252. }
  96253. }
  96254. }
  96255. //did we find enough controllers? Great! let the developer know.
  96256. if (_this.controllers.length >= 2) {
  96257. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  96258. }
  96259. }
  96260. }
  96261. });
  96262. };
  96263. return WebVRFreeCamera;
  96264. }(BABYLON.FreeCamera));
  96265. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  96266. })(BABYLON || (BABYLON = {}));
  96267. //# sourceMappingURL=babylon.webVRCamera.js.map
  96268. var BABYLON;
  96269. (function (BABYLON) {
  96270. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  96271. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  96272. });
  96273. // We're mainly based on the logic defined into the FreeCamera code
  96274. /**
  96275. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  96276. * being tilted forward or back and left or right.
  96277. */
  96278. var DeviceOrientationCamera = /** @class */ (function (_super) {
  96279. __extends(DeviceOrientationCamera, _super);
  96280. /**
  96281. * Creates a new device orientation camera
  96282. * @param name The name of the camera
  96283. * @param position The start position camera
  96284. * @param scene The scene the camera belongs to
  96285. */
  96286. function DeviceOrientationCamera(name, position, scene) {
  96287. var _this = _super.call(this, name, position, scene) || this;
  96288. _this._quaternionCache = new BABYLON.Quaternion();
  96289. _this.inputs.addDeviceOrientation();
  96290. return _this;
  96291. }
  96292. /**
  96293. * Gets the current instance class name ("DeviceOrientationCamera").
  96294. * This helps avoiding instanceof at run time.
  96295. * @returns the class name
  96296. */
  96297. DeviceOrientationCamera.prototype.getClassName = function () {
  96298. return "DeviceOrientationCamera";
  96299. };
  96300. /**
  96301. * @hidden
  96302. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  96303. */
  96304. DeviceOrientationCamera.prototype._checkInputs = function () {
  96305. _super.prototype._checkInputs.call(this);
  96306. this._quaternionCache.copyFrom(this.rotationQuaternion);
  96307. if (this._initialQuaternion) {
  96308. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  96309. }
  96310. };
  96311. /**
  96312. * Reset the camera to its default orientation on the specified axis only.
  96313. * @param axis The axis to reset
  96314. */
  96315. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  96316. var _this = this;
  96317. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  96318. //can only work if this camera has a rotation quaternion already.
  96319. if (!this.rotationQuaternion)
  96320. return;
  96321. if (!this._initialQuaternion) {
  96322. this._initialQuaternion = new BABYLON.Quaternion();
  96323. }
  96324. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  96325. ['x', 'y', 'z'].forEach(function (axisName) {
  96326. if (!axis[axisName]) {
  96327. _this._initialQuaternion[axisName] = 0;
  96328. }
  96329. else {
  96330. _this._initialQuaternion[axisName] *= -1;
  96331. }
  96332. });
  96333. this._initialQuaternion.normalize();
  96334. //force rotation update
  96335. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  96336. };
  96337. return DeviceOrientationCamera;
  96338. }(BABYLON.FreeCamera));
  96339. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  96340. })(BABYLON || (BABYLON = {}));
  96341. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  96342. var BABYLON;
  96343. (function (BABYLON) {
  96344. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  96345. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96346. });
  96347. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  96348. __extends(VRDeviceOrientationFreeCamera, _super);
  96349. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  96350. if (compensateDistortion === void 0) { compensateDistortion = true; }
  96351. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  96352. var _this = _super.call(this, name, position, scene) || this;
  96353. vrCameraMetrics.compensateDistortion = compensateDistortion;
  96354. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  96355. return _this;
  96356. }
  96357. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  96358. return "VRDeviceOrientationFreeCamera";
  96359. };
  96360. return VRDeviceOrientationFreeCamera;
  96361. }(BABYLON.DeviceOrientationCamera));
  96362. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  96363. })(BABYLON || (BABYLON = {}));
  96364. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  96365. var BABYLON;
  96366. (function (BABYLON) {
  96367. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  96368. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  96369. });
  96370. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  96371. __extends(VRDeviceOrientationArcRotateCamera, _super);
  96372. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  96373. if (compensateDistortion === void 0) { compensateDistortion = true; }
  96374. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  96375. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  96376. vrCameraMetrics.compensateDistortion = compensateDistortion;
  96377. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  96378. _this.inputs.addVRDeviceOrientation();
  96379. return _this;
  96380. }
  96381. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  96382. return "VRDeviceOrientationArcRotateCamera";
  96383. };
  96384. return VRDeviceOrientationArcRotateCamera;
  96385. }(BABYLON.ArcRotateCamera));
  96386. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  96387. })(BABYLON || (BABYLON = {}));
  96388. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  96389. var BABYLON;
  96390. (function (BABYLON) {
  96391. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  96392. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  96393. });
  96394. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  96395. __extends(VRDeviceOrientationGamepadCamera, _super);
  96396. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  96397. if (compensateDistortion === void 0) { compensateDistortion = true; }
  96398. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  96399. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  96400. _this.inputs.addGamepad();
  96401. return _this;
  96402. }
  96403. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  96404. return "VRDeviceOrientationGamepadCamera";
  96405. };
  96406. return VRDeviceOrientationGamepadCamera;
  96407. }(BABYLON.VRDeviceOrientationFreeCamera));
  96408. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  96409. })(BABYLON || (BABYLON = {}));
  96410. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  96411. var BABYLON;
  96412. (function (BABYLON) {
  96413. var VRExperienceHelperGazer = /** @class */ (function () {
  96414. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  96415. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  96416. this.scene = scene;
  96417. /** @hidden */
  96418. this._pointerDownOnMeshAsked = false;
  96419. /** @hidden */
  96420. this._isActionableMesh = false;
  96421. /** @hidden */
  96422. this._teleportationRequestInitiated = false;
  96423. /** @hidden */
  96424. this._teleportationBackRequestInitiated = false;
  96425. /** @hidden */
  96426. this._rotationRightAsked = false;
  96427. /** @hidden */
  96428. this._rotationLeftAsked = false;
  96429. /** @hidden */
  96430. this._dpadPressed = true;
  96431. /** @hidden */
  96432. this._activePointer = false;
  96433. this._id = VRExperienceHelperGazer._idCounter++;
  96434. // Gaze tracker
  96435. if (!gazeTrackerToClone) {
  96436. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  96437. this._gazeTracker.bakeCurrentTransformIntoVertices();
  96438. this._gazeTracker.isPickable = false;
  96439. this._gazeTracker.isVisible = false;
  96440. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  96441. targetMat.specularColor = BABYLON.Color3.Black();
  96442. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  96443. targetMat.backFaceCulling = false;
  96444. this._gazeTracker.material = targetMat;
  96445. }
  96446. else {
  96447. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  96448. }
  96449. }
  96450. /** @hidden */
  96451. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  96452. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  96453. };
  96454. /** @hidden */
  96455. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  96456. this._pointerDownOnMeshAsked = true;
  96457. if (this._currentHit) {
  96458. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  96459. }
  96460. };
  96461. /** @hidden */
  96462. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  96463. if (this._currentHit) {
  96464. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  96465. }
  96466. this._pointerDownOnMeshAsked = false;
  96467. };
  96468. /** @hidden */
  96469. VRExperienceHelperGazer.prototype._activatePointer = function () {
  96470. this._activePointer = true;
  96471. };
  96472. /** @hidden */
  96473. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  96474. this._activePointer = false;
  96475. };
  96476. /** @hidden */
  96477. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  96478. if (distance === void 0) { distance = 100; }
  96479. };
  96480. VRExperienceHelperGazer.prototype.dispose = function () {
  96481. this._interactionsEnabled = false;
  96482. this._teleportationEnabled = false;
  96483. if (this._gazeTracker) {
  96484. this._gazeTracker.dispose();
  96485. }
  96486. };
  96487. VRExperienceHelperGazer._idCounter = 0;
  96488. return VRExperienceHelperGazer;
  96489. }());
  96490. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  96491. __extends(VRExperienceHelperControllerGazer, _super);
  96492. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  96493. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  96494. _this.webVRController = webVRController;
  96495. // Laser pointer
  96496. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  96497. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  96498. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  96499. laserPointerMaterial.alpha = 0.6;
  96500. _this._laserPointer.material = laserPointerMaterial;
  96501. _this._laserPointer.rotation.x = Math.PI / 2;
  96502. _this._laserPointer.position.z = -0.5;
  96503. _this._laserPointer.isVisible = false;
  96504. _this._laserPointer.isPickable = false;
  96505. if (!webVRController.mesh) {
  96506. // Create an empty mesh that is used prior to loading the high quality model
  96507. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  96508. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  96509. preloadPointerPose.rotation.x = -0.7;
  96510. preloadMesh.addChild(preloadPointerPose);
  96511. webVRController.attachToMesh(preloadMesh);
  96512. }
  96513. _this._setLaserPointerParent(webVRController.mesh);
  96514. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  96515. _this._setLaserPointerParent(mesh);
  96516. });
  96517. return _this;
  96518. }
  96519. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  96520. return this.webVRController.getForwardRay(length);
  96521. };
  96522. /** @hidden */
  96523. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  96524. _super.prototype._activatePointer.call(this);
  96525. this._laserPointer.isVisible = true;
  96526. };
  96527. /** @hidden */
  96528. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  96529. _super.prototype._deactivatePointer.call(this);
  96530. this._laserPointer.isVisible = false;
  96531. };
  96532. /** @hidden */
  96533. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  96534. this._laserPointer.material.emissiveColor = color;
  96535. };
  96536. /** @hidden */
  96537. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  96538. var makeNotPick = function (root) {
  96539. root.isPickable = false;
  96540. root.getChildMeshes().forEach(function (c) {
  96541. makeNotPick(c);
  96542. });
  96543. };
  96544. makeNotPick(mesh);
  96545. var childMeshes = mesh.getChildMeshes();
  96546. this.webVRController._pointingPoseNode = null;
  96547. for (var i = 0; i < childMeshes.length; i++) {
  96548. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  96549. mesh = childMeshes[i];
  96550. this.webVRController._pointingPoseNode = mesh;
  96551. break;
  96552. }
  96553. }
  96554. this._laserPointer.parent = mesh;
  96555. };
  96556. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  96557. if (distance === void 0) { distance = 100; }
  96558. this._laserPointer.scaling.y = distance;
  96559. this._laserPointer.position.z = -distance / 2;
  96560. };
  96561. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  96562. _super.prototype.dispose.call(this);
  96563. this._laserPointer.dispose();
  96564. if (this._meshAttachedObserver) {
  96565. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  96566. }
  96567. };
  96568. return VRExperienceHelperControllerGazer;
  96569. }(VRExperienceHelperGazer));
  96570. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  96571. __extends(VRExperienceHelperCameraGazer, _super);
  96572. function VRExperienceHelperCameraGazer(getCamera, scene) {
  96573. var _this = _super.call(this, scene) || this;
  96574. _this.getCamera = getCamera;
  96575. return _this;
  96576. }
  96577. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  96578. var camera = this.getCamera();
  96579. if (camera) {
  96580. return camera.getForwardRay(length);
  96581. }
  96582. else {
  96583. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  96584. }
  96585. };
  96586. return VRExperienceHelperCameraGazer;
  96587. }(VRExperienceHelperGazer));
  96588. /**
  96589. * Helps to quickly add VR support to an existing scene.
  96590. * See http://doc.babylonjs.com/how_to/webvr_helper
  96591. */
  96592. var VRExperienceHelper = /** @class */ (function () {
  96593. /**
  96594. * Instantiates a VRExperienceHelper.
  96595. * Helps to quickly add VR support to an existing scene.
  96596. * @param scene The scene the VRExperienceHelper belongs to.
  96597. * @param webVROptions Options to modify the vr experience helper's behavior.
  96598. */
  96599. function VRExperienceHelper(scene,
  96600. /** Options to modify the vr experience helper's behavior. */
  96601. webVROptions) {
  96602. if (webVROptions === void 0) { webVROptions = {}; }
  96603. var _this = this;
  96604. this.webVROptions = webVROptions;
  96605. // Can the system support WebVR, even if a headset isn't plugged in?
  96606. this._webVRsupported = false;
  96607. // If WebVR is supported, is a headset plugged in and are we ready to present?
  96608. this._webVRready = false;
  96609. // Are we waiting for the requestPresent callback to complete?
  96610. this._webVRrequesting = false;
  96611. // Are we presenting to the headset right now? (this is the vrDevice state)
  96612. this._webVRpresenting = false;
  96613. // Are we presenting in the fullscreen fallback?
  96614. this._fullscreenVRpresenting = false;
  96615. /**
  96616. * Observable raised when entering VR.
  96617. */
  96618. this.onEnteringVRObservable = new BABYLON.Observable();
  96619. /**
  96620. * Observable raised when exiting VR.
  96621. */
  96622. this.onExitingVRObservable = new BABYLON.Observable();
  96623. /**
  96624. * Observable raised when controller mesh is loaded.
  96625. */
  96626. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  96627. this._useCustomVRButton = false;
  96628. this._teleportationRequested = false;
  96629. this._teleportActive = false;
  96630. this._floorMeshesCollection = [];
  96631. this._rotationAllowed = true;
  96632. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  96633. this._isDefaultTeleportationTarget = true;
  96634. this._teleportationFillColor = "#444444";
  96635. this._teleportationBorderColor = "#FFFFFF";
  96636. this._rotationAngle = 0;
  96637. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  96638. this._padSensibilityUp = 0.65;
  96639. this._padSensibilityDown = 0.35;
  96640. this._leftController = null;
  96641. this._rightController = null;
  96642. /**
  96643. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  96644. */
  96645. this.onNewMeshSelected = new BABYLON.Observable();
  96646. /**
  96647. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  96648. */
  96649. this.onNewMeshPicked = new BABYLON.Observable();
  96650. /**
  96651. * Observable raised before camera teleportation
  96652. */
  96653. this.onBeforeCameraTeleport = new BABYLON.Observable();
  96654. /**
  96655. * Observable raised after camera teleportation
  96656. */
  96657. this.onAfterCameraTeleport = new BABYLON.Observable();
  96658. /**
  96659. * Observable raised when current selected mesh gets unselected
  96660. */
  96661. this.onSelectedMeshUnselected = new BABYLON.Observable();
  96662. /**
  96663. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  96664. */
  96665. this.teleportationEnabled = true;
  96666. this._teleportationInitialized = false;
  96667. this._interactionsEnabled = false;
  96668. this._interactionsRequested = false;
  96669. this._displayGaze = true;
  96670. this._displayLaserPointer = true;
  96671. /**
  96672. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  96673. */
  96674. this.updateGazeTrackerScale = true;
  96675. this._onResize = function () {
  96676. _this.moveButtonToBottomRight();
  96677. if (_this._fullscreenVRpresenting && _this._webVRready) {
  96678. _this.exitVR();
  96679. }
  96680. };
  96681. this._onFullscreenChange = function () {
  96682. if (document.fullscreen !== undefined) {
  96683. _this._fullscreenVRpresenting = document.fullscreen;
  96684. }
  96685. else if (document.mozFullScreen !== undefined) {
  96686. _this._fullscreenVRpresenting = document.mozFullScreen;
  96687. }
  96688. else if (document.webkitIsFullScreen !== undefined) {
  96689. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  96690. }
  96691. else if (document.msIsFullScreen !== undefined) {
  96692. _this._fullscreenVRpresenting = document.msIsFullScreen;
  96693. }
  96694. else if (document.msFullscreenElement !== undefined) {
  96695. _this._fullscreenVRpresenting = document.msFullscreenElement;
  96696. }
  96697. if (!_this._fullscreenVRpresenting && _this._canvas) {
  96698. _this.exitVR();
  96699. if (!_this._useCustomVRButton) {
  96700. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  96701. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  96702. }
  96703. }
  96704. };
  96705. this.beforeRender = function () {
  96706. if (_this._leftController && _this._leftController._activePointer) {
  96707. _this._castRayAndSelectObject(_this._leftController);
  96708. }
  96709. if (_this._rightController && _this._rightController._activePointer) {
  96710. _this._castRayAndSelectObject(_this._rightController);
  96711. }
  96712. if (_this._noControllerIsActive) {
  96713. _this._castRayAndSelectObject(_this._cameraGazer);
  96714. }
  96715. else {
  96716. _this._cameraGazer._gazeTracker.isVisible = false;
  96717. }
  96718. };
  96719. this._onNewGamepadConnected = function (gamepad) {
  96720. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  96721. if (gamepad.leftStick) {
  96722. gamepad.onleftstickchanged(function (stickValues) {
  96723. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  96724. // Listening to classic/xbox gamepad only if no VR controller is active
  96725. if ((!_this._leftController && !_this._rightController) ||
  96726. ((_this._leftController && !_this._leftController._activePointer) &&
  96727. (_this._rightController && !_this._rightController._activePointer))) {
  96728. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  96729. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  96730. }
  96731. }
  96732. });
  96733. }
  96734. if (gamepad.rightStick) {
  96735. gamepad.onrightstickchanged(function (stickValues) {
  96736. if (_this._teleportationInitialized) {
  96737. _this._checkRotate(stickValues, _this._cameraGazer);
  96738. }
  96739. });
  96740. }
  96741. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  96742. gamepad.onbuttondown(function (buttonPressed) {
  96743. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  96744. _this._cameraGazer._selectionPointerDown();
  96745. }
  96746. });
  96747. gamepad.onbuttonup(function (buttonPressed) {
  96748. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  96749. _this._cameraGazer._selectionPointerUp();
  96750. }
  96751. });
  96752. }
  96753. }
  96754. else {
  96755. var webVRController = gamepad;
  96756. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  96757. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  96758. _this._rightController = controller;
  96759. }
  96760. else {
  96761. _this._leftController = controller;
  96762. }
  96763. _this._tryEnableInteractionOnController(controller);
  96764. }
  96765. };
  96766. // 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
  96767. this._tryEnableInteractionOnController = function (controller) {
  96768. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  96769. _this._enableInteractionOnController(controller);
  96770. }
  96771. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  96772. _this._enableTeleportationOnController(controller);
  96773. }
  96774. };
  96775. this._onNewGamepadDisconnected = function (gamepad) {
  96776. if (gamepad instanceof BABYLON.WebVRController) {
  96777. if (gamepad.hand === "left" && _this._leftController != null) {
  96778. _this._leftController.dispose();
  96779. _this._leftController = null;
  96780. }
  96781. if (gamepad.hand === "right" && _this._rightController != null) {
  96782. _this._rightController.dispose();
  96783. _this._rightController = null;
  96784. }
  96785. }
  96786. };
  96787. this._workingVector = BABYLON.Vector3.Zero();
  96788. this._workingQuaternion = BABYLON.Quaternion.Identity();
  96789. this._workingMatrix = BABYLON.Matrix.Identity();
  96790. this._scene = scene;
  96791. this._canvas = scene.getEngine().getRenderingCanvas();
  96792. // Parse options
  96793. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  96794. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  96795. }
  96796. if (webVROptions.createDeviceOrientationCamera === undefined) {
  96797. webVROptions.createDeviceOrientationCamera = true;
  96798. }
  96799. if (webVROptions.laserToggle === undefined) {
  96800. webVROptions.laserToggle = true;
  96801. }
  96802. if (webVROptions.defaultHeight === undefined) {
  96803. webVROptions.defaultHeight = 1.7;
  96804. }
  96805. if (webVROptions.useCustomVRButton) {
  96806. this._useCustomVRButton = true;
  96807. if (webVROptions.customVRButton) {
  96808. this._btnVR = webVROptions.customVRButton;
  96809. }
  96810. }
  96811. if (webVROptions.rayLength) {
  96812. this._rayLength = webVROptions.rayLength;
  96813. }
  96814. this._defaultHeight = webVROptions.defaultHeight;
  96815. if (webVROptions.positionScale) {
  96816. this._rayLength *= webVROptions.positionScale;
  96817. this._defaultHeight *= webVROptions.positionScale;
  96818. }
  96819. this._hasEnteredVR = false;
  96820. // Set position
  96821. if (this._scene.activeCamera) {
  96822. this._position = this._scene.activeCamera.position.clone();
  96823. }
  96824. else {
  96825. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  96826. }
  96827. // Set non-vr camera
  96828. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  96829. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  96830. // Copy data from existing camera
  96831. if (this._scene.activeCamera) {
  96832. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  96833. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  96834. // Set rotation from previous camera
  96835. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  96836. var targetCamera = this._scene.activeCamera;
  96837. if (targetCamera.rotationQuaternion) {
  96838. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  96839. }
  96840. else {
  96841. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  96842. }
  96843. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  96844. }
  96845. }
  96846. this._scene.activeCamera = this._deviceOrientationCamera;
  96847. if (this._canvas) {
  96848. this._scene.activeCamera.attachControl(this._canvas);
  96849. }
  96850. }
  96851. else {
  96852. this._existingCamera = this._scene.activeCamera;
  96853. }
  96854. // Create VR cameras
  96855. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  96856. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  96857. }
  96858. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  96859. this._webVRCamera.useStandingMatrix();
  96860. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  96861. // Create default button
  96862. if (!this._useCustomVRButton) {
  96863. this._btnVR = document.createElement("BUTTON");
  96864. this._btnVR.className = "babylonVRicon";
  96865. this._btnVR.id = "babylonVRiconbtn";
  96866. this._btnVR.title = "Click to switch to VR";
  96867. 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) }";
  96868. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  96869. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  96870. // css += ".babylonVRicon.vrdisplaysupported { }";
  96871. // css += ".babylonVRicon.vrdisplayready { }";
  96872. // css += ".babylonVRicon.vrdisplayrequesting { }";
  96873. var style = document.createElement('style');
  96874. style.appendChild(document.createTextNode(css));
  96875. document.getElementsByTagName('head')[0].appendChild(style);
  96876. this.moveButtonToBottomRight();
  96877. }
  96878. // VR button click event
  96879. if (this._btnVR) {
  96880. this._btnVR.addEventListener("click", function () {
  96881. if (!_this.isInVRMode) {
  96882. _this.enterVR();
  96883. }
  96884. else {
  96885. _this.exitVR();
  96886. }
  96887. });
  96888. }
  96889. // Window events
  96890. window.addEventListener("resize", this._onResize);
  96891. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  96892. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  96893. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  96894. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  96895. document.onmsfullscreenchange = this._onFullscreenChange;
  96896. // Display vr button when headset is connected
  96897. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  96898. this.displayVRButton();
  96899. }
  96900. else {
  96901. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  96902. if (e.vrDisplay) {
  96903. _this.displayVRButton();
  96904. }
  96905. });
  96906. }
  96907. // Exiting VR mode using 'ESC' key on desktop
  96908. this._onKeyDown = function (event) {
  96909. if (event.keyCode === 27 && _this.isInVRMode) {
  96910. _this.exitVR();
  96911. }
  96912. };
  96913. document.addEventListener("keydown", this._onKeyDown);
  96914. // Exiting VR mode double tapping the touch screen
  96915. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  96916. if (_this.isInVRMode) {
  96917. _this.exitVR();
  96918. if (_this._fullscreenVRpresenting) {
  96919. _this._scene.getEngine().switchFullscreen(true);
  96920. }
  96921. }
  96922. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  96923. // Listen for WebVR display changes
  96924. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  96925. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  96926. this._onVRRequestPresentStart = function () {
  96927. _this._webVRrequesting = true;
  96928. _this.updateButtonVisibility();
  96929. };
  96930. this._onVRRequestPresentComplete = function (success) {
  96931. _this._webVRrequesting = false;
  96932. _this.updateButtonVisibility();
  96933. };
  96934. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  96935. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  96936. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  96937. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  96938. scene.onDisposeObservable.add(function () {
  96939. _this.dispose();
  96940. });
  96941. // Gamepad connection events
  96942. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  96943. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  96944. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  96945. this.updateButtonVisibility();
  96946. //create easing functions
  96947. this._circleEase = new BABYLON.CircleEase();
  96948. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  96949. if (this.webVROptions.floorMeshes) {
  96950. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  96951. }
  96952. }
  96953. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  96954. /** Return this.onEnteringVRObservable
  96955. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  96956. */
  96957. get: function () {
  96958. return this.onEnteringVRObservable;
  96959. },
  96960. enumerable: true,
  96961. configurable: true
  96962. });
  96963. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  96964. /** Return this.onExitingVRObservable
  96965. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  96966. */
  96967. get: function () {
  96968. return this.onExitingVRObservable;
  96969. },
  96970. enumerable: true,
  96971. configurable: true
  96972. });
  96973. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  96974. /** Return this.onControllerMeshLoadedObservable
  96975. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  96976. */
  96977. get: function () {
  96978. return this.onControllerMeshLoadedObservable;
  96979. },
  96980. enumerable: true,
  96981. configurable: true
  96982. });
  96983. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  96984. /**
  96985. * The mesh used to display where the user is going to teleport.
  96986. */
  96987. get: function () {
  96988. return this._teleportationTarget;
  96989. },
  96990. /**
  96991. * Sets the mesh to be used to display where the user is going to teleport.
  96992. */
  96993. set: function (value) {
  96994. if (value) {
  96995. value.name = "teleportationTarget";
  96996. this._isDefaultTeleportationTarget = false;
  96997. this._teleportationTarget = value;
  96998. }
  96999. },
  97000. enumerable: true,
  97001. configurable: true
  97002. });
  97003. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  97004. /**
  97005. * 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
  97006. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  97007. * See http://doc.babylonjs.com/resources/baking_transformations
  97008. */
  97009. get: function () {
  97010. return this._cameraGazer._gazeTracker;
  97011. },
  97012. set: function (value) {
  97013. if (value) {
  97014. // Dispose of existing meshes
  97015. if (this._cameraGazer._gazeTracker) {
  97016. this._cameraGazer._gazeTracker.dispose();
  97017. }
  97018. if (this._leftController && this._leftController._gazeTracker) {
  97019. this._leftController._gazeTracker.dispose();
  97020. }
  97021. if (this._rightController && this._rightController._gazeTracker) {
  97022. this._rightController._gazeTracker.dispose();
  97023. }
  97024. // Set and create gaze trackers on head and controllers
  97025. this._cameraGazer._gazeTracker = value;
  97026. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  97027. this._cameraGazer._gazeTracker.isPickable = false;
  97028. this._cameraGazer._gazeTracker.isVisible = false;
  97029. this._cameraGazer._gazeTracker.name = "gazeTracker";
  97030. if (this._leftController) {
  97031. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  97032. }
  97033. if (this._rightController) {
  97034. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  97035. }
  97036. }
  97037. },
  97038. enumerable: true,
  97039. configurable: true
  97040. });
  97041. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  97042. /**
  97043. * The gaze tracking mesh corresponding to the left controller
  97044. */
  97045. get: function () {
  97046. if (this._leftController) {
  97047. return this._leftController._gazeTracker;
  97048. }
  97049. return null;
  97050. },
  97051. enumerable: true,
  97052. configurable: true
  97053. });
  97054. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  97055. /**
  97056. * The gaze tracking mesh corresponding to the right controller
  97057. */
  97058. get: function () {
  97059. if (this._rightController) {
  97060. return this._rightController._gazeTracker;
  97061. }
  97062. return null;
  97063. },
  97064. enumerable: true,
  97065. configurable: true
  97066. });
  97067. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  97068. /**
  97069. * If the ray of the gaze should be displayed.
  97070. */
  97071. get: function () {
  97072. return this._displayGaze;
  97073. },
  97074. /**
  97075. * Sets if the ray of the gaze should be displayed.
  97076. */
  97077. set: function (value) {
  97078. this._displayGaze = value;
  97079. if (!value) {
  97080. this._cameraGazer._gazeTracker.isVisible = false;
  97081. if (this._leftController) {
  97082. this._leftController._gazeTracker.isVisible = false;
  97083. }
  97084. if (this._rightController) {
  97085. this._rightController._gazeTracker.isVisible = false;
  97086. }
  97087. }
  97088. },
  97089. enumerable: true,
  97090. configurable: true
  97091. });
  97092. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  97093. /**
  97094. * If the ray of the LaserPointer should be displayed.
  97095. */
  97096. get: function () {
  97097. return this._displayLaserPointer;
  97098. },
  97099. /**
  97100. * Sets if the ray of the LaserPointer should be displayed.
  97101. */
  97102. set: function (value) {
  97103. this._displayLaserPointer = value;
  97104. if (!value) {
  97105. if (this._rightController) {
  97106. this._rightController._deactivatePointer();
  97107. this._rightController._gazeTracker.isVisible = false;
  97108. }
  97109. if (this._leftController) {
  97110. this._leftController._deactivatePointer();
  97111. this._leftController._gazeTracker.isVisible = false;
  97112. }
  97113. }
  97114. else {
  97115. if (this._rightController) {
  97116. this._rightController._activatePointer();
  97117. }
  97118. if (this._leftController) {
  97119. this._leftController._activatePointer();
  97120. }
  97121. }
  97122. },
  97123. enumerable: true,
  97124. configurable: true
  97125. });
  97126. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  97127. /**
  97128. * The deviceOrientationCamera used as the camera when not in VR.
  97129. */
  97130. get: function () {
  97131. return this._deviceOrientationCamera;
  97132. },
  97133. enumerable: true,
  97134. configurable: true
  97135. });
  97136. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  97137. /**
  97138. * Based on the current WebVR support, returns the current VR camera used.
  97139. */
  97140. get: function () {
  97141. if (this._webVRready) {
  97142. return this._webVRCamera;
  97143. }
  97144. else {
  97145. return this._scene.activeCamera;
  97146. }
  97147. },
  97148. enumerable: true,
  97149. configurable: true
  97150. });
  97151. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  97152. /**
  97153. * The webVRCamera which is used when in VR.
  97154. */
  97155. get: function () {
  97156. return this._webVRCamera;
  97157. },
  97158. enumerable: true,
  97159. configurable: true
  97160. });
  97161. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  97162. /**
  97163. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  97164. */
  97165. get: function () {
  97166. return this._vrDeviceOrientationCamera;
  97167. },
  97168. enumerable: true,
  97169. configurable: true
  97170. });
  97171. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  97172. get: function () {
  97173. var result = this._cameraGazer._teleportationRequestInitiated
  97174. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  97175. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  97176. return result;
  97177. },
  97178. enumerable: true,
  97179. configurable: true
  97180. });
  97181. // Raised when one of the controller has loaded successfully its associated default mesh
  97182. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  97183. if (this._leftController && this._leftController.webVRController == webVRController) {
  97184. if (webVRController.mesh) {
  97185. this._leftController._setLaserPointerParent(webVRController.mesh);
  97186. }
  97187. }
  97188. if (this._rightController && this._rightController.webVRController == webVRController) {
  97189. if (webVRController.mesh) {
  97190. this._rightController._setLaserPointerParent(webVRController.mesh);
  97191. }
  97192. }
  97193. try {
  97194. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  97195. }
  97196. catch (err) {
  97197. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  97198. }
  97199. };
  97200. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  97201. /**
  97202. * Gets a value indicating if we are currently in VR mode.
  97203. */
  97204. get: function () {
  97205. return this._webVRpresenting || this._fullscreenVRpresenting;
  97206. },
  97207. enumerable: true,
  97208. configurable: true
  97209. });
  97210. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  97211. var vrDisplay = this._scene.getEngine().getVRDevice();
  97212. if (vrDisplay) {
  97213. var wasPresenting = this._webVRpresenting;
  97214. this._webVRpresenting = vrDisplay.isPresenting;
  97215. if (wasPresenting && !this._webVRpresenting)
  97216. this.exitVR();
  97217. }
  97218. else {
  97219. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  97220. }
  97221. this.updateButtonVisibility();
  97222. };
  97223. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  97224. this._webVRsupported = eventArgs.vrSupported;
  97225. this._webVRready = !!eventArgs.vrDisplay;
  97226. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  97227. this.updateButtonVisibility();
  97228. };
  97229. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  97230. if (this._canvas && !this._useCustomVRButton) {
  97231. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  97232. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  97233. }
  97234. };
  97235. VRExperienceHelper.prototype.displayVRButton = function () {
  97236. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  97237. document.body.appendChild(this._btnVR);
  97238. this._btnVRDisplayed = true;
  97239. }
  97240. };
  97241. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  97242. if (!this._btnVR || this._useCustomVRButton) {
  97243. return;
  97244. }
  97245. this._btnVR.className = "babylonVRicon";
  97246. if (this.isInVRMode) {
  97247. this._btnVR.className += " vrdisplaypresenting";
  97248. }
  97249. else {
  97250. if (this._webVRready)
  97251. this._btnVR.className += " vrdisplayready";
  97252. if (this._webVRsupported)
  97253. this._btnVR.className += " vrdisplaysupported";
  97254. if (this._webVRrequesting)
  97255. this._btnVR.className += " vrdisplayrequesting";
  97256. }
  97257. };
  97258. /**
  97259. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  97260. * Otherwise, will use the fullscreen API.
  97261. */
  97262. VRExperienceHelper.prototype.enterVR = function () {
  97263. if (this.onEnteringVRObservable) {
  97264. try {
  97265. this.onEnteringVRObservable.notifyObservers(this);
  97266. }
  97267. catch (err) {
  97268. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  97269. }
  97270. }
  97271. if (this._scene.activeCamera) {
  97272. this._position = this._scene.activeCamera.position.clone();
  97273. // make sure that we return to the last active camera
  97274. this._existingCamera = this._scene.activeCamera;
  97275. }
  97276. if (this._webVRrequesting)
  97277. return;
  97278. // If WebVR is supported and a headset is connected
  97279. if (this._webVRready) {
  97280. if (!this._webVRpresenting) {
  97281. this._webVRCamera.position = this._position;
  97282. this._scene.activeCamera = this._webVRCamera;
  97283. }
  97284. }
  97285. else if (this._vrDeviceOrientationCamera) {
  97286. this._vrDeviceOrientationCamera.position = this._position;
  97287. if (this._scene.activeCamera) {
  97288. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  97289. }
  97290. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  97291. this._scene.getEngine().switchFullscreen(true);
  97292. this.updateButtonVisibility();
  97293. }
  97294. if (this._scene.activeCamera && this._canvas) {
  97295. this._scene.activeCamera.attachControl(this._canvas);
  97296. }
  97297. if (this._interactionsEnabled) {
  97298. this._scene.registerBeforeRender(this.beforeRender);
  97299. }
  97300. this._hasEnteredVR = true;
  97301. };
  97302. /**
  97303. * Attempt to exit VR, or fullscreen.
  97304. */
  97305. VRExperienceHelper.prototype.exitVR = function () {
  97306. if (this._hasEnteredVR) {
  97307. if (this.onExitingVRObservable) {
  97308. try {
  97309. this.onExitingVRObservable.notifyObservers(this);
  97310. }
  97311. catch (err) {
  97312. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  97313. }
  97314. }
  97315. if (this._webVRpresenting) {
  97316. this._scene.getEngine().disableVR();
  97317. }
  97318. if (this._scene.activeCamera) {
  97319. this._position = this._scene.activeCamera.position.clone();
  97320. }
  97321. if (this._deviceOrientationCamera) {
  97322. this._deviceOrientationCamera.position = this._position;
  97323. this._scene.activeCamera = this._deviceOrientationCamera;
  97324. if (this._canvas) {
  97325. this._scene.activeCamera.attachControl(this._canvas);
  97326. }
  97327. }
  97328. else if (this._existingCamera) {
  97329. this._existingCamera.position = this._position;
  97330. this._scene.activeCamera = this._existingCamera;
  97331. }
  97332. this.updateButtonVisibility();
  97333. if (this._interactionsEnabled) {
  97334. this._scene.unregisterBeforeRender(this.beforeRender);
  97335. this._cameraGazer._gazeTracker.isVisible = false;
  97336. if (this._leftController) {
  97337. this._leftController._gazeTracker.isVisible = false;
  97338. }
  97339. if (this._rightController) {
  97340. this._rightController._gazeTracker.isVisible = false;
  97341. }
  97342. }
  97343. // resize to update width and height when exiting vr exits fullscreen
  97344. this._scene.getEngine().resize();
  97345. this._hasEnteredVR = false;
  97346. }
  97347. };
  97348. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  97349. /**
  97350. * The position of the vr experience helper.
  97351. */
  97352. get: function () {
  97353. return this._position;
  97354. },
  97355. /**
  97356. * Sets the position of the vr experience helper.
  97357. */
  97358. set: function (value) {
  97359. this._position = value;
  97360. if (this._scene.activeCamera) {
  97361. this._scene.activeCamera.position = value;
  97362. }
  97363. },
  97364. enumerable: true,
  97365. configurable: true
  97366. });
  97367. /**
  97368. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  97369. */
  97370. VRExperienceHelper.prototype.enableInteractions = function () {
  97371. var _this = this;
  97372. if (!this._interactionsEnabled) {
  97373. this._interactionsRequested = true;
  97374. if (this._leftController) {
  97375. this._enableInteractionOnController(this._leftController);
  97376. }
  97377. if (this._rightController) {
  97378. this._enableInteractionOnController(this._rightController);
  97379. }
  97380. this.raySelectionPredicate = function (mesh) {
  97381. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  97382. };
  97383. this.meshSelectionPredicate = function (mesh) {
  97384. return true;
  97385. };
  97386. this._raySelectionPredicate = function (mesh) {
  97387. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  97388. && mesh.name.indexOf("teleportationTarget") === -1
  97389. && mesh.name.indexOf("torusTeleportation") === -1)) {
  97390. return _this.raySelectionPredicate(mesh);
  97391. }
  97392. return false;
  97393. };
  97394. this._interactionsEnabled = true;
  97395. }
  97396. };
  97397. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  97398. get: function () {
  97399. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  97400. },
  97401. enumerable: true,
  97402. configurable: true
  97403. });
  97404. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  97405. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  97406. if (this._floorMeshesCollection[i].id === mesh.id) {
  97407. return true;
  97408. }
  97409. }
  97410. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  97411. return true;
  97412. }
  97413. return false;
  97414. };
  97415. /**
  97416. * Adds a floor mesh to be used for teleportation.
  97417. * @param floorMesh the mesh to be used for teleportation.
  97418. */
  97419. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  97420. if (!this._floorMeshesCollection) {
  97421. return;
  97422. }
  97423. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  97424. return;
  97425. }
  97426. this._floorMeshesCollection.push(floorMesh);
  97427. };
  97428. /**
  97429. * Removes a floor mesh from being used for teleportation.
  97430. * @param floorMesh the mesh to be removed.
  97431. */
  97432. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  97433. if (!this._floorMeshesCollection) {
  97434. return;
  97435. }
  97436. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  97437. if (meshIndex !== -1) {
  97438. this._floorMeshesCollection.splice(meshIndex, 1);
  97439. }
  97440. };
  97441. /**
  97442. * Enables interactions and teleportation using the VR controllers and gaze.
  97443. * @param vrTeleportationOptions options to modify teleportation behavior.
  97444. */
  97445. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  97446. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  97447. if (!this._teleportationInitialized) {
  97448. this._teleportationRequested = true;
  97449. this.enableInteractions();
  97450. if (vrTeleportationOptions.floorMeshName) {
  97451. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  97452. }
  97453. if (vrTeleportationOptions.floorMeshes) {
  97454. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  97455. }
  97456. if (this._leftController != null) {
  97457. this._enableTeleportationOnController(this._leftController);
  97458. }
  97459. if (this._rightController != null) {
  97460. this._enableTeleportationOnController(this._rightController);
  97461. }
  97462. // Creates an image processing post process for the vignette not relying
  97463. // on the main scene configuration for image processing to reduce setup and spaces
  97464. // (gamma/linear) conflicts.
  97465. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  97466. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  97467. imageProcessingConfiguration.vignetteEnabled = true;
  97468. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  97469. this._webVRCamera.detachPostProcess(this._postProcessMove);
  97470. this._teleportationInitialized = true;
  97471. if (this._isDefaultTeleportationTarget) {
  97472. this._createTeleportationCircles();
  97473. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  97474. }
  97475. }
  97476. };
  97477. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  97478. var _this = this;
  97479. var controllerMesh = controller.webVRController.mesh;
  97480. if (controllerMesh) {
  97481. controller._interactionsEnabled = true;
  97482. controller._activatePointer();
  97483. if (this.webVROptions.laserToggle) {
  97484. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  97485. // Enabling / disabling laserPointer
  97486. if (_this._displayLaserPointer && stateObject.value === 1) {
  97487. if (controller._activePointer) {
  97488. controller._deactivatePointer();
  97489. }
  97490. else {
  97491. controller._activatePointer();
  97492. }
  97493. if (_this.displayGaze) {
  97494. controller._gazeTracker.isVisible = controller._activePointer;
  97495. }
  97496. }
  97497. });
  97498. }
  97499. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  97500. var gazer = controller;
  97501. if (_this._noControllerIsActive) {
  97502. gazer = _this._cameraGazer;
  97503. }
  97504. if (!gazer._pointerDownOnMeshAsked) {
  97505. if (stateObject.value > _this._padSensibilityUp) {
  97506. gazer._selectionPointerDown();
  97507. }
  97508. }
  97509. else if (stateObject.value < _this._padSensibilityDown) {
  97510. gazer._selectionPointerUp();
  97511. }
  97512. });
  97513. }
  97514. };
  97515. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  97516. // Dont teleport if another gaze already requested teleportation
  97517. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  97518. return;
  97519. }
  97520. if (!gazer._teleportationRequestInitiated) {
  97521. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  97522. gazer._activatePointer();
  97523. gazer._teleportationRequestInitiated = true;
  97524. }
  97525. }
  97526. else {
  97527. // Listening to the proper controller values changes to confirm teleportation
  97528. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  97529. if (this._teleportActive) {
  97530. this.teleportCamera(this._haloCenter);
  97531. }
  97532. gazer._teleportationRequestInitiated = false;
  97533. }
  97534. }
  97535. };
  97536. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  97537. // Only rotate when user is not currently selecting a teleportation location
  97538. if (gazer._teleportationRequestInitiated) {
  97539. return;
  97540. }
  97541. if (!gazer._rotationLeftAsked) {
  97542. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  97543. gazer._rotationLeftAsked = true;
  97544. if (this._rotationAllowed) {
  97545. this._rotateCamera(false);
  97546. }
  97547. }
  97548. }
  97549. else {
  97550. if (stateObject.x > -this._padSensibilityDown) {
  97551. gazer._rotationLeftAsked = false;
  97552. }
  97553. }
  97554. if (!gazer._rotationRightAsked) {
  97555. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  97556. gazer._rotationRightAsked = true;
  97557. if (this._rotationAllowed) {
  97558. this._rotateCamera(true);
  97559. }
  97560. }
  97561. }
  97562. else {
  97563. if (stateObject.x < this._padSensibilityDown) {
  97564. gazer._rotationRightAsked = false;
  97565. }
  97566. }
  97567. };
  97568. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  97569. // Only teleport backwards when user is not currently selecting a teleportation location
  97570. if (gazer._teleportationRequestInitiated) {
  97571. return;
  97572. }
  97573. // Teleport backwards
  97574. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  97575. if (!gazer._teleportationBackRequestInitiated) {
  97576. if (!this.currentVRCamera) {
  97577. return;
  97578. }
  97579. // Get rotation and position of the current camera
  97580. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  97581. var position = this.currentVRCamera.position;
  97582. // If the camera has device position, use that instead
  97583. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  97584. rotation = this.currentVRCamera.deviceRotationQuaternion;
  97585. position = this.currentVRCamera.devicePosition;
  97586. }
  97587. // Get matrix with only the y rotation of the device rotation
  97588. rotation.toEulerAnglesToRef(this._workingVector);
  97589. this._workingVector.z = 0;
  97590. this._workingVector.x = 0;
  97591. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  97592. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  97593. // Rotate backwards ray by device rotation to cast at the ground behind the user
  97594. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  97595. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  97596. var ray = new BABYLON.Ray(position, this._workingVector);
  97597. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  97598. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  97599. this.teleportCamera(hit.pickedPoint);
  97600. }
  97601. gazer._teleportationBackRequestInitiated = true;
  97602. }
  97603. }
  97604. else {
  97605. gazer._teleportationBackRequestInitiated = false;
  97606. }
  97607. };
  97608. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  97609. var _this = this;
  97610. var controllerMesh = controller.webVRController.mesh;
  97611. if (controllerMesh) {
  97612. if (!controller._interactionsEnabled) {
  97613. this._enableInteractionOnController(controller);
  97614. }
  97615. controller._interactionsEnabled = true;
  97616. controller._teleportationEnabled = true;
  97617. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  97618. controller._dpadPressed = false;
  97619. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  97620. controller._dpadPressed = stateObject.pressed;
  97621. if (!controller._dpadPressed) {
  97622. controller._rotationLeftAsked = false;
  97623. controller._rotationRightAsked = false;
  97624. controller._teleportationBackRequestInitiated = false;
  97625. }
  97626. });
  97627. }
  97628. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  97629. if (_this.teleportationEnabled) {
  97630. _this._checkTeleportBackwards(stateObject, controller);
  97631. _this._checkTeleportWithRay(stateObject, controller);
  97632. }
  97633. _this._checkRotate(stateObject, controller);
  97634. });
  97635. }
  97636. };
  97637. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  97638. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  97639. this._teleportationTarget.isPickable = false;
  97640. var length = 512;
  97641. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  97642. dynamicTexture.hasAlpha = true;
  97643. var context = dynamicTexture.getContext();
  97644. var centerX = length / 2;
  97645. var centerY = length / 2;
  97646. var radius = 200;
  97647. context.beginPath();
  97648. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  97649. context.fillStyle = this._teleportationFillColor;
  97650. context.fill();
  97651. context.lineWidth = 10;
  97652. context.strokeStyle = this._teleportationBorderColor;
  97653. context.stroke();
  97654. context.closePath();
  97655. dynamicTexture.update();
  97656. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  97657. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  97658. this._teleportationTarget.material = teleportationCircleMaterial;
  97659. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  97660. torus.isPickable = false;
  97661. torus.parent = this._teleportationTarget;
  97662. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  97663. var keys = [];
  97664. keys.push({
  97665. frame: 0,
  97666. value: 0
  97667. });
  97668. keys.push({
  97669. frame: 30,
  97670. value: 0.4
  97671. });
  97672. keys.push({
  97673. frame: 60,
  97674. value: 0
  97675. });
  97676. animationInnerCircle.setKeys(keys);
  97677. var easingFunction = new BABYLON.SineEase();
  97678. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  97679. animationInnerCircle.setEasingFunction(easingFunction);
  97680. torus.animations = [];
  97681. torus.animations.push(animationInnerCircle);
  97682. this._scene.beginAnimation(torus, 0, 60, true);
  97683. this._hideTeleportationTarget();
  97684. };
  97685. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  97686. this._teleportActive = true;
  97687. if (this._teleportationInitialized) {
  97688. this._teleportationTarget.isVisible = true;
  97689. if (this._isDefaultTeleportationTarget) {
  97690. this._teleportationTarget.getChildren()[0].isVisible = true;
  97691. }
  97692. }
  97693. };
  97694. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  97695. this._teleportActive = false;
  97696. if (this._teleportationInitialized) {
  97697. this._teleportationTarget.isVisible = false;
  97698. if (this._isDefaultTeleportationTarget) {
  97699. this._teleportationTarget.getChildren()[0].isVisible = false;
  97700. }
  97701. }
  97702. };
  97703. VRExperienceHelper.prototype._rotateCamera = function (right) {
  97704. var _this = this;
  97705. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  97706. return;
  97707. }
  97708. if (right) {
  97709. this._rotationAngle++;
  97710. }
  97711. else {
  97712. this._rotationAngle--;
  97713. }
  97714. this.currentVRCamera.animations = [];
  97715. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  97716. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97717. var animationRotationKeys = [];
  97718. animationRotationKeys.push({
  97719. frame: 0,
  97720. value: this.currentVRCamera.rotationQuaternion
  97721. });
  97722. animationRotationKeys.push({
  97723. frame: 6,
  97724. value: target
  97725. });
  97726. animationRotation.setKeys(animationRotationKeys);
  97727. animationRotation.setEasingFunction(this._circleEase);
  97728. this.currentVRCamera.animations.push(animationRotation);
  97729. this._postProcessMove.animations = [];
  97730. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97731. var vignetteWeightKeys = [];
  97732. vignetteWeightKeys.push({
  97733. frame: 0,
  97734. value: 0
  97735. });
  97736. vignetteWeightKeys.push({
  97737. frame: 3,
  97738. value: 4
  97739. });
  97740. vignetteWeightKeys.push({
  97741. frame: 6,
  97742. value: 0
  97743. });
  97744. animationPP.setKeys(vignetteWeightKeys);
  97745. animationPP.setEasingFunction(this._circleEase);
  97746. this._postProcessMove.animations.push(animationPP);
  97747. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97748. var vignetteStretchKeys = [];
  97749. vignetteStretchKeys.push({
  97750. frame: 0,
  97751. value: 0
  97752. });
  97753. vignetteStretchKeys.push({
  97754. frame: 3,
  97755. value: 10
  97756. });
  97757. vignetteStretchKeys.push({
  97758. frame: 6,
  97759. value: 0
  97760. });
  97761. animationPP2.setKeys(vignetteStretchKeys);
  97762. animationPP2.setEasingFunction(this._circleEase);
  97763. this._postProcessMove.animations.push(animationPP2);
  97764. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  97765. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  97766. this._postProcessMove.samples = 4;
  97767. this._webVRCamera.attachPostProcess(this._postProcessMove);
  97768. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  97769. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  97770. });
  97771. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  97772. };
  97773. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  97774. if (hit.pickedPoint) {
  97775. if (gazer._teleportationRequestInitiated) {
  97776. this._displayTeleportationTarget();
  97777. this._haloCenter.copyFrom(hit.pickedPoint);
  97778. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  97779. }
  97780. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  97781. if (pickNormal) {
  97782. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  97783. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  97784. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  97785. }
  97786. this._teleportationTarget.position.y += 0.1;
  97787. }
  97788. };
  97789. /**
  97790. * Teleports the users feet to the desired location
  97791. * @param location The location where the user's feet should be placed
  97792. */
  97793. VRExperienceHelper.prototype.teleportCamera = function (location) {
  97794. var _this = this;
  97795. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  97796. return;
  97797. }
  97798. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  97799. // offset of the headset from the anchor.
  97800. if (this.webVRCamera.leftCamera) {
  97801. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  97802. this._workingVector.subtractInPlace(this.webVRCamera.position);
  97803. location.subtractToRef(this._workingVector, this._workingVector);
  97804. }
  97805. else {
  97806. this._workingVector.copyFrom(location);
  97807. }
  97808. // Add height to account for user's height offset
  97809. if (this.isInVRMode) {
  97810. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  97811. }
  97812. else {
  97813. this._workingVector.y += this._defaultHeight;
  97814. }
  97815. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  97816. // Create animation from the camera's position to the new location
  97817. this.currentVRCamera.animations = [];
  97818. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97819. var animationCameraTeleportationKeys = [{
  97820. frame: 0,
  97821. value: this.currentVRCamera.position
  97822. },
  97823. {
  97824. frame: 11,
  97825. value: this._workingVector
  97826. }
  97827. ];
  97828. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  97829. animationCameraTeleportation.setEasingFunction(this._circleEase);
  97830. this.currentVRCamera.animations.push(animationCameraTeleportation);
  97831. this._postProcessMove.animations = [];
  97832. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97833. var vignetteWeightKeys = [];
  97834. vignetteWeightKeys.push({
  97835. frame: 0,
  97836. value: 0
  97837. });
  97838. vignetteWeightKeys.push({
  97839. frame: 5,
  97840. value: 8
  97841. });
  97842. vignetteWeightKeys.push({
  97843. frame: 11,
  97844. value: 0
  97845. });
  97846. animationPP.setKeys(vignetteWeightKeys);
  97847. this._postProcessMove.animations.push(animationPP);
  97848. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97849. var vignetteStretchKeys = [];
  97850. vignetteStretchKeys.push({
  97851. frame: 0,
  97852. value: 0
  97853. });
  97854. vignetteStretchKeys.push({
  97855. frame: 5,
  97856. value: 10
  97857. });
  97858. vignetteStretchKeys.push({
  97859. frame: 11,
  97860. value: 0
  97861. });
  97862. animationPP2.setKeys(vignetteStretchKeys);
  97863. this._postProcessMove.animations.push(animationPP2);
  97864. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  97865. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  97866. this._webVRCamera.attachPostProcess(this._postProcessMove);
  97867. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  97868. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  97869. });
  97870. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  97871. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  97872. });
  97873. this._hideTeleportationTarget();
  97874. };
  97875. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  97876. if (normal) {
  97877. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  97878. if (angle < Math.PI / 2) {
  97879. normal.scaleInPlace(-1);
  97880. }
  97881. }
  97882. return normal;
  97883. };
  97884. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  97885. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  97886. return;
  97887. }
  97888. var ray = gazer._getForwardRay(this._rayLength);
  97889. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  97890. if (hit) {
  97891. // Populate the contrllers mesh that can be used for drag/drop
  97892. if (gazer._laserPointer) {
  97893. hit.originMesh = gazer._laserPointer.parent;
  97894. }
  97895. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  97896. }
  97897. gazer._currentHit = hit;
  97898. // Moving the gazeTracker on the mesh face targetted
  97899. if (hit && hit.pickedPoint) {
  97900. if (this._displayGaze) {
  97901. var multiplier = 1;
  97902. gazer._gazeTracker.isVisible = true;
  97903. if (gazer._isActionableMesh) {
  97904. multiplier = 3;
  97905. }
  97906. if (this.updateGazeTrackerScale) {
  97907. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  97908. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  97909. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  97910. }
  97911. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  97912. // To avoid z-fighting
  97913. var deltaFighting = 0.002;
  97914. if (pickNormal) {
  97915. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  97916. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  97917. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  97918. }
  97919. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  97920. if (gazer._gazeTracker.position.x < 0) {
  97921. gazer._gazeTracker.position.x += deltaFighting;
  97922. }
  97923. else {
  97924. gazer._gazeTracker.position.x -= deltaFighting;
  97925. }
  97926. if (gazer._gazeTracker.position.y < 0) {
  97927. gazer._gazeTracker.position.y += deltaFighting;
  97928. }
  97929. else {
  97930. gazer._gazeTracker.position.y -= deltaFighting;
  97931. }
  97932. if (gazer._gazeTracker.position.z < 0) {
  97933. gazer._gazeTracker.position.z += deltaFighting;
  97934. }
  97935. else {
  97936. gazer._gazeTracker.position.z -= deltaFighting;
  97937. }
  97938. }
  97939. // Changing the size of the laser pointer based on the distance from the targetted point
  97940. gazer._updatePointerDistance(hit.distance);
  97941. }
  97942. else {
  97943. gazer._updatePointerDistance();
  97944. gazer._gazeTracker.isVisible = false;
  97945. }
  97946. if (hit && hit.pickedMesh) {
  97947. // The object selected is the floor, we're in a teleportation scenario
  97948. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  97949. // Moving the teleportation area to this targetted point
  97950. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  97951. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  97952. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97953. }
  97954. gazer._currentMeshSelected = null;
  97955. if (gazer._teleportationRequestInitiated) {
  97956. this._moveTeleportationSelectorTo(hit, gazer, ray);
  97957. }
  97958. return;
  97959. }
  97960. // If not, we're in a selection scenario
  97961. //this._teleportationAllowed = false;
  97962. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  97963. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  97964. this.onNewMeshPicked.notifyObservers(hit);
  97965. gazer._currentMeshSelected = hit.pickedMesh;
  97966. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  97967. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  97968. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  97969. gazer._isActionableMesh = true;
  97970. }
  97971. else {
  97972. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97973. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97974. gazer._isActionableMesh = false;
  97975. }
  97976. try {
  97977. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  97978. }
  97979. catch (err) {
  97980. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  97981. }
  97982. }
  97983. else {
  97984. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97985. gazer._currentMeshSelected = null;
  97986. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97987. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97988. }
  97989. }
  97990. }
  97991. else {
  97992. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97993. gazer._currentMeshSelected = null;
  97994. //this._teleportationAllowed = false;
  97995. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97996. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97997. }
  97998. };
  97999. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  98000. if (mesh) {
  98001. this.onSelectedMeshUnselected.notifyObservers(mesh);
  98002. }
  98003. };
  98004. /**
  98005. * Sets the color of the laser ray from the vr controllers.
  98006. * @param color new color for the ray.
  98007. */
  98008. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  98009. if (this._leftController) {
  98010. this._leftController._setLaserPointerColor(color);
  98011. }
  98012. if (this._rightController) {
  98013. this._rightController._setLaserPointerColor(color);
  98014. }
  98015. };
  98016. /**
  98017. * Sets the color of the ray from the vr headsets gaze.
  98018. * @param color new color for the ray.
  98019. */
  98020. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  98021. if (!this._cameraGazer._gazeTracker.material) {
  98022. return;
  98023. }
  98024. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  98025. if (this._leftController) {
  98026. this._leftController._gazeTracker.material.emissiveColor = color;
  98027. }
  98028. if (this._rightController) {
  98029. this._rightController._gazeTracker.material.emissiveColor = color;
  98030. }
  98031. };
  98032. /**
  98033. * Exits VR and disposes of the vr experience helper
  98034. */
  98035. VRExperienceHelper.prototype.dispose = function () {
  98036. if (this.isInVRMode) {
  98037. this.exitVR();
  98038. }
  98039. if (this._postProcessMove) {
  98040. this._postProcessMove.dispose();
  98041. }
  98042. if (this._webVRCamera) {
  98043. this._webVRCamera.dispose();
  98044. }
  98045. if (this._vrDeviceOrientationCamera) {
  98046. this._vrDeviceOrientationCamera.dispose();
  98047. }
  98048. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  98049. document.body.removeChild(this._btnVR);
  98050. }
  98051. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  98052. this._deviceOrientationCamera.dispose();
  98053. }
  98054. if (this._cameraGazer) {
  98055. this._cameraGazer.dispose();
  98056. }
  98057. if (this._leftController) {
  98058. this._leftController.dispose();
  98059. }
  98060. if (this._rightController) {
  98061. this._rightController.dispose();
  98062. }
  98063. if (this._teleportationTarget) {
  98064. this._teleportationTarget.dispose();
  98065. }
  98066. this._floorMeshesCollection = [];
  98067. document.removeEventListener("keydown", this._onKeyDown);
  98068. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  98069. window.removeEventListener("resize", this._onResize);
  98070. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  98071. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  98072. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  98073. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  98074. document.onmsfullscreenchange = null;
  98075. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  98076. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  98077. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  98078. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  98079. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  98080. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  98081. this._scene.unregisterBeforeRender(this.beforeRender);
  98082. };
  98083. /**
  98084. * Gets the name of the VRExperienceHelper class
  98085. * @returns "VRExperienceHelper"
  98086. */
  98087. VRExperienceHelper.prototype.getClassName = function () {
  98088. return "VRExperienceHelper";
  98089. };
  98090. return VRExperienceHelper;
  98091. }());
  98092. BABYLON.VRExperienceHelper = VRExperienceHelper;
  98093. })(BABYLON || (BABYLON = {}));
  98094. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  98095. // Mainly based on these 2 articles :
  98096. // 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
  98097. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  98098. var BABYLON;
  98099. (function (BABYLON) {
  98100. /**
  98101. * Defines the potential axis of a Joystick
  98102. */
  98103. var JoystickAxis;
  98104. (function (JoystickAxis) {
  98105. /** X axis */
  98106. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  98107. /** Y axis */
  98108. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  98109. /** Z axis */
  98110. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  98111. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  98112. /**
  98113. * Class used to define virtual joystick (used in touch mode)
  98114. */
  98115. var VirtualJoystick = /** @class */ (function () {
  98116. /**
  98117. * Creates a new virtual joystick
  98118. * @param leftJoystick defines that the joystick is for left hand (false by default)
  98119. */
  98120. function VirtualJoystick(leftJoystick) {
  98121. var _this = this;
  98122. if (leftJoystick) {
  98123. this._leftJoystick = true;
  98124. }
  98125. else {
  98126. this._leftJoystick = false;
  98127. }
  98128. VirtualJoystick._globalJoystickIndex++;
  98129. // By default left & right arrow keys are moving the X
  98130. // and up & down keys are moving the Y
  98131. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  98132. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  98133. this.reverseLeftRight = false;
  98134. this.reverseUpDown = false;
  98135. // collections of pointers
  98136. this._touches = new BABYLON.StringDictionary();
  98137. this.deltaPosition = BABYLON.Vector3.Zero();
  98138. this._joystickSensibility = 25;
  98139. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  98140. this._onResize = function (evt) {
  98141. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  98142. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  98143. if (VirtualJoystick.vjCanvas) {
  98144. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  98145. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  98146. }
  98147. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  98148. };
  98149. // injecting a canvas element on top of the canvas 3D game
  98150. if (!VirtualJoystick.vjCanvas) {
  98151. window.addEventListener("resize", this._onResize, false);
  98152. VirtualJoystick.vjCanvas = document.createElement("canvas");
  98153. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  98154. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  98155. VirtualJoystick.vjCanvas.width = window.innerWidth;
  98156. VirtualJoystick.vjCanvas.height = window.innerHeight;
  98157. VirtualJoystick.vjCanvas.style.width = "100%";
  98158. VirtualJoystick.vjCanvas.style.height = "100%";
  98159. VirtualJoystick.vjCanvas.style.position = "absolute";
  98160. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  98161. VirtualJoystick.vjCanvas.style.top = "0px";
  98162. VirtualJoystick.vjCanvas.style.left = "0px";
  98163. VirtualJoystick.vjCanvas.style.zIndex = "5";
  98164. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  98165. // Support for jQuery PEP polyfill
  98166. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  98167. var context = VirtualJoystick.vjCanvas.getContext('2d');
  98168. if (!context) {
  98169. throw new Error("Unable to create canvas for virtual joystick");
  98170. }
  98171. VirtualJoystick.vjCanvasContext = context;
  98172. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  98173. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  98174. document.body.appendChild(VirtualJoystick.vjCanvas);
  98175. }
  98176. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  98177. this.pressed = false;
  98178. // default joystick color
  98179. this._joystickColor = "cyan";
  98180. this._joystickPointerID = -1;
  98181. // current joystick position
  98182. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  98183. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  98184. // origin joystick position
  98185. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  98186. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  98187. this._onPointerDownHandlerRef = function (evt) {
  98188. _this._onPointerDown(evt);
  98189. };
  98190. this._onPointerMoveHandlerRef = function (evt) {
  98191. _this._onPointerMove(evt);
  98192. };
  98193. this._onPointerUpHandlerRef = function (evt) {
  98194. _this._onPointerUp(evt);
  98195. };
  98196. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  98197. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  98198. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  98199. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  98200. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  98201. evt.preventDefault(); // Disables system menu
  98202. }, false);
  98203. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  98204. }
  98205. /**
  98206. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  98207. * @param newJoystickSensibility defines the new sensibility
  98208. */
  98209. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  98210. this._joystickSensibility = newJoystickSensibility;
  98211. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  98212. };
  98213. VirtualJoystick.prototype._onPointerDown = function (e) {
  98214. var positionOnScreenCondition;
  98215. e.preventDefault();
  98216. if (this._leftJoystick === true) {
  98217. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  98218. }
  98219. else {
  98220. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  98221. }
  98222. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  98223. // First contact will be dedicated to the virtual joystick
  98224. this._joystickPointerID = e.pointerId;
  98225. this._joystickPointerStartPos.x = e.clientX;
  98226. this._joystickPointerStartPos.y = e.clientY;
  98227. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  98228. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  98229. this._deltaJoystickVector.x = 0;
  98230. this._deltaJoystickVector.y = 0;
  98231. this.pressed = true;
  98232. this._touches.add(e.pointerId.toString(), e);
  98233. }
  98234. else {
  98235. // You can only trigger the action buttons with a joystick declared
  98236. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  98237. this._action();
  98238. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  98239. }
  98240. }
  98241. };
  98242. VirtualJoystick.prototype._onPointerMove = function (e) {
  98243. // If the current pointer is the one associated to the joystick (first touch contact)
  98244. if (this._joystickPointerID == e.pointerId) {
  98245. this._joystickPointerPos.x = e.clientX;
  98246. this._joystickPointerPos.y = e.clientY;
  98247. this._deltaJoystickVector = this._joystickPointerPos.clone();
  98248. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  98249. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  98250. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  98251. switch (this._axisTargetedByLeftAndRight) {
  98252. case JoystickAxis.X:
  98253. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  98254. break;
  98255. case JoystickAxis.Y:
  98256. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  98257. break;
  98258. case JoystickAxis.Z:
  98259. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  98260. break;
  98261. }
  98262. var directionUpDown = this.reverseUpDown ? 1 : -1;
  98263. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  98264. switch (this._axisTargetedByUpAndDown) {
  98265. case JoystickAxis.X:
  98266. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  98267. break;
  98268. case JoystickAxis.Y:
  98269. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  98270. break;
  98271. case JoystickAxis.Z:
  98272. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  98273. break;
  98274. }
  98275. }
  98276. else {
  98277. var data = this._touches.get(e.pointerId.toString());
  98278. if (data) {
  98279. data.x = e.clientX;
  98280. data.y = e.clientY;
  98281. }
  98282. }
  98283. };
  98284. VirtualJoystick.prototype._onPointerUp = function (e) {
  98285. if (this._joystickPointerID == e.pointerId) {
  98286. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  98287. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  98288. this._joystickPointerID = -1;
  98289. this.pressed = false;
  98290. }
  98291. else {
  98292. var touch = this._touches.get(e.pointerId.toString());
  98293. if (touch) {
  98294. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  98295. }
  98296. }
  98297. this._deltaJoystickVector.x = 0;
  98298. this._deltaJoystickVector.y = 0;
  98299. this._touches.remove(e.pointerId.toString());
  98300. };
  98301. /**
  98302. * Change the color of the virtual joystick
  98303. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  98304. */
  98305. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  98306. this._joystickColor = newColor;
  98307. };
  98308. /**
  98309. * Defines a callback to call when the joystick is touched
  98310. * @param action defines the callback
  98311. */
  98312. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  98313. this._action = action;
  98314. };
  98315. /**
  98316. * Defines which axis you'd like to control for left & right
  98317. * @param axis defines the axis to use
  98318. */
  98319. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  98320. switch (axis) {
  98321. case JoystickAxis.X:
  98322. case JoystickAxis.Y:
  98323. case JoystickAxis.Z:
  98324. this._axisTargetedByLeftAndRight = axis;
  98325. break;
  98326. default:
  98327. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  98328. break;
  98329. }
  98330. };
  98331. /**
  98332. * Defines which axis you'd like to control for up & down
  98333. * @param axis defines the axis to use
  98334. */
  98335. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  98336. switch (axis) {
  98337. case JoystickAxis.X:
  98338. case JoystickAxis.Y:
  98339. case JoystickAxis.Z:
  98340. this._axisTargetedByUpAndDown = axis;
  98341. break;
  98342. default:
  98343. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  98344. break;
  98345. }
  98346. };
  98347. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  98348. var _this = this;
  98349. if (this.pressed) {
  98350. this._touches.forEach(function (key, touch) {
  98351. if (touch.pointerId === _this._joystickPointerID) {
  98352. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  98353. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  98354. VirtualJoystick.vjCanvasContext.beginPath();
  98355. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  98356. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  98357. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  98358. VirtualJoystick.vjCanvasContext.stroke();
  98359. VirtualJoystick.vjCanvasContext.closePath();
  98360. VirtualJoystick.vjCanvasContext.beginPath();
  98361. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  98362. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  98363. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  98364. VirtualJoystick.vjCanvasContext.stroke();
  98365. VirtualJoystick.vjCanvasContext.closePath();
  98366. VirtualJoystick.vjCanvasContext.beginPath();
  98367. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  98368. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  98369. VirtualJoystick.vjCanvasContext.stroke();
  98370. VirtualJoystick.vjCanvasContext.closePath();
  98371. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  98372. }
  98373. else {
  98374. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  98375. VirtualJoystick.vjCanvasContext.beginPath();
  98376. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  98377. VirtualJoystick.vjCanvasContext.beginPath();
  98378. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  98379. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  98380. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  98381. VirtualJoystick.vjCanvasContext.stroke();
  98382. VirtualJoystick.vjCanvasContext.closePath();
  98383. touch.prevX = touch.x;
  98384. touch.prevY = touch.y;
  98385. }
  98386. ;
  98387. });
  98388. }
  98389. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  98390. };
  98391. /**
  98392. * Release internal HTML canvas
  98393. */
  98394. VirtualJoystick.prototype.releaseCanvas = function () {
  98395. if (VirtualJoystick.vjCanvas) {
  98396. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  98397. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  98398. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  98399. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  98400. window.removeEventListener("resize", this._onResize);
  98401. document.body.removeChild(VirtualJoystick.vjCanvas);
  98402. VirtualJoystick.vjCanvas = null;
  98403. }
  98404. };
  98405. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  98406. VirtualJoystick._globalJoystickIndex = 0;
  98407. return VirtualJoystick;
  98408. }());
  98409. BABYLON.VirtualJoystick = VirtualJoystick;
  98410. })(BABYLON || (BABYLON = {}));
  98411. //# sourceMappingURL=babylon.virtualJoystick.js.map
  98412. var BABYLON;
  98413. (function (BABYLON) {
  98414. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  98415. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  98416. });
  98417. // We're mainly based on the logic defined into the FreeCamera code
  98418. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  98419. __extends(VirtualJoysticksCamera, _super);
  98420. function VirtualJoysticksCamera(name, position, scene) {
  98421. var _this = _super.call(this, name, position, scene) || this;
  98422. _this.inputs.addVirtualJoystick();
  98423. return _this;
  98424. }
  98425. VirtualJoysticksCamera.prototype.getClassName = function () {
  98426. return "VirtualJoysticksCamera";
  98427. };
  98428. return VirtualJoysticksCamera;
  98429. }(BABYLON.FreeCamera));
  98430. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  98431. })(BABYLON || (BABYLON = {}));
  98432. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  98433. var BABYLON;
  98434. (function (BABYLON) {
  98435. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  98436. function FreeCameraVirtualJoystickInput() {
  98437. }
  98438. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  98439. return this._leftjoystick;
  98440. };
  98441. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  98442. return this._rightjoystick;
  98443. };
  98444. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  98445. if (this._leftjoystick) {
  98446. var camera = this.camera;
  98447. var speed = camera._computeLocalCameraSpeed() * 50;
  98448. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  98449. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  98450. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  98451. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  98452. if (!this._leftjoystick.pressed) {
  98453. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  98454. }
  98455. if (!this._rightjoystick.pressed) {
  98456. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  98457. }
  98458. }
  98459. };
  98460. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  98461. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  98462. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  98463. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  98464. this._leftjoystick.setJoystickSensibility(0.15);
  98465. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  98466. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  98467. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  98468. this._rightjoystick.reverseUpDown = true;
  98469. this._rightjoystick.setJoystickSensibility(0.05);
  98470. this._rightjoystick.setJoystickColor("yellow");
  98471. };
  98472. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  98473. this._leftjoystick.releaseCanvas();
  98474. this._rightjoystick.releaseCanvas();
  98475. };
  98476. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  98477. return "FreeCameraVirtualJoystickInput";
  98478. };
  98479. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  98480. return "virtualJoystick";
  98481. };
  98482. return FreeCameraVirtualJoystickInput;
  98483. }());
  98484. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  98485. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  98486. })(BABYLON || (BABYLON = {}));
  98487. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  98488. var BABYLON;
  98489. (function (BABYLON) {
  98490. var SimplificationSettings = /** @class */ (function () {
  98491. function SimplificationSettings(quality, distance, optimizeMesh) {
  98492. this.quality = quality;
  98493. this.distance = distance;
  98494. this.optimizeMesh = optimizeMesh;
  98495. }
  98496. return SimplificationSettings;
  98497. }());
  98498. BABYLON.SimplificationSettings = SimplificationSettings;
  98499. var SimplificationQueue = /** @class */ (function () {
  98500. function SimplificationQueue() {
  98501. this.running = false;
  98502. this._simplificationArray = [];
  98503. }
  98504. SimplificationQueue.prototype.addTask = function (task) {
  98505. this._simplificationArray.push(task);
  98506. };
  98507. SimplificationQueue.prototype.executeNext = function () {
  98508. var task = this._simplificationArray.pop();
  98509. if (task) {
  98510. this.running = true;
  98511. this.runSimplification(task);
  98512. }
  98513. else {
  98514. this.running = false;
  98515. }
  98516. };
  98517. SimplificationQueue.prototype.runSimplification = function (task) {
  98518. var _this = this;
  98519. if (task.parallelProcessing) {
  98520. //parallel simplifier
  98521. task.settings.forEach(function (setting) {
  98522. var simplifier = _this.getSimplifier(task);
  98523. simplifier.simplify(setting, function (newMesh) {
  98524. task.mesh.addLODLevel(setting.distance, newMesh);
  98525. newMesh.isVisible = true;
  98526. //check if it is the last
  98527. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  98528. //all done, run the success callback.
  98529. task.successCallback();
  98530. }
  98531. _this.executeNext();
  98532. });
  98533. });
  98534. }
  98535. else {
  98536. //single simplifier.
  98537. var simplifier = this.getSimplifier(task);
  98538. var runDecimation = function (setting, callback) {
  98539. simplifier.simplify(setting, function (newMesh) {
  98540. task.mesh.addLODLevel(setting.distance, newMesh);
  98541. newMesh.isVisible = true;
  98542. //run the next quality level
  98543. callback();
  98544. });
  98545. };
  98546. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  98547. runDecimation(task.settings[loop.index], function () {
  98548. loop.executeNext();
  98549. });
  98550. }, function () {
  98551. //execution ended, run the success callback.
  98552. if (task.successCallback) {
  98553. task.successCallback();
  98554. }
  98555. _this.executeNext();
  98556. });
  98557. }
  98558. };
  98559. SimplificationQueue.prototype.getSimplifier = function (task) {
  98560. switch (task.simplificationType) {
  98561. case SimplificationType.QUADRATIC:
  98562. default:
  98563. return new QuadraticErrorSimplification(task.mesh);
  98564. }
  98565. };
  98566. return SimplificationQueue;
  98567. }());
  98568. BABYLON.SimplificationQueue = SimplificationQueue;
  98569. /**
  98570. * The implemented types of simplification
  98571. * At the moment only Quadratic Error Decimation is implemented
  98572. */
  98573. var SimplificationType;
  98574. (function (SimplificationType) {
  98575. /** Quadratic error decimation */
  98576. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  98577. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  98578. var DecimationTriangle = /** @class */ (function () {
  98579. function DecimationTriangle(vertices) {
  98580. this.vertices = vertices;
  98581. this.error = new Array(4);
  98582. this.deleted = false;
  98583. this.isDirty = false;
  98584. this.deletePending = false;
  98585. this.borderFactor = 0;
  98586. }
  98587. return DecimationTriangle;
  98588. }());
  98589. BABYLON.DecimationTriangle = DecimationTriangle;
  98590. var DecimationVertex = /** @class */ (function () {
  98591. function DecimationVertex(position, id) {
  98592. this.position = position;
  98593. this.id = id;
  98594. this.isBorder = true;
  98595. this.q = new QuadraticMatrix();
  98596. this.triangleCount = 0;
  98597. this.triangleStart = 0;
  98598. this.originalOffsets = [];
  98599. }
  98600. DecimationVertex.prototype.updatePosition = function (newPosition) {
  98601. this.position.copyFrom(newPosition);
  98602. };
  98603. return DecimationVertex;
  98604. }());
  98605. BABYLON.DecimationVertex = DecimationVertex;
  98606. var QuadraticMatrix = /** @class */ (function () {
  98607. function QuadraticMatrix(data) {
  98608. this.data = new Array(10);
  98609. for (var i = 0; i < 10; ++i) {
  98610. if (data && data[i]) {
  98611. this.data[i] = data[i];
  98612. }
  98613. else {
  98614. this.data[i] = 0;
  98615. }
  98616. }
  98617. }
  98618. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  98619. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  98620. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  98621. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  98622. return det;
  98623. };
  98624. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  98625. for (var i = 0; i < 10; ++i) {
  98626. this.data[i] += matrix.data[i];
  98627. }
  98628. };
  98629. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  98630. for (var i = 0; i < 10; ++i) {
  98631. this.data[i] += data[i];
  98632. }
  98633. };
  98634. QuadraticMatrix.prototype.add = function (matrix) {
  98635. var m = new QuadraticMatrix();
  98636. for (var i = 0; i < 10; ++i) {
  98637. m.data[i] = this.data[i] + matrix.data[i];
  98638. }
  98639. return m;
  98640. };
  98641. QuadraticMatrix.FromData = function (a, b, c, d) {
  98642. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  98643. };
  98644. //returning an array to avoid garbage collection
  98645. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  98646. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  98647. };
  98648. return QuadraticMatrix;
  98649. }());
  98650. BABYLON.QuadraticMatrix = QuadraticMatrix;
  98651. var Reference = /** @class */ (function () {
  98652. function Reference(vertexId, triangleId) {
  98653. this.vertexId = vertexId;
  98654. this.triangleId = triangleId;
  98655. }
  98656. return Reference;
  98657. }());
  98658. BABYLON.Reference = Reference;
  98659. /**
  98660. * An implementation of the Quadratic Error simplification algorithm.
  98661. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  98662. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  98663. * @author RaananW
  98664. */
  98665. var QuadraticErrorSimplification = /** @class */ (function () {
  98666. function QuadraticErrorSimplification(_mesh) {
  98667. this._mesh = _mesh;
  98668. this.syncIterations = 5000;
  98669. this.aggressiveness = 7;
  98670. this.decimationIterations = 100;
  98671. this.boundingBoxEpsilon = BABYLON.Epsilon;
  98672. }
  98673. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  98674. var _this = this;
  98675. this.initDecimatedMesh();
  98676. //iterating through the submeshes array, one after the other.
  98677. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  98678. _this.initWithMesh(loop.index, function () {
  98679. _this.runDecimation(settings, loop.index, function () {
  98680. loop.executeNext();
  98681. });
  98682. }, settings.optimizeMesh);
  98683. }, function () {
  98684. setTimeout(function () {
  98685. successCallback(_this._reconstructedMesh);
  98686. }, 0);
  98687. });
  98688. };
  98689. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  98690. var _this = this;
  98691. var targetCount = ~~(this.triangles.length * settings.quality);
  98692. var deletedTriangles = 0;
  98693. var triangleCount = this.triangles.length;
  98694. var iterationFunction = function (iteration, callback) {
  98695. setTimeout(function () {
  98696. if (iteration % 5 === 0) {
  98697. _this.updateMesh(iteration === 0);
  98698. }
  98699. for (var i = 0; i < _this.triangles.length; ++i) {
  98700. _this.triangles[i].isDirty = false;
  98701. }
  98702. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  98703. var trianglesIterator = function (i) {
  98704. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  98705. var t = _this.triangles[tIdx];
  98706. if (!t)
  98707. return;
  98708. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  98709. return;
  98710. }
  98711. for (var j = 0; j < 3; ++j) {
  98712. if (t.error[j] < threshold) {
  98713. var deleted0 = [];
  98714. var deleted1 = [];
  98715. var v0 = t.vertices[j];
  98716. var v1 = t.vertices[(j + 1) % 3];
  98717. if (v0.isBorder || v1.isBorder)
  98718. continue;
  98719. var p = BABYLON.Vector3.Zero();
  98720. var n = BABYLON.Vector3.Zero();
  98721. var uv = BABYLON.Vector2.Zero();
  98722. var color = new BABYLON.Color4(0, 0, 0, 1);
  98723. _this.calculateError(v0, v1, p, n, uv, color);
  98724. var delTr = new Array();
  98725. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  98726. continue;
  98727. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  98728. continue;
  98729. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  98730. continue;
  98731. var uniqueArray = new Array();
  98732. delTr.forEach(function (deletedT) {
  98733. if (uniqueArray.indexOf(deletedT) === -1) {
  98734. deletedT.deletePending = true;
  98735. uniqueArray.push(deletedT);
  98736. }
  98737. });
  98738. if (uniqueArray.length % 2 !== 0) {
  98739. continue;
  98740. }
  98741. v0.q = v1.q.add(v0.q);
  98742. v0.updatePosition(p);
  98743. var tStart = _this.references.length;
  98744. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  98745. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  98746. var tCount = _this.references.length - tStart;
  98747. if (tCount <= v0.triangleCount) {
  98748. if (tCount) {
  98749. for (var c = 0; c < tCount; c++) {
  98750. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  98751. }
  98752. }
  98753. }
  98754. else {
  98755. v0.triangleStart = tStart;
  98756. }
  98757. v0.triangleCount = tCount;
  98758. break;
  98759. }
  98760. }
  98761. };
  98762. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  98763. }, 0);
  98764. };
  98765. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  98766. if (triangleCount - deletedTriangles <= targetCount)
  98767. loop.breakLoop();
  98768. else {
  98769. iterationFunction(loop.index, function () {
  98770. loop.executeNext();
  98771. });
  98772. }
  98773. }, function () {
  98774. setTimeout(function () {
  98775. //reconstruct this part of the mesh
  98776. _this.reconstructMesh(submeshIndex);
  98777. successCallback();
  98778. }, 0);
  98779. });
  98780. };
  98781. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  98782. var _this = this;
  98783. this.vertices = [];
  98784. this.triangles = [];
  98785. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  98786. var indices = this._mesh.getIndices();
  98787. var submesh = this._mesh.subMeshes[submeshIndex];
  98788. var findInVertices = function (positionToSearch) {
  98789. if (optimizeMesh) {
  98790. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  98791. if (_this.vertices[ii].position.equals(positionToSearch)) {
  98792. return _this.vertices[ii];
  98793. }
  98794. }
  98795. }
  98796. return null;
  98797. };
  98798. var vertexReferences = [];
  98799. var vertexInit = function (i) {
  98800. if (!positionData) {
  98801. return;
  98802. }
  98803. var offset = i + submesh.verticesStart;
  98804. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  98805. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  98806. vertex.originalOffsets.push(offset);
  98807. if (vertex.id === _this.vertices.length) {
  98808. _this.vertices.push(vertex);
  98809. }
  98810. vertexReferences.push(vertex.id);
  98811. };
  98812. //var totalVertices = mesh.getTotalVertices();
  98813. var totalVertices = submesh.verticesCount;
  98814. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  98815. var indicesInit = function (i) {
  98816. if (!indices) {
  98817. return;
  98818. }
  98819. var offset = (submesh.indexStart / 3) + i;
  98820. var pos = (offset * 3);
  98821. var i0 = indices[pos + 0];
  98822. var i1 = indices[pos + 1];
  98823. var i2 = indices[pos + 2];
  98824. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  98825. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  98826. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  98827. var triangle = new DecimationTriangle([v0, v1, v2]);
  98828. triangle.originalOffset = pos;
  98829. _this.triangles.push(triangle);
  98830. };
  98831. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  98832. _this.init(callback);
  98833. });
  98834. });
  98835. };
  98836. QuadraticErrorSimplification.prototype.init = function (callback) {
  98837. var _this = this;
  98838. var triangleInit1 = function (i) {
  98839. var t = _this.triangles[i];
  98840. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  98841. for (var j = 0; j < 3; j++) {
  98842. 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))));
  98843. }
  98844. };
  98845. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  98846. var triangleInit2 = function (i) {
  98847. var t = _this.triangles[i];
  98848. for (var j = 0; j < 3; ++j) {
  98849. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  98850. }
  98851. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  98852. };
  98853. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  98854. callback();
  98855. });
  98856. });
  98857. };
  98858. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  98859. var newTriangles = [];
  98860. var i;
  98861. for (i = 0; i < this.vertices.length; ++i) {
  98862. this.vertices[i].triangleCount = 0;
  98863. }
  98864. var t;
  98865. var j;
  98866. for (i = 0; i < this.triangles.length; ++i) {
  98867. if (!this.triangles[i].deleted) {
  98868. t = this.triangles[i];
  98869. for (j = 0; j < 3; ++j) {
  98870. t.vertices[j].triangleCount = 1;
  98871. }
  98872. newTriangles.push(t);
  98873. }
  98874. }
  98875. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  98876. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  98877. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  98878. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  98879. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  98880. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  98881. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  98882. var vertexCount = 0;
  98883. for (i = 0; i < this.vertices.length; ++i) {
  98884. var vertex = this.vertices[i];
  98885. vertex.id = vertexCount;
  98886. if (vertex.triangleCount) {
  98887. vertex.originalOffsets.forEach(function (originalOffset) {
  98888. if (!normalData) {
  98889. return;
  98890. }
  98891. newPositionData.push(vertex.position.x);
  98892. newPositionData.push(vertex.position.y);
  98893. newPositionData.push(vertex.position.z);
  98894. newNormalData.push(normalData[originalOffset * 3]);
  98895. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  98896. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  98897. if (uvs && uvs.length) {
  98898. newUVsData.push(uvs[(originalOffset * 2)]);
  98899. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  98900. }
  98901. else if (colorsData && colorsData.length) {
  98902. newColorsData.push(colorsData[(originalOffset * 4)]);
  98903. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  98904. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  98905. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  98906. }
  98907. ++vertexCount;
  98908. });
  98909. }
  98910. }
  98911. var startingIndex = this._reconstructedMesh.getTotalIndices();
  98912. var startingVertex = this._reconstructedMesh.getTotalVertices();
  98913. var submeshesArray = this._reconstructedMesh.subMeshes;
  98914. this._reconstructedMesh.subMeshes = [];
  98915. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  98916. var originalIndices = this._mesh.getIndices();
  98917. for (i = 0; i < newTriangles.length; ++i) {
  98918. t = newTriangles[i]; //now get the new referencing point for each vertex
  98919. [0, 1, 2].forEach(function (idx) {
  98920. var id = originalIndices[t.originalOffset + idx];
  98921. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  98922. if (offset < 0)
  98923. offset = 0;
  98924. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  98925. });
  98926. }
  98927. //overwriting the old vertex buffers and indices.
  98928. this._reconstructedMesh.setIndices(newIndicesArray);
  98929. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  98930. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  98931. if (newUVsData.length > 0)
  98932. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  98933. if (newColorsData.length > 0)
  98934. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  98935. //create submesh
  98936. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  98937. if (submeshIndex > 0) {
  98938. this._reconstructedMesh.subMeshes = [];
  98939. submeshesArray.forEach(function (submesh) {
  98940. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  98941. });
  98942. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  98943. }
  98944. };
  98945. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  98946. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  98947. this._reconstructedMesh.material = this._mesh.material;
  98948. this._reconstructedMesh.parent = this._mesh.parent;
  98949. this._reconstructedMesh.isVisible = false;
  98950. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  98951. };
  98952. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  98953. for (var i = 0; i < vertex1.triangleCount; ++i) {
  98954. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  98955. if (t.deleted)
  98956. continue;
  98957. var s = this.references[vertex1.triangleStart + i].vertexId;
  98958. var v1 = t.vertices[(s + 1) % 3];
  98959. var v2 = t.vertices[(s + 2) % 3];
  98960. if ((v1 === vertex2 || v2 === vertex2)) {
  98961. deletedArray[i] = true;
  98962. delTr.push(t);
  98963. continue;
  98964. }
  98965. var d1 = v1.position.subtract(point);
  98966. d1 = d1.normalize();
  98967. var d2 = v2.position.subtract(point);
  98968. d2 = d2.normalize();
  98969. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  98970. return true;
  98971. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  98972. deletedArray[i] = false;
  98973. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  98974. return true;
  98975. }
  98976. return false;
  98977. };
  98978. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  98979. var newDeleted = deletedTriangles;
  98980. for (var i = 0; i < vertex.triangleCount; ++i) {
  98981. var ref = this.references[vertex.triangleStart + i];
  98982. var t = this.triangles[ref.triangleId];
  98983. if (t.deleted)
  98984. continue;
  98985. if (deletedArray[i] && t.deletePending) {
  98986. t.deleted = true;
  98987. newDeleted++;
  98988. continue;
  98989. }
  98990. t.vertices[ref.vertexId] = origVertex;
  98991. t.isDirty = true;
  98992. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  98993. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  98994. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  98995. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  98996. this.references.push(ref);
  98997. }
  98998. return newDeleted;
  98999. };
  99000. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  99001. for (var i = 0; i < this.vertices.length; ++i) {
  99002. var vCount = [];
  99003. var vId = [];
  99004. var v = this.vertices[i];
  99005. var j;
  99006. for (j = 0; j < v.triangleCount; ++j) {
  99007. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  99008. for (var ii = 0; ii < 3; ii++) {
  99009. var ofs = 0;
  99010. var vv = triangle.vertices[ii];
  99011. while (ofs < vCount.length) {
  99012. if (vId[ofs] === vv.id)
  99013. break;
  99014. ++ofs;
  99015. }
  99016. if (ofs === vCount.length) {
  99017. vCount.push(1);
  99018. vId.push(vv.id);
  99019. }
  99020. else {
  99021. vCount[ofs]++;
  99022. }
  99023. }
  99024. }
  99025. for (j = 0; j < vCount.length; ++j) {
  99026. if (vCount[j] === 1) {
  99027. this.vertices[vId[j]].isBorder = true;
  99028. }
  99029. else {
  99030. this.vertices[vId[j]].isBorder = false;
  99031. }
  99032. }
  99033. }
  99034. };
  99035. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  99036. if (identifyBorders === void 0) { identifyBorders = false; }
  99037. var i;
  99038. if (!identifyBorders) {
  99039. var newTrianglesVector = [];
  99040. for (i = 0; i < this.triangles.length; ++i) {
  99041. if (!this.triangles[i].deleted) {
  99042. newTrianglesVector.push(this.triangles[i]);
  99043. }
  99044. }
  99045. this.triangles = newTrianglesVector;
  99046. }
  99047. for (i = 0; i < this.vertices.length; ++i) {
  99048. this.vertices[i].triangleCount = 0;
  99049. this.vertices[i].triangleStart = 0;
  99050. }
  99051. var t;
  99052. var j;
  99053. var v;
  99054. for (i = 0; i < this.triangles.length; ++i) {
  99055. t = this.triangles[i];
  99056. for (j = 0; j < 3; ++j) {
  99057. v = t.vertices[j];
  99058. v.triangleCount++;
  99059. }
  99060. }
  99061. var tStart = 0;
  99062. for (i = 0; i < this.vertices.length; ++i) {
  99063. this.vertices[i].triangleStart = tStart;
  99064. tStart += this.vertices[i].triangleCount;
  99065. this.vertices[i].triangleCount = 0;
  99066. }
  99067. var newReferences = new Array(this.triangles.length * 3);
  99068. for (i = 0; i < this.triangles.length; ++i) {
  99069. t = this.triangles[i];
  99070. for (j = 0; j < 3; ++j) {
  99071. v = t.vertices[j];
  99072. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  99073. v.triangleCount++;
  99074. }
  99075. }
  99076. this.references = newReferences;
  99077. if (identifyBorders) {
  99078. this.identifyBorder();
  99079. }
  99080. };
  99081. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  99082. var x = point.x;
  99083. var y = point.y;
  99084. var z = point.z;
  99085. 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
  99086. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  99087. };
  99088. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  99089. var q = vertex1.q.add(vertex2.q);
  99090. var border = vertex1.isBorder && vertex2.isBorder;
  99091. var error = 0;
  99092. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  99093. if (qDet !== 0 && !border) {
  99094. if (!pointResult) {
  99095. pointResult = BABYLON.Vector3.Zero();
  99096. }
  99097. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  99098. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  99099. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  99100. error = this.vertexError(q, pointResult);
  99101. }
  99102. else {
  99103. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  99104. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  99105. var error1 = this.vertexError(q, vertex1.position);
  99106. var error2 = this.vertexError(q, vertex2.position);
  99107. var error3 = this.vertexError(q, p3);
  99108. error = Math.min(error1, error2, error3);
  99109. if (error === error1) {
  99110. if (pointResult) {
  99111. pointResult.copyFrom(vertex1.position);
  99112. }
  99113. }
  99114. else if (error === error2) {
  99115. if (pointResult) {
  99116. pointResult.copyFrom(vertex2.position);
  99117. }
  99118. }
  99119. else {
  99120. if (pointResult) {
  99121. pointResult.copyFrom(p3);
  99122. }
  99123. }
  99124. }
  99125. return error;
  99126. };
  99127. return QuadraticErrorSimplification;
  99128. }());
  99129. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  99130. })(BABYLON || (BABYLON = {}));
  99131. //# sourceMappingURL=babylon.meshSimplification.js.map
  99132. var BABYLON;
  99133. (function (BABYLON) {
  99134. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  99135. get: function () {
  99136. if (!this._simplificationQueue) {
  99137. this._simplificationQueue = new BABYLON.SimplificationQueue();
  99138. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  99139. if (!component) {
  99140. component = new SimplicationQueueSceneComponent(this);
  99141. this._addComponent(component);
  99142. }
  99143. }
  99144. return this._simplificationQueue;
  99145. },
  99146. set: function (value) {
  99147. this._simplificationQueue = value;
  99148. },
  99149. enumerable: true,
  99150. configurable: true
  99151. });
  99152. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  99153. if (parallelProcessing === void 0) { parallelProcessing = true; }
  99154. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  99155. this.getScene().simplificationQueue.addTask({
  99156. settings: settings,
  99157. parallelProcessing: parallelProcessing,
  99158. mesh: this,
  99159. simplificationType: simplificationType,
  99160. successCallback: successCallback
  99161. });
  99162. return this;
  99163. };
  99164. /**
  99165. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  99166. * created in a scene
  99167. */
  99168. var SimplicationQueueSceneComponent = /** @class */ (function () {
  99169. /**
  99170. * Creates a new instance of the component for the given scene
  99171. * @param scene Defines the scene to register the component in
  99172. */
  99173. function SimplicationQueueSceneComponent(scene) {
  99174. /**
  99175. * The component name helpfull to identify the component in the list of scene components.
  99176. */
  99177. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  99178. this.scene = scene;
  99179. }
  99180. /**
  99181. * Registers the component in a given scene
  99182. */
  99183. SimplicationQueueSceneComponent.prototype.register = function () {
  99184. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  99185. };
  99186. /**
  99187. * Rebuilds the elements related to this component in case of
  99188. * context lost for instance.
  99189. */
  99190. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  99191. // Nothing to do for this component
  99192. };
  99193. /**
  99194. * Disposes the component and the associated ressources
  99195. */
  99196. SimplicationQueueSceneComponent.prototype.dispose = function () {
  99197. // Nothing to do for this component
  99198. };
  99199. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  99200. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  99201. this.scene._simplificationQueue.executeNext();
  99202. }
  99203. };
  99204. return SimplicationQueueSceneComponent;
  99205. }());
  99206. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  99207. })(BABYLON || (BABYLON = {}));
  99208. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  99209. var BABYLON;
  99210. (function (BABYLON) {
  99211. var MeshLODLevel = /** @class */ (function () {
  99212. function MeshLODLevel(distance, mesh) {
  99213. this.distance = distance;
  99214. this.mesh = mesh;
  99215. }
  99216. return MeshLODLevel;
  99217. }());
  99218. BABYLON.MeshLODLevel = MeshLODLevel;
  99219. })(BABYLON || (BABYLON = {}));
  99220. //# sourceMappingURL=babylon.meshLODLevel.js.map
  99221. var BABYLON;
  99222. (function (BABYLON) {
  99223. /**
  99224. * Defines the root class used to create scene optimization to use with SceneOptimizer
  99225. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99226. */
  99227. var SceneOptimization = /** @class */ (function () {
  99228. /**
  99229. * Creates the SceneOptimization object
  99230. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99231. * @param desc defines the description associated with the optimization
  99232. */
  99233. function SceneOptimization(
  99234. /**
  99235. * Defines the priority of this optimization (0 by default which means first in the list)
  99236. */
  99237. priority) {
  99238. if (priority === void 0) { priority = 0; }
  99239. this.priority = priority;
  99240. }
  99241. /**
  99242. * Gets a string describing the action executed by the current optimization
  99243. * @returns description string
  99244. */
  99245. SceneOptimization.prototype.getDescription = function () {
  99246. return "";
  99247. };
  99248. /**
  99249. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99250. * @param scene defines the current scene where to apply this optimization
  99251. * @param optimizer defines the current optimizer
  99252. * @returns true if everything that can be done was applied
  99253. */
  99254. SceneOptimization.prototype.apply = function (scene, optimizer) {
  99255. return true;
  99256. };
  99257. ;
  99258. return SceneOptimization;
  99259. }());
  99260. BABYLON.SceneOptimization = SceneOptimization;
  99261. /**
  99262. * Defines an optimization used to reduce the size of render target textures
  99263. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99264. */
  99265. var TextureOptimization = /** @class */ (function (_super) {
  99266. __extends(TextureOptimization, _super);
  99267. /**
  99268. * Creates the TextureOptimization object
  99269. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99270. * @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
  99271. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  99272. */
  99273. function TextureOptimization(
  99274. /**
  99275. * Defines the priority of this optimization (0 by default which means first in the list)
  99276. */
  99277. priority,
  99278. /**
  99279. * 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
  99280. */
  99281. maximumSize,
  99282. /**
  99283. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  99284. */
  99285. step) {
  99286. if (priority === void 0) { priority = 0; }
  99287. if (maximumSize === void 0) { maximumSize = 1024; }
  99288. if (step === void 0) { step = 0.5; }
  99289. var _this = _super.call(this, priority) || this;
  99290. _this.priority = priority;
  99291. _this.maximumSize = maximumSize;
  99292. _this.step = step;
  99293. return _this;
  99294. }
  99295. /**
  99296. * Gets a string describing the action executed by the current optimization
  99297. * @returns description string
  99298. */
  99299. TextureOptimization.prototype.getDescription = function () {
  99300. return "Reducing render target texture size to " + this.maximumSize;
  99301. };
  99302. /**
  99303. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99304. * @param scene defines the current scene where to apply this optimization
  99305. * @param optimizer defines the current optimizer
  99306. * @returns true if everything that can be done was applied
  99307. */
  99308. TextureOptimization.prototype.apply = function (scene, optimizer) {
  99309. var allDone = true;
  99310. for (var index = 0; index < scene.textures.length; index++) {
  99311. var texture = scene.textures[index];
  99312. if (!texture.canRescale || texture.getContext) {
  99313. continue;
  99314. }
  99315. var currentSize = texture.getSize();
  99316. var maxDimension = Math.max(currentSize.width, currentSize.height);
  99317. if (maxDimension > this.maximumSize) {
  99318. texture.scale(this.step);
  99319. allDone = false;
  99320. }
  99321. }
  99322. return allDone;
  99323. };
  99324. return TextureOptimization;
  99325. }(SceneOptimization));
  99326. BABYLON.TextureOptimization = TextureOptimization;
  99327. /**
  99328. * Defines an optimization used to increase or decrease the rendering resolution
  99329. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99330. */
  99331. var HardwareScalingOptimization = /** @class */ (function (_super) {
  99332. __extends(HardwareScalingOptimization, _super);
  99333. /**
  99334. * Creates the HardwareScalingOptimization object
  99335. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99336. * @param maximumScale defines the maximum scale to use (2 by default)
  99337. * @param step defines the step to use between two passes (0.5 by default)
  99338. */
  99339. function HardwareScalingOptimization(
  99340. /**
  99341. * Defines the priority of this optimization (0 by default which means first in the list)
  99342. */
  99343. priority,
  99344. /**
  99345. * Defines the maximum scale to use (2 by default)
  99346. */
  99347. maximumScale,
  99348. /**
  99349. * Defines the step to use between two passes (0.5 by default)
  99350. */
  99351. step) {
  99352. if (priority === void 0) { priority = 0; }
  99353. if (maximumScale === void 0) { maximumScale = 2; }
  99354. if (step === void 0) { step = 0.25; }
  99355. var _this = _super.call(this, priority) || this;
  99356. _this.priority = priority;
  99357. _this.maximumScale = maximumScale;
  99358. _this.step = step;
  99359. _this._currentScale = -1;
  99360. _this._directionOffset = 1;
  99361. return _this;
  99362. }
  99363. /**
  99364. * Gets a string describing the action executed by the current optimization
  99365. * @return description string
  99366. */
  99367. HardwareScalingOptimization.prototype.getDescription = function () {
  99368. return "Setting hardware scaling level to " + this._currentScale;
  99369. };
  99370. /**
  99371. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99372. * @param scene defines the current scene where to apply this optimization
  99373. * @param optimizer defines the current optimizer
  99374. * @returns true if everything that can be done was applied
  99375. */
  99376. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  99377. if (this._currentScale === -1) {
  99378. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  99379. if (this._currentScale > this.maximumScale) {
  99380. this._directionOffset = -1;
  99381. }
  99382. }
  99383. this._currentScale += this._directionOffset * this.step;
  99384. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  99385. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  99386. };
  99387. ;
  99388. return HardwareScalingOptimization;
  99389. }(SceneOptimization));
  99390. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  99391. /**
  99392. * Defines an optimization used to remove shadows
  99393. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99394. */
  99395. var ShadowsOptimization = /** @class */ (function (_super) {
  99396. __extends(ShadowsOptimization, _super);
  99397. function ShadowsOptimization() {
  99398. return _super !== null && _super.apply(this, arguments) || this;
  99399. }
  99400. /**
  99401. * Gets a string describing the action executed by the current optimization
  99402. * @return description string
  99403. */
  99404. ShadowsOptimization.prototype.getDescription = function () {
  99405. return "Turning shadows on/off";
  99406. };
  99407. /**
  99408. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99409. * @param scene defines the current scene where to apply this optimization
  99410. * @param optimizer defines the current optimizer
  99411. * @returns true if everything that can be done was applied
  99412. */
  99413. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  99414. scene.shadowsEnabled = optimizer.isInImprovementMode;
  99415. return true;
  99416. };
  99417. ;
  99418. return ShadowsOptimization;
  99419. }(SceneOptimization));
  99420. BABYLON.ShadowsOptimization = ShadowsOptimization;
  99421. /**
  99422. * Defines an optimization used to turn post-processes off
  99423. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99424. */
  99425. var PostProcessesOptimization = /** @class */ (function (_super) {
  99426. __extends(PostProcessesOptimization, _super);
  99427. function PostProcessesOptimization() {
  99428. return _super !== null && _super.apply(this, arguments) || this;
  99429. }
  99430. /**
  99431. * Gets a string describing the action executed by the current optimization
  99432. * @return description string
  99433. */
  99434. PostProcessesOptimization.prototype.getDescription = function () {
  99435. return "Turning post-processes on/off";
  99436. };
  99437. /**
  99438. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99439. * @param scene defines the current scene where to apply this optimization
  99440. * @param optimizer defines the current optimizer
  99441. * @returns true if everything that can be done was applied
  99442. */
  99443. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  99444. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  99445. return true;
  99446. };
  99447. ;
  99448. return PostProcessesOptimization;
  99449. }(SceneOptimization));
  99450. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  99451. /**
  99452. * Defines an optimization used to turn lens flares off
  99453. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99454. */
  99455. var LensFlaresOptimization = /** @class */ (function (_super) {
  99456. __extends(LensFlaresOptimization, _super);
  99457. function LensFlaresOptimization() {
  99458. return _super !== null && _super.apply(this, arguments) || this;
  99459. }
  99460. /**
  99461. * Gets a string describing the action executed by the current optimization
  99462. * @return description string
  99463. */
  99464. LensFlaresOptimization.prototype.getDescription = function () {
  99465. return "Turning lens flares on/off";
  99466. };
  99467. /**
  99468. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99469. * @param scene defines the current scene where to apply this optimization
  99470. * @param optimizer defines the current optimizer
  99471. * @returns true if everything that can be done was applied
  99472. */
  99473. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  99474. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  99475. return true;
  99476. };
  99477. ;
  99478. return LensFlaresOptimization;
  99479. }(SceneOptimization));
  99480. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  99481. /**
  99482. * Defines an optimization based on user defined callback.
  99483. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99484. */
  99485. var CustomOptimization = /** @class */ (function (_super) {
  99486. __extends(CustomOptimization, _super);
  99487. function CustomOptimization() {
  99488. return _super !== null && _super.apply(this, arguments) || this;
  99489. }
  99490. /**
  99491. * Gets a string describing the action executed by the current optimization
  99492. * @returns description string
  99493. */
  99494. CustomOptimization.prototype.getDescription = function () {
  99495. if (this.onGetDescription) {
  99496. return this.onGetDescription();
  99497. }
  99498. return "Running user defined callback";
  99499. };
  99500. /**
  99501. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99502. * @param scene defines the current scene where to apply this optimization
  99503. * @param optimizer defines the current optimizer
  99504. * @returns true if everything that can be done was applied
  99505. */
  99506. CustomOptimization.prototype.apply = function (scene, optimizer) {
  99507. if (this.onApply) {
  99508. return this.onApply(scene, optimizer);
  99509. }
  99510. return true;
  99511. };
  99512. ;
  99513. return CustomOptimization;
  99514. }(SceneOptimization));
  99515. BABYLON.CustomOptimization = CustomOptimization;
  99516. /**
  99517. * Defines an optimization used to turn particles off
  99518. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99519. */
  99520. var ParticlesOptimization = /** @class */ (function (_super) {
  99521. __extends(ParticlesOptimization, _super);
  99522. function ParticlesOptimization() {
  99523. return _super !== null && _super.apply(this, arguments) || this;
  99524. }
  99525. /**
  99526. * Gets a string describing the action executed by the current optimization
  99527. * @return description string
  99528. */
  99529. ParticlesOptimization.prototype.getDescription = function () {
  99530. return "Turning particles on/off";
  99531. };
  99532. /**
  99533. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99534. * @param scene defines the current scene where to apply this optimization
  99535. * @param optimizer defines the current optimizer
  99536. * @returns true if everything that can be done was applied
  99537. */
  99538. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  99539. scene.particlesEnabled = optimizer.isInImprovementMode;
  99540. return true;
  99541. };
  99542. ;
  99543. return ParticlesOptimization;
  99544. }(SceneOptimization));
  99545. BABYLON.ParticlesOptimization = ParticlesOptimization;
  99546. /**
  99547. * Defines an optimization used to turn render targets off
  99548. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99549. */
  99550. var RenderTargetsOptimization = /** @class */ (function (_super) {
  99551. __extends(RenderTargetsOptimization, _super);
  99552. function RenderTargetsOptimization() {
  99553. return _super !== null && _super.apply(this, arguments) || this;
  99554. }
  99555. /**
  99556. * Gets a string describing the action executed by the current optimization
  99557. * @return description string
  99558. */
  99559. RenderTargetsOptimization.prototype.getDescription = function () {
  99560. return "Turning render targets off";
  99561. };
  99562. /**
  99563. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99564. * @param scene defines the current scene where to apply this optimization
  99565. * @param optimizer defines the current optimizer
  99566. * @returns true if everything that can be done was applied
  99567. */
  99568. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  99569. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  99570. return true;
  99571. };
  99572. ;
  99573. return RenderTargetsOptimization;
  99574. }(SceneOptimization));
  99575. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  99576. /**
  99577. * Defines an optimization used to merge meshes with compatible materials
  99578. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99579. */
  99580. var MergeMeshesOptimization = /** @class */ (function (_super) {
  99581. __extends(MergeMeshesOptimization, _super);
  99582. function MergeMeshesOptimization() {
  99583. var _this = _super !== null && _super.apply(this, arguments) || this;
  99584. _this._canBeMerged = function (abstractMesh) {
  99585. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  99586. return false;
  99587. }
  99588. var mesh = abstractMesh;
  99589. if (mesh.isDisposed()) {
  99590. return false;
  99591. }
  99592. if (!mesh.isVisible || !mesh.isEnabled()) {
  99593. return false;
  99594. }
  99595. if (mesh.instances.length > 0) {
  99596. return false;
  99597. }
  99598. if (mesh.skeleton || mesh.hasLODLevels) {
  99599. return false;
  99600. }
  99601. return true;
  99602. };
  99603. return _this;
  99604. }
  99605. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  99606. /**
  99607. * Gets or sets a boolean which defines if optimization octree has to be updated
  99608. */
  99609. get: function () {
  99610. return MergeMeshesOptimization._UpdateSelectionTree;
  99611. },
  99612. /**
  99613. * Gets or sets a boolean which defines if optimization octree has to be updated
  99614. */
  99615. set: function (value) {
  99616. MergeMeshesOptimization._UpdateSelectionTree = value;
  99617. },
  99618. enumerable: true,
  99619. configurable: true
  99620. });
  99621. /**
  99622. * Gets a string describing the action executed by the current optimization
  99623. * @return description string
  99624. */
  99625. MergeMeshesOptimization.prototype.getDescription = function () {
  99626. return "Merging similar meshes together";
  99627. };
  99628. /**
  99629. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99630. * @param scene defines the current scene where to apply this optimization
  99631. * @param optimizer defines the current optimizer
  99632. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  99633. * @returns true if everything that can be done was applied
  99634. */
  99635. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  99636. var globalPool = scene.meshes.slice(0);
  99637. var globalLength = globalPool.length;
  99638. for (var index = 0; index < globalLength; index++) {
  99639. var currentPool = new Array();
  99640. var current = globalPool[index];
  99641. // Checks
  99642. if (!this._canBeMerged(current)) {
  99643. continue;
  99644. }
  99645. currentPool.push(current);
  99646. // Find compatible meshes
  99647. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  99648. var otherMesh = globalPool[subIndex];
  99649. if (!this._canBeMerged(otherMesh)) {
  99650. continue;
  99651. }
  99652. if (otherMesh.material !== current.material) {
  99653. continue;
  99654. }
  99655. if (otherMesh.checkCollisions !== current.checkCollisions) {
  99656. continue;
  99657. }
  99658. currentPool.push(otherMesh);
  99659. globalLength--;
  99660. globalPool.splice(subIndex, 1);
  99661. subIndex--;
  99662. }
  99663. if (currentPool.length < 2) {
  99664. continue;
  99665. }
  99666. // Merge meshes
  99667. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  99668. }
  99669. if (updateSelectionTree != undefined) {
  99670. if (updateSelectionTree) {
  99671. scene.createOrUpdateSelectionOctree();
  99672. }
  99673. }
  99674. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  99675. scene.createOrUpdateSelectionOctree();
  99676. }
  99677. return true;
  99678. };
  99679. ;
  99680. MergeMeshesOptimization._UpdateSelectionTree = false;
  99681. return MergeMeshesOptimization;
  99682. }(SceneOptimization));
  99683. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  99684. /**
  99685. * Defines a list of options used by SceneOptimizer
  99686. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99687. */
  99688. var SceneOptimizerOptions = /** @class */ (function () {
  99689. /**
  99690. * Creates a new list of options used by SceneOptimizer
  99691. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  99692. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  99693. */
  99694. function SceneOptimizerOptions(
  99695. /**
  99696. * Defines the target frame rate to reach (60 by default)
  99697. */
  99698. targetFrameRate,
  99699. /**
  99700. * Defines the interval between two checkes (2000ms by default)
  99701. */
  99702. trackerDuration) {
  99703. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  99704. if (trackerDuration === void 0) { trackerDuration = 2000; }
  99705. this.targetFrameRate = targetFrameRate;
  99706. this.trackerDuration = trackerDuration;
  99707. /**
  99708. * Gets the list of optimizations to apply
  99709. */
  99710. this.optimizations = new Array();
  99711. }
  99712. /**
  99713. * Add a new optimization
  99714. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  99715. * @returns the current SceneOptimizerOptions
  99716. */
  99717. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  99718. this.optimizations.push(optimization);
  99719. return this;
  99720. };
  99721. /**
  99722. * Add a new custom optimization
  99723. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  99724. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  99725. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99726. * @returns the current SceneOptimizerOptions
  99727. */
  99728. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  99729. if (priority === void 0) { priority = 0; }
  99730. var optimization = new CustomOptimization(priority);
  99731. optimization.onApply = onApply;
  99732. optimization.onGetDescription = onGetDescription;
  99733. this.optimizations.push(optimization);
  99734. return this;
  99735. };
  99736. /**
  99737. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  99738. * @param targetFrameRate defines the target frame rate (60 by default)
  99739. * @returns a SceneOptimizerOptions object
  99740. */
  99741. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  99742. var result = new SceneOptimizerOptions(targetFrameRate);
  99743. var priority = 0;
  99744. result.addOptimization(new MergeMeshesOptimization(priority));
  99745. result.addOptimization(new ShadowsOptimization(priority));
  99746. result.addOptimization(new LensFlaresOptimization(priority));
  99747. // Next priority
  99748. priority++;
  99749. result.addOptimization(new PostProcessesOptimization(priority));
  99750. result.addOptimization(new ParticlesOptimization(priority));
  99751. // Next priority
  99752. priority++;
  99753. result.addOptimization(new TextureOptimization(priority, 1024));
  99754. return result;
  99755. };
  99756. /**
  99757. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  99758. * @param targetFrameRate defines the target frame rate (60 by default)
  99759. * @returns a SceneOptimizerOptions object
  99760. */
  99761. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  99762. var result = new SceneOptimizerOptions(targetFrameRate);
  99763. var priority = 0;
  99764. result.addOptimization(new MergeMeshesOptimization(priority));
  99765. result.addOptimization(new ShadowsOptimization(priority));
  99766. result.addOptimization(new LensFlaresOptimization(priority));
  99767. // Next priority
  99768. priority++;
  99769. result.addOptimization(new PostProcessesOptimization(priority));
  99770. result.addOptimization(new ParticlesOptimization(priority));
  99771. // Next priority
  99772. priority++;
  99773. result.addOptimization(new TextureOptimization(priority, 512));
  99774. // Next priority
  99775. priority++;
  99776. result.addOptimization(new RenderTargetsOptimization(priority));
  99777. // Next priority
  99778. priority++;
  99779. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  99780. return result;
  99781. };
  99782. /**
  99783. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  99784. * @param targetFrameRate defines the target frame rate (60 by default)
  99785. * @returns a SceneOptimizerOptions object
  99786. */
  99787. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  99788. var result = new SceneOptimizerOptions(targetFrameRate);
  99789. var priority = 0;
  99790. result.addOptimization(new MergeMeshesOptimization(priority));
  99791. result.addOptimization(new ShadowsOptimization(priority));
  99792. result.addOptimization(new LensFlaresOptimization(priority));
  99793. // Next priority
  99794. priority++;
  99795. result.addOptimization(new PostProcessesOptimization(priority));
  99796. result.addOptimization(new ParticlesOptimization(priority));
  99797. // Next priority
  99798. priority++;
  99799. result.addOptimization(new TextureOptimization(priority, 256));
  99800. // Next priority
  99801. priority++;
  99802. result.addOptimization(new RenderTargetsOptimization(priority));
  99803. // Next priority
  99804. priority++;
  99805. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  99806. return result;
  99807. };
  99808. return SceneOptimizerOptions;
  99809. }());
  99810. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  99811. /**
  99812. * Class used to run optimizations in order to reach a target frame rate
  99813. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99814. */
  99815. var SceneOptimizer = /** @class */ (function () {
  99816. /**
  99817. * Creates a new SceneOptimizer
  99818. * @param scene defines the scene to work on
  99819. * @param options defines the options to use with the SceneOptimizer
  99820. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  99821. * @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)
  99822. */
  99823. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  99824. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  99825. if (improvementMode === void 0) { improvementMode = false; }
  99826. var _this = this;
  99827. this._isRunning = false;
  99828. this._currentPriorityLevel = 0;
  99829. this._targetFrameRate = 60;
  99830. this._trackerDuration = 2000;
  99831. this._currentFrameRate = 0;
  99832. this._improvementMode = false;
  99833. /**
  99834. * Defines an observable called when the optimizer reaches the target frame rate
  99835. */
  99836. this.onSuccessObservable = new BABYLON.Observable();
  99837. /**
  99838. * Defines an observable called when the optimizer enables an optimization
  99839. */
  99840. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  99841. /**
  99842. * Defines an observable called when the optimizer is not able to reach the target frame rate
  99843. */
  99844. this.onFailureObservable = new BABYLON.Observable();
  99845. if (!options) {
  99846. this._options = new SceneOptimizerOptions();
  99847. }
  99848. else {
  99849. this._options = options;
  99850. }
  99851. if (this._options.targetFrameRate) {
  99852. this._targetFrameRate = this._options.targetFrameRate;
  99853. }
  99854. if (this._options.trackerDuration) {
  99855. this._trackerDuration = this._options.trackerDuration;
  99856. }
  99857. if (autoGeneratePriorities) {
  99858. var priority = 0;
  99859. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  99860. var optim = _a[_i];
  99861. optim.priority = priority++;
  99862. }
  99863. }
  99864. this._improvementMode = improvementMode;
  99865. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  99866. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  99867. _this._sceneDisposeObserver = null;
  99868. _this.dispose();
  99869. });
  99870. }
  99871. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  99872. /**
  99873. * Gets a boolean indicating if the optimizer is in improvement mode
  99874. */
  99875. get: function () {
  99876. return this._improvementMode;
  99877. },
  99878. enumerable: true,
  99879. configurable: true
  99880. });
  99881. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  99882. /**
  99883. * Gets the current priority level (0 at start)
  99884. */
  99885. get: function () {
  99886. return this._currentPriorityLevel;
  99887. },
  99888. enumerable: true,
  99889. configurable: true
  99890. });
  99891. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  99892. /**
  99893. * Gets the current frame rate checked by the SceneOptimizer
  99894. */
  99895. get: function () {
  99896. return this._currentFrameRate;
  99897. },
  99898. enumerable: true,
  99899. configurable: true
  99900. });
  99901. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  99902. /**
  99903. * Gets or sets the current target frame rate (60 by default)
  99904. */
  99905. get: function () {
  99906. return this._targetFrameRate;
  99907. },
  99908. /**
  99909. * Gets or sets the current target frame rate (60 by default)
  99910. */
  99911. set: function (value) {
  99912. this._targetFrameRate = value;
  99913. },
  99914. enumerable: true,
  99915. configurable: true
  99916. });
  99917. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  99918. /**
  99919. * Gets or sets the current interval between two checks (every 2000ms by default)
  99920. */
  99921. get: function () {
  99922. return this._trackerDuration;
  99923. },
  99924. /**
  99925. * Gets or sets the current interval between two checks (every 2000ms by default)
  99926. */
  99927. set: function (value) {
  99928. this._trackerDuration = value;
  99929. },
  99930. enumerable: true,
  99931. configurable: true
  99932. });
  99933. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  99934. /**
  99935. * Gets the list of active optimizations
  99936. */
  99937. get: function () {
  99938. return this._options.optimizations;
  99939. },
  99940. enumerable: true,
  99941. configurable: true
  99942. });
  99943. /**
  99944. * Stops the current optimizer
  99945. */
  99946. SceneOptimizer.prototype.stop = function () {
  99947. this._isRunning = false;
  99948. };
  99949. /**
  99950. * Reset the optimizer to initial step (current priority level = 0)
  99951. */
  99952. SceneOptimizer.prototype.reset = function () {
  99953. this._currentPriorityLevel = 0;
  99954. };
  99955. /**
  99956. * Start the optimizer. By default it will try to reach a specific framerate
  99957. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  99958. */
  99959. SceneOptimizer.prototype.start = function () {
  99960. var _this = this;
  99961. if (this._isRunning) {
  99962. return;
  99963. }
  99964. this._isRunning = true;
  99965. // Let's wait for the scene to be ready before running our check
  99966. this._scene.executeWhenReady(function () {
  99967. setTimeout(function () {
  99968. _this._checkCurrentState();
  99969. }, _this._trackerDuration);
  99970. });
  99971. };
  99972. SceneOptimizer.prototype._checkCurrentState = function () {
  99973. var _this = this;
  99974. if (!this._isRunning) {
  99975. return;
  99976. }
  99977. var scene = this._scene;
  99978. var options = this._options;
  99979. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  99980. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  99981. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  99982. this._isRunning = false;
  99983. this.onSuccessObservable.notifyObservers(this);
  99984. return;
  99985. }
  99986. // Apply current level of optimizations
  99987. var allDone = true;
  99988. var noOptimizationApplied = true;
  99989. for (var index = 0; index < options.optimizations.length; index++) {
  99990. var optimization = options.optimizations[index];
  99991. if (optimization.priority === this._currentPriorityLevel) {
  99992. noOptimizationApplied = false;
  99993. allDone = allDone && optimization.apply(scene, this);
  99994. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  99995. }
  99996. }
  99997. // If no optimization was applied, this is a failure :(
  99998. if (noOptimizationApplied) {
  99999. this._isRunning = false;
  100000. this.onFailureObservable.notifyObservers(this);
  100001. return;
  100002. }
  100003. // If all optimizations were done, move to next level
  100004. if (allDone) {
  100005. this._currentPriorityLevel++;
  100006. }
  100007. // Let's the system running for a specific amount of time before checking FPS
  100008. scene.executeWhenReady(function () {
  100009. setTimeout(function () {
  100010. _this._checkCurrentState();
  100011. }, _this._trackerDuration);
  100012. });
  100013. };
  100014. /**
  100015. * Release all resources
  100016. */
  100017. SceneOptimizer.prototype.dispose = function () {
  100018. this.stop();
  100019. this.onSuccessObservable.clear();
  100020. this.onFailureObservable.clear();
  100021. this.onNewOptimizationAppliedObservable.clear();
  100022. if (this._sceneDisposeObserver) {
  100023. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  100024. }
  100025. };
  100026. /**
  100027. * Helper function to create a SceneOptimizer with one single line of code
  100028. * @param scene defines the scene to work on
  100029. * @param options defines the options to use with the SceneOptimizer
  100030. * @param onSuccess defines a callback to call on success
  100031. * @param onFailure defines a callback to call on failure
  100032. * @returns the new SceneOptimizer object
  100033. */
  100034. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  100035. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  100036. if (onSuccess) {
  100037. optimizer.onSuccessObservable.add(function () {
  100038. onSuccess();
  100039. });
  100040. }
  100041. if (onFailure) {
  100042. optimizer.onFailureObservable.add(function () {
  100043. onFailure();
  100044. });
  100045. }
  100046. optimizer.start();
  100047. return optimizer;
  100048. };
  100049. return SceneOptimizer;
  100050. }());
  100051. BABYLON.SceneOptimizer = SceneOptimizer;
  100052. })(BABYLON || (BABYLON = {}));
  100053. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  100054. var BABYLON;
  100055. (function (BABYLON) {
  100056. /**
  100057. * Gets the outline renderer associated with the scene
  100058. * @returns a OutlineRenderer
  100059. */
  100060. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  100061. if (!this._outlineRenderer) {
  100062. this._outlineRenderer = new OutlineRenderer(this);
  100063. }
  100064. return this._outlineRenderer;
  100065. };
  100066. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  100067. get: function () {
  100068. return this._renderOutline;
  100069. },
  100070. set: function (value) {
  100071. if (value) {
  100072. // Lazy Load the component.
  100073. this.getScene().getOutlineRenderer();
  100074. }
  100075. this._renderOutline = value;
  100076. },
  100077. enumerable: true,
  100078. configurable: true
  100079. });
  100080. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  100081. get: function () {
  100082. return this._renderOverlay;
  100083. },
  100084. set: function (value) {
  100085. if (value) {
  100086. // Lazy Load the component.
  100087. this.getScene().getOutlineRenderer();
  100088. }
  100089. this._renderOverlay = value;
  100090. },
  100091. enumerable: true,
  100092. configurable: true
  100093. });
  100094. /**
  100095. * This class is responsible to draw bothe outline/overlay of meshes.
  100096. * It should not be used directly but through the available method on mesh.
  100097. */
  100098. var OutlineRenderer = /** @class */ (function () {
  100099. /**
  100100. * Instantiates a new outline renderer. (There could be only one per scene).
  100101. * @param scene Defines the scene it belongs to
  100102. */
  100103. function OutlineRenderer(scene) {
  100104. /**
  100105. * The name of the component. Each component must have a unique name.
  100106. */
  100107. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  100108. /**
  100109. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  100110. */
  100111. this.zOffset = 1;
  100112. this.scene = scene;
  100113. this._engine = scene.getEngine();
  100114. this.scene._addComponent(this);
  100115. }
  100116. /**
  100117. * Register the component to one instance of a scene.
  100118. */
  100119. OutlineRenderer.prototype.register = function () {
  100120. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  100121. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  100122. };
  100123. /**
  100124. * Rebuilds the elements related to this component in case of
  100125. * context lost for instance.
  100126. */
  100127. OutlineRenderer.prototype.rebuild = function () {
  100128. // Nothing to do here.
  100129. };
  100130. /**
  100131. * Disposes the component and the associated ressources.
  100132. */
  100133. OutlineRenderer.prototype.dispose = function () {
  100134. // Nothing to do here.
  100135. };
  100136. /**
  100137. * Renders the outline in the canvas.
  100138. * @param subMesh Defines the sumesh to render
  100139. * @param batch Defines the batch of meshes in case of instances
  100140. * @param useOverlay Defines if the rendering is for the overlay or the outline
  100141. */
  100142. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  100143. var _this = this;
  100144. if (useOverlay === void 0) { useOverlay = false; }
  100145. var scene = this.scene;
  100146. var engine = scene.getEngine();
  100147. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  100148. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  100149. return;
  100150. }
  100151. var mesh = subMesh.getRenderingMesh();
  100152. var material = subMesh.getMaterial();
  100153. if (!material || !scene.activeCamera) {
  100154. return;
  100155. }
  100156. engine.enableEffect(this._effect);
  100157. // Logarithmic depth
  100158. if (material.useLogarithmicDepth) {
  100159. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  100160. }
  100161. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  100162. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  100163. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  100164. // Bones
  100165. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  100166. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  100167. }
  100168. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  100169. // Alpha test
  100170. if (material && material.needAlphaTesting()) {
  100171. var alphaTexture = material.getAlphaTestTexture();
  100172. if (alphaTexture) {
  100173. this._effect.setTexture("diffuseSampler", alphaTexture);
  100174. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  100175. }
  100176. }
  100177. engine.setZOffset(-this.zOffset);
  100178. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  100179. engine.setZOffset(0);
  100180. };
  100181. /**
  100182. * Returns whether or not the outline renderer is ready for a given submesh.
  100183. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  100184. * @param subMesh Defines the submesh to check readyness for
  100185. * @param useInstances Defines wheter wee are trying to render instances or not
  100186. * @returns true if ready otherwise false
  100187. */
  100188. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  100189. var defines = [];
  100190. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  100191. var mesh = subMesh.getMesh();
  100192. var material = subMesh.getMaterial();
  100193. if (material) {
  100194. // Alpha test
  100195. if (material.needAlphaTesting()) {
  100196. defines.push("#define ALPHATEST");
  100197. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100198. attribs.push(BABYLON.VertexBuffer.UVKind);
  100199. defines.push("#define UV1");
  100200. }
  100201. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  100202. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100203. defines.push("#define UV2");
  100204. }
  100205. }
  100206. //Logarithmic depth
  100207. if (material.useLogarithmicDepth) {
  100208. defines.push("#define LOGARITHMICDEPTH");
  100209. }
  100210. }
  100211. // Bones
  100212. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  100213. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  100214. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  100215. if (mesh.numBoneInfluencers > 4) {
  100216. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  100217. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  100218. }
  100219. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  100220. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  100221. }
  100222. else {
  100223. defines.push("#define NUM_BONE_INFLUENCERS 0");
  100224. }
  100225. // Instances
  100226. if (useInstances) {
  100227. defines.push("#define INSTANCES");
  100228. attribs.push("world0");
  100229. attribs.push("world1");
  100230. attribs.push("world2");
  100231. attribs.push("world3");
  100232. }
  100233. // Get correct effect
  100234. var join = defines.join("\n");
  100235. if (this._cachedDefines !== join) {
  100236. this._cachedDefines = join;
  100237. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  100238. }
  100239. return this._effect.isReady();
  100240. };
  100241. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  100242. // Outline - step 1
  100243. this._savedDepthWrite = this._engine.getDepthWrite();
  100244. if (mesh.renderOutline) {
  100245. this._engine.setDepthWrite(false);
  100246. this.render(subMesh, batch);
  100247. this._engine.setDepthWrite(this._savedDepthWrite);
  100248. }
  100249. };
  100250. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  100251. // Outline - step 2
  100252. if (mesh.renderOutline && this._savedDepthWrite) {
  100253. this._engine.setDepthWrite(true);
  100254. this._engine.setColorWrite(false);
  100255. this.render(subMesh, batch);
  100256. this._engine.setColorWrite(true);
  100257. }
  100258. // Overlay
  100259. if (mesh.renderOverlay) {
  100260. var currentMode = this._engine.getAlphaMode();
  100261. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  100262. this.render(subMesh, batch, true);
  100263. this._engine.setAlphaMode(currentMode);
  100264. }
  100265. };
  100266. return OutlineRenderer;
  100267. }());
  100268. BABYLON.OutlineRenderer = OutlineRenderer;
  100269. })(BABYLON || (BABYLON = {}));
  100270. //# sourceMappingURL=babylon.outlineRenderer.js.map
  100271. var BABYLON;
  100272. (function (BABYLON) {
  100273. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  100274. if (this._edgesRenderer) {
  100275. this._edgesRenderer.dispose();
  100276. this._edgesRenderer = null;
  100277. }
  100278. return this;
  100279. };
  100280. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  100281. if (epsilon === void 0) { epsilon = 0.95; }
  100282. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  100283. this.disableEdgesRendering();
  100284. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  100285. return this;
  100286. };
  100287. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  100288. get: function () {
  100289. return this._edgesRenderer;
  100290. },
  100291. enumerable: true,
  100292. configurable: true
  100293. });
  100294. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  100295. if (epsilon === void 0) { epsilon = 0.95; }
  100296. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  100297. this.disableEdgesRendering();
  100298. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  100299. return this;
  100300. };
  100301. /**
  100302. * FaceAdjacencies Helper class to generate edges
  100303. */
  100304. var FaceAdjacencies = /** @class */ (function () {
  100305. function FaceAdjacencies() {
  100306. this.edges = new Array();
  100307. this.edgesConnectedCount = 0;
  100308. }
  100309. return FaceAdjacencies;
  100310. }());
  100311. /**
  100312. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  100313. */
  100314. var EdgesRenderer = /** @class */ (function () {
  100315. /**
  100316. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  100317. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  100318. * @param source Mesh used to create edges
  100319. * @param epsilon sum of angles in adjacency to check for edge
  100320. * @param checkVerticesInsteadOfIndices
  100321. * @param generateEdgesLines - should generate Lines or only prepare resources.
  100322. */
  100323. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  100324. if (epsilon === void 0) { epsilon = 0.95; }
  100325. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  100326. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  100327. var _this = this;
  100328. this.edgesWidthScalerForOrthographic = 1000.0;
  100329. this.edgesWidthScalerForPerspective = 50.0;
  100330. this._linesPositions = new Array();
  100331. this._linesNormals = new Array();
  100332. this._linesIndices = new Array();
  100333. this._buffers = {};
  100334. this._checkVerticesInsteadOfIndices = false;
  100335. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  100336. this.isEnabled = true;
  100337. this._source = source;
  100338. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  100339. this._epsilon = epsilon;
  100340. this._prepareRessources();
  100341. if (generateEdgesLines) {
  100342. this._generateEdgesLines();
  100343. }
  100344. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  100345. _this._rebuild();
  100346. });
  100347. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  100348. _this.dispose();
  100349. });
  100350. }
  100351. EdgesRenderer.prototype._prepareRessources = function () {
  100352. if (this._lineShader) {
  100353. return;
  100354. }
  100355. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  100356. attributes: ["position", "normal"],
  100357. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  100358. });
  100359. this._lineShader.disableDepthWrite = true;
  100360. this._lineShader.backFaceCulling = false;
  100361. };
  100362. /** @hidden */
  100363. EdgesRenderer.prototype._rebuild = function () {
  100364. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  100365. if (buffer) {
  100366. buffer._rebuild();
  100367. }
  100368. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  100369. if (buffer) {
  100370. buffer._rebuild();
  100371. }
  100372. var scene = this._source.getScene();
  100373. var engine = scene.getEngine();
  100374. this._ib = engine.createIndexBuffer(this._linesIndices);
  100375. };
  100376. /**
  100377. * Releases the required resources for the edges renderer
  100378. */
  100379. EdgesRenderer.prototype.dispose = function () {
  100380. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  100381. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  100382. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  100383. if (buffer) {
  100384. buffer.dispose();
  100385. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  100386. }
  100387. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  100388. if (buffer) {
  100389. buffer.dispose();
  100390. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  100391. }
  100392. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  100393. this._lineShader.dispose();
  100394. };
  100395. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  100396. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  100397. return 0;
  100398. }
  100399. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  100400. return 1;
  100401. }
  100402. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  100403. return 2;
  100404. }
  100405. return -1;
  100406. };
  100407. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  100408. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  100409. return 0;
  100410. }
  100411. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  100412. return 1;
  100413. }
  100414. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  100415. return 2;
  100416. }
  100417. return -1;
  100418. };
  100419. /**
  100420. * Checks if the pair of p0 and p1 is en edge
  100421. * @param faceIndex
  100422. * @param edge
  100423. * @param faceNormals
  100424. * @param p0
  100425. * @param p1
  100426. * @private
  100427. */
  100428. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  100429. var needToCreateLine;
  100430. if (edge === undefined) {
  100431. needToCreateLine = true;
  100432. }
  100433. else {
  100434. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  100435. needToCreateLine = dotProduct < this._epsilon;
  100436. }
  100437. if (needToCreateLine) {
  100438. var offset = this._linesPositions.length / 3;
  100439. var normal = p0.subtract(p1);
  100440. normal.normalize();
  100441. // Positions
  100442. this._linesPositions.push(p0.x);
  100443. this._linesPositions.push(p0.y);
  100444. this._linesPositions.push(p0.z);
  100445. this._linesPositions.push(p0.x);
  100446. this._linesPositions.push(p0.y);
  100447. this._linesPositions.push(p0.z);
  100448. this._linesPositions.push(p1.x);
  100449. this._linesPositions.push(p1.y);
  100450. this._linesPositions.push(p1.z);
  100451. this._linesPositions.push(p1.x);
  100452. this._linesPositions.push(p1.y);
  100453. this._linesPositions.push(p1.z);
  100454. // Normals
  100455. this._linesNormals.push(p1.x);
  100456. this._linesNormals.push(p1.y);
  100457. this._linesNormals.push(p1.z);
  100458. this._linesNormals.push(-1);
  100459. this._linesNormals.push(p1.x);
  100460. this._linesNormals.push(p1.y);
  100461. this._linesNormals.push(p1.z);
  100462. this._linesNormals.push(1);
  100463. this._linesNormals.push(p0.x);
  100464. this._linesNormals.push(p0.y);
  100465. this._linesNormals.push(p0.z);
  100466. this._linesNormals.push(-1);
  100467. this._linesNormals.push(p0.x);
  100468. this._linesNormals.push(p0.y);
  100469. this._linesNormals.push(p0.z);
  100470. this._linesNormals.push(1);
  100471. // Indices
  100472. this._linesIndices.push(offset);
  100473. this._linesIndices.push(offset + 1);
  100474. this._linesIndices.push(offset + 2);
  100475. this._linesIndices.push(offset);
  100476. this._linesIndices.push(offset + 2);
  100477. this._linesIndices.push(offset + 3);
  100478. }
  100479. };
  100480. /**
  100481. * Generates lines edges from adjacencjes
  100482. * @private
  100483. */
  100484. EdgesRenderer.prototype._generateEdgesLines = function () {
  100485. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  100486. var indices = this._source.getIndices();
  100487. if (!indices || !positions) {
  100488. return;
  100489. }
  100490. // First let's find adjacencies
  100491. var adjacencies = new Array();
  100492. var faceNormals = new Array();
  100493. var index;
  100494. var faceAdjacencies;
  100495. // Prepare faces
  100496. for (index = 0; index < indices.length; index += 3) {
  100497. faceAdjacencies = new FaceAdjacencies();
  100498. var p0Index = indices[index];
  100499. var p1Index = indices[index + 1];
  100500. var p2Index = indices[index + 2];
  100501. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  100502. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  100503. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  100504. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  100505. faceNormal.normalize();
  100506. faceNormals.push(faceNormal);
  100507. adjacencies.push(faceAdjacencies);
  100508. }
  100509. // Scan
  100510. for (index = 0; index < adjacencies.length; index++) {
  100511. faceAdjacencies = adjacencies[index];
  100512. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  100513. var otherFaceAdjacencies = adjacencies[otherIndex];
  100514. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  100515. break;
  100516. }
  100517. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  100518. continue;
  100519. }
  100520. var otherP0 = indices[otherIndex * 3];
  100521. var otherP1 = indices[otherIndex * 3 + 1];
  100522. var otherP2 = indices[otherIndex * 3 + 2];
  100523. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  100524. var otherEdgeIndex = 0;
  100525. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  100526. continue;
  100527. }
  100528. switch (edgeIndex) {
  100529. case 0:
  100530. if (this._checkVerticesInsteadOfIndices) {
  100531. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  100532. }
  100533. else {
  100534. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  100535. }
  100536. break;
  100537. case 1:
  100538. if (this._checkVerticesInsteadOfIndices) {
  100539. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  100540. }
  100541. else {
  100542. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  100543. }
  100544. break;
  100545. case 2:
  100546. if (this._checkVerticesInsteadOfIndices) {
  100547. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  100548. }
  100549. else {
  100550. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  100551. }
  100552. break;
  100553. }
  100554. if (otherEdgeIndex === -1) {
  100555. continue;
  100556. }
  100557. faceAdjacencies.edges[edgeIndex] = otherIndex;
  100558. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  100559. faceAdjacencies.edgesConnectedCount++;
  100560. otherFaceAdjacencies.edgesConnectedCount++;
  100561. if (faceAdjacencies.edgesConnectedCount === 3) {
  100562. break;
  100563. }
  100564. }
  100565. }
  100566. }
  100567. // Create lines
  100568. for (index = 0; index < adjacencies.length; index++) {
  100569. // 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
  100570. var current = adjacencies[index];
  100571. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  100572. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  100573. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  100574. }
  100575. // Merge into a single mesh
  100576. var engine = this._source.getScene().getEngine();
  100577. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  100578. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  100579. this._ib = engine.createIndexBuffer(this._linesIndices);
  100580. this._indicesCount = this._linesIndices.length;
  100581. };
  100582. /**
  100583. * Checks wether or not the edges renderer is ready to render.
  100584. * @return true if ready, otherwise false.
  100585. */
  100586. EdgesRenderer.prototype.isReady = function () {
  100587. return this._lineShader.isReady();
  100588. };
  100589. /**
  100590. * Renders the edges of the attached mesh,
  100591. */
  100592. EdgesRenderer.prototype.render = function () {
  100593. var scene = this._source.getScene();
  100594. if (!this.isReady() || !scene.activeCamera) {
  100595. return;
  100596. }
  100597. var engine = scene.getEngine();
  100598. this._lineShader._preBind();
  100599. if (this._source.edgesColor.a !== 1) {
  100600. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  100601. }
  100602. else {
  100603. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  100604. }
  100605. // VBOs
  100606. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  100607. scene.resetCachedMaterial();
  100608. this._lineShader.setColor4("color", this._source.edgesColor);
  100609. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  100610. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  100611. }
  100612. else {
  100613. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  100614. }
  100615. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  100616. this._lineShader.bind(this._source.getWorldMatrix());
  100617. // Draw order
  100618. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  100619. this._lineShader.unbind();
  100620. };
  100621. return EdgesRenderer;
  100622. }());
  100623. BABYLON.EdgesRenderer = EdgesRenderer;
  100624. })(BABYLON || (BABYLON = {}));
  100625. //# sourceMappingURL=babylon.edgesRenderer.js.map
  100626. var BABYLON;
  100627. (function (BABYLON) {
  100628. /**
  100629. * FaceAdjacencies Helper class to generate edges
  100630. */
  100631. var FaceAdjacencies = /** @class */ (function () {
  100632. function FaceAdjacencies() {
  100633. this.edges = new Array();
  100634. this.edgesConnectedCount = 0;
  100635. }
  100636. return FaceAdjacencies;
  100637. }());
  100638. /**
  100639. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  100640. */
  100641. var LineEdgesRenderer = /** @class */ (function (_super) {
  100642. __extends(LineEdgesRenderer, _super);
  100643. /**
  100644. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  100645. * @param source LineMesh used to generate edges
  100646. * @param epsilon not important (specified angle for edge detection)
  100647. * @param checkVerticesInsteadOfIndices not important for LineMesh
  100648. */
  100649. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  100650. if (epsilon === void 0) { epsilon = 0.95; }
  100651. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  100652. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  100653. _this._generateEdgesLines();
  100654. return _this;
  100655. }
  100656. /**
  100657. * Always create the edge since its a line so only important things are p0 and p1
  100658. * @param faceIndex not important for LineMesh
  100659. * @param edge not important for LineMesh
  100660. * @param faceNormals not important for LineMesh
  100661. * @param p0 beginnig of line
  100662. * @param p1 end of line
  100663. */
  100664. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  100665. var offset = this._linesPositions.length / 3;
  100666. var normal = p0.subtract(p1);
  100667. normal.normalize();
  100668. // Positions
  100669. this._linesPositions.push(p0.x);
  100670. this._linesPositions.push(p0.y);
  100671. this._linesPositions.push(p0.z);
  100672. this._linesPositions.push(p0.x);
  100673. this._linesPositions.push(p0.y);
  100674. this._linesPositions.push(p0.z);
  100675. this._linesPositions.push(p1.x);
  100676. this._linesPositions.push(p1.y);
  100677. this._linesPositions.push(p1.z);
  100678. this._linesPositions.push(p1.x);
  100679. this._linesPositions.push(p1.y);
  100680. this._linesPositions.push(p1.z);
  100681. // Normals
  100682. this._linesNormals.push(p1.x);
  100683. this._linesNormals.push(p1.y);
  100684. this._linesNormals.push(p1.z);
  100685. this._linesNormals.push(-1);
  100686. this._linesNormals.push(p1.x);
  100687. this._linesNormals.push(p1.y);
  100688. this._linesNormals.push(p1.z);
  100689. this._linesNormals.push(1);
  100690. this._linesNormals.push(p0.x);
  100691. this._linesNormals.push(p0.y);
  100692. this._linesNormals.push(p0.z);
  100693. this._linesNormals.push(-1);
  100694. this._linesNormals.push(p0.x);
  100695. this._linesNormals.push(p0.y);
  100696. this._linesNormals.push(p0.z);
  100697. this._linesNormals.push(1);
  100698. // Indices
  100699. this._linesIndices.push(offset);
  100700. this._linesIndices.push(offset + 1);
  100701. this._linesIndices.push(offset + 2);
  100702. this._linesIndices.push(offset);
  100703. this._linesIndices.push(offset + 2);
  100704. this._linesIndices.push(offset + 3);
  100705. };
  100706. /**
  100707. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  100708. */
  100709. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  100710. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  100711. var indices = this._source.getIndices();
  100712. if (!indices || !positions) {
  100713. return;
  100714. }
  100715. // First let's find adjacencies
  100716. var adjacencies = new Array();
  100717. var faceNormals = new Array();
  100718. var index;
  100719. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  100720. var currentAdjecancy = new FaceAdjacencies();
  100721. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  100722. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  100723. adjacencies.push(currentAdjecancy);
  100724. }
  100725. // Create lines
  100726. for (index = 0; index < adjacencies.length; index++) {
  100727. // 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
  100728. var current = adjacencies[index];
  100729. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  100730. }
  100731. // Merge into a single mesh
  100732. var engine = this._source.getScene().getEngine();
  100733. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  100734. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  100735. this._ib = engine.createIndexBuffer(this._linesIndices);
  100736. this._indicesCount = this._linesIndices.length;
  100737. };
  100738. return LineEdgesRenderer;
  100739. }(BABYLON.EdgesRenderer));
  100740. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  100741. })(BABYLON || (BABYLON = {}));
  100742. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  100743. var BABYLON;
  100744. (function (BABYLON) {
  100745. // Adds the parser to the scene parsers.
  100746. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  100747. if (parsedData.effectLayers) {
  100748. if (!container.effectLayers) {
  100749. container.effectLayers = new Array();
  100750. }
  100751. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  100752. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  100753. container.effectLayers.push(effectLayer);
  100754. }
  100755. }
  100756. });
  100757. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  100758. var index = this.effectLayers.indexOf(toRemove);
  100759. if (index !== -1) {
  100760. this.effectLayers.splice(index, 1);
  100761. }
  100762. return index;
  100763. };
  100764. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  100765. this.effectLayers.push(newEffectLayer);
  100766. };
  100767. /**
  100768. * Defines the layer scene component responsible to manage any effect layers
  100769. * in a given scene.
  100770. */
  100771. var EffectLayerSceneComponent = /** @class */ (function () {
  100772. /**
  100773. * Creates a new instance of the component for the given scene
  100774. * @param scene Defines the scene to register the component in
  100775. */
  100776. function EffectLayerSceneComponent(scene) {
  100777. /**
  100778. * The component name helpfull to identify the component in the list of scene components.
  100779. */
  100780. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  100781. this._renderEffects = false;
  100782. this._needStencil = false;
  100783. this._previousStencilState = false;
  100784. this.scene = scene;
  100785. this._engine = scene.getEngine();
  100786. scene.effectLayers = new Array();
  100787. }
  100788. /**
  100789. * Registers the component in a given scene
  100790. */
  100791. EffectLayerSceneComponent.prototype.register = function () {
  100792. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  100793. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  100794. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  100795. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  100796. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  100797. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  100798. };
  100799. /**
  100800. * Rebuilds the elements related to this component in case of
  100801. * context lost for instance.
  100802. */
  100803. EffectLayerSceneComponent.prototype.rebuild = function () {
  100804. var layers = this.scene.effectLayers;
  100805. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  100806. var effectLayer = layers_1[_i];
  100807. effectLayer._rebuild();
  100808. }
  100809. };
  100810. /**
  100811. * Serializes the component data to the specified json object
  100812. * @param serializationObject The object to serialize to
  100813. */
  100814. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  100815. // Effect layers
  100816. serializationObject.effectLayers = [];
  100817. var layers = this.scene.effectLayers;
  100818. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  100819. var effectLayer = layers_2[_i];
  100820. if (effectLayer.serialize) {
  100821. serializationObject.effectLayers.push(effectLayer.serialize());
  100822. }
  100823. }
  100824. };
  100825. /**
  100826. * Adds all the element from the container to the scene
  100827. * @param container the container holding the elements
  100828. */
  100829. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  100830. var _this = this;
  100831. if (!container.effectLayers) {
  100832. return;
  100833. }
  100834. container.effectLayers.forEach(function (o) {
  100835. _this.scene.addEffectLayer(o);
  100836. });
  100837. };
  100838. /**
  100839. * Removes all the elements in the container from the scene
  100840. * @param container contains the elements to remove
  100841. */
  100842. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  100843. var _this = this;
  100844. if (!container.effectLayers) {
  100845. return;
  100846. }
  100847. container.effectLayers.forEach(function (o) {
  100848. _this.scene.removeEffectLayer(o);
  100849. });
  100850. };
  100851. /**
  100852. * Disposes the component and the associated ressources.
  100853. */
  100854. EffectLayerSceneComponent.prototype.dispose = function () {
  100855. var layers = this.scene.effectLayers;
  100856. while (layers.length) {
  100857. layers[0].dispose();
  100858. }
  100859. };
  100860. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  100861. var layers = this.scene.effectLayers;
  100862. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  100863. var layer = layers_3[_i];
  100864. if (!layer.hasMesh(mesh)) {
  100865. continue;
  100866. }
  100867. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  100868. var subMesh = _b[_a];
  100869. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  100870. return false;
  100871. }
  100872. }
  100873. }
  100874. return true;
  100875. };
  100876. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  100877. this._renderEffects = false;
  100878. this._needStencil = false;
  100879. var layers = this.scene.effectLayers;
  100880. if (layers && layers.length > 0) {
  100881. this._previousStencilState = this._engine.getStencilBuffer();
  100882. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  100883. var effectLayer = layers_4[_i];
  100884. if (effectLayer.shouldRender() &&
  100885. (!effectLayer.camera ||
  100886. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  100887. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  100888. this._renderEffects = true;
  100889. this._needStencil = this._needStencil || effectLayer.needStencil();
  100890. var renderTarget = effectLayer._mainTexture;
  100891. if (renderTarget._shouldRender()) {
  100892. this.scene.incrementRenderId();
  100893. renderTarget.render(false, false);
  100894. }
  100895. }
  100896. }
  100897. this.scene.incrementRenderId();
  100898. }
  100899. };
  100900. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  100901. // Activate effect Layer stencil
  100902. if (this._needStencil) {
  100903. this._engine.setStencilBuffer(true);
  100904. }
  100905. };
  100906. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  100907. // Restore effect Layer stencil
  100908. if (this._needStencil) {
  100909. this._engine.setStencilBuffer(this._previousStencilState);
  100910. }
  100911. };
  100912. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  100913. if (this._renderEffects) {
  100914. this._engine.setDepthBuffer(false);
  100915. var layers = this.scene.effectLayers;
  100916. for (var i = 0; i < layers.length; i++) {
  100917. var effectLayer = layers[i];
  100918. if (effectLayer.renderingGroupId === renderingGroupId) {
  100919. if (effectLayer.shouldRender()) {
  100920. effectLayer.render();
  100921. }
  100922. }
  100923. }
  100924. this._engine.setDepthBuffer(true);
  100925. }
  100926. };
  100927. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  100928. if (this._renderEffects) {
  100929. this._draw(-1);
  100930. }
  100931. };
  100932. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  100933. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  100934. this._draw(index);
  100935. }
  100936. };
  100937. return EffectLayerSceneComponent;
  100938. }());
  100939. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  100940. })(BABYLON || (BABYLON = {}));
  100941. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  100942. var __assign = (this && this.__assign) || function () {
  100943. __assign = Object.assign || function(t) {
  100944. for (var s, i = 1, n = arguments.length; i < n; i++) {
  100945. s = arguments[i];
  100946. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  100947. t[p] = s[p];
  100948. }
  100949. return t;
  100950. };
  100951. return __assign.apply(this, arguments);
  100952. };
  100953. var BABYLON;
  100954. (function (BABYLON) {
  100955. /**
  100956. * The effect layer Helps adding post process effect blended with the main pass.
  100957. *
  100958. * This can be for instance use to generate glow or higlight effects on the scene.
  100959. *
  100960. * The effect layer class can not be used directly and is intented to inherited from to be
  100961. * customized per effects.
  100962. */
  100963. var EffectLayer = /** @class */ (function () {
  100964. /**
  100965. * Instantiates a new effect Layer and references it in the scene.
  100966. * @param name The name of the layer
  100967. * @param scene The scene to use the layer in
  100968. */
  100969. function EffectLayer(
  100970. /** The Friendly of the effect in the scene */
  100971. name, scene) {
  100972. this._vertexBuffers = {};
  100973. this._maxSize = 0;
  100974. this._mainTextureDesiredSize = { width: 0, height: 0 };
  100975. this._shouldRender = true;
  100976. this._postProcesses = [];
  100977. this._textures = [];
  100978. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  100979. /**
  100980. * The clear color of the texture used to generate the glow map.
  100981. */
  100982. this.neutralColor = new BABYLON.Color4();
  100983. /**
  100984. * Specifies wether the highlight layer is enabled or not.
  100985. */
  100986. this.isEnabled = true;
  100987. /**
  100988. * An event triggered when the effect layer has been disposed.
  100989. */
  100990. this.onDisposeObservable = new BABYLON.Observable();
  100991. /**
  100992. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  100993. */
  100994. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  100995. /**
  100996. * An event triggered when the generated texture is being merged in the scene.
  100997. */
  100998. this.onBeforeComposeObservable = new BABYLON.Observable();
  100999. /**
  101000. * An event triggered when the generated texture has been merged in the scene.
  101001. */
  101002. this.onAfterComposeObservable = new BABYLON.Observable();
  101003. /**
  101004. * An event triggered when the efffect layer changes its size.
  101005. */
  101006. this.onSizeChangedObservable = new BABYLON.Observable();
  101007. this.name = name;
  101008. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  101009. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  101010. if (!component) {
  101011. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  101012. this._scene._addComponent(component);
  101013. }
  101014. this._engine = this._scene.getEngine();
  101015. this._maxSize = this._engine.getCaps().maxTextureSize;
  101016. this._scene.effectLayers.push(this);
  101017. // Generate Buffers
  101018. this._generateIndexBuffer();
  101019. this._genrateVertexBuffer();
  101020. }
  101021. Object.defineProperty(EffectLayer.prototype, "camera", {
  101022. /**
  101023. * Gets the camera attached to the layer.
  101024. */
  101025. get: function () {
  101026. return this._effectLayerOptions.camera;
  101027. },
  101028. enumerable: true,
  101029. configurable: true
  101030. });
  101031. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  101032. /**
  101033. * Gets the rendering group id the layer should render in.
  101034. */
  101035. get: function () {
  101036. return this._effectLayerOptions.renderingGroupId;
  101037. },
  101038. enumerable: true,
  101039. configurable: true
  101040. });
  101041. /**
  101042. * Initializes the effect layer with the required options.
  101043. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  101044. */
  101045. EffectLayer.prototype._init = function (options) {
  101046. // Adapt options
  101047. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  101048. this._setMainTextureSize();
  101049. this._createMainTexture();
  101050. this._createTextureAndPostProcesses();
  101051. this._mergeEffect = this._createMergeEffect();
  101052. };
  101053. /**
  101054. * Generates the index buffer of the full screen quad blending to the main canvas.
  101055. */
  101056. EffectLayer.prototype._generateIndexBuffer = function () {
  101057. // Indices
  101058. var indices = [];
  101059. indices.push(0);
  101060. indices.push(1);
  101061. indices.push(2);
  101062. indices.push(0);
  101063. indices.push(2);
  101064. indices.push(3);
  101065. this._indexBuffer = this._engine.createIndexBuffer(indices);
  101066. };
  101067. /**
  101068. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  101069. */
  101070. EffectLayer.prototype._genrateVertexBuffer = function () {
  101071. // VBO
  101072. var vertices = [];
  101073. vertices.push(1, 1);
  101074. vertices.push(-1, 1);
  101075. vertices.push(-1, -1);
  101076. vertices.push(1, -1);
  101077. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  101078. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  101079. };
  101080. /**
  101081. * Sets the main texture desired size which is the closest power of two
  101082. * of the engine canvas size.
  101083. */
  101084. EffectLayer.prototype._setMainTextureSize = function () {
  101085. if (this._effectLayerOptions.mainTextureFixedSize) {
  101086. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  101087. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  101088. }
  101089. else {
  101090. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  101091. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  101092. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  101093. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  101094. }
  101095. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  101096. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  101097. };
  101098. /**
  101099. * Creates the main texture for the effect layer.
  101100. */
  101101. EffectLayer.prototype._createMainTexture = function () {
  101102. var _this = this;
  101103. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  101104. width: this._mainTextureDesiredSize.width,
  101105. height: this._mainTextureDesiredSize.height
  101106. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  101107. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  101108. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101109. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101110. this._mainTexture.anisotropicFilteringLevel = 1;
  101111. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101112. this._mainTexture.renderParticles = false;
  101113. this._mainTexture.renderList = null;
  101114. this._mainTexture.ignoreCameraViewport = true;
  101115. // Custom render function
  101116. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  101117. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  101118. var index;
  101119. var engine = _this._scene.getEngine();
  101120. if (depthOnlySubMeshes.length) {
  101121. engine.setColorWrite(false);
  101122. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  101123. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  101124. }
  101125. engine.setColorWrite(true);
  101126. }
  101127. for (index = 0; index < opaqueSubMeshes.length; index++) {
  101128. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  101129. }
  101130. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  101131. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  101132. }
  101133. for (index = 0; index < transparentSubMeshes.length; index++) {
  101134. _this._renderSubMesh(transparentSubMeshes.data[index]);
  101135. }
  101136. };
  101137. this._mainTexture.onClearObservable.add(function (engine) {
  101138. engine.clear(_this.neutralColor, true, true, true);
  101139. });
  101140. };
  101141. /**
  101142. * Checks for the readiness of the element composing the layer.
  101143. * @param subMesh the mesh to check for
  101144. * @param useInstances specify wether or not to use instances to render the mesh
  101145. * @param emissiveTexture the associated emissive texture used to generate the glow
  101146. * @return true if ready otherwise, false
  101147. */
  101148. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  101149. var material = subMesh.getMaterial();
  101150. if (!material) {
  101151. return false;
  101152. }
  101153. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  101154. return false;
  101155. }
  101156. var defines = [];
  101157. var attribs = [BABYLON.VertexBuffer.PositionKind];
  101158. var mesh = subMesh.getMesh();
  101159. var uv1 = false;
  101160. var uv2 = false;
  101161. // Alpha test
  101162. if (material && material.needAlphaTesting()) {
  101163. var alphaTexture = material.getAlphaTestTexture();
  101164. if (alphaTexture) {
  101165. defines.push("#define ALPHATEST");
  101166. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  101167. alphaTexture.coordinatesIndex === 1) {
  101168. defines.push("#define DIFFUSEUV2");
  101169. uv2 = true;
  101170. }
  101171. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  101172. defines.push("#define DIFFUSEUV1");
  101173. uv1 = true;
  101174. }
  101175. }
  101176. }
  101177. // Emissive
  101178. if (emissiveTexture) {
  101179. defines.push("#define EMISSIVE");
  101180. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  101181. emissiveTexture.coordinatesIndex === 1) {
  101182. defines.push("#define EMISSIVEUV2");
  101183. uv2 = true;
  101184. }
  101185. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  101186. defines.push("#define EMISSIVEUV1");
  101187. uv1 = true;
  101188. }
  101189. }
  101190. if (uv1) {
  101191. attribs.push(BABYLON.VertexBuffer.UVKind);
  101192. defines.push("#define UV1");
  101193. }
  101194. if (uv2) {
  101195. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  101196. defines.push("#define UV2");
  101197. }
  101198. // Bones
  101199. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  101200. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  101201. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  101202. if (mesh.numBoneInfluencers > 4) {
  101203. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  101204. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  101205. }
  101206. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  101207. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  101208. }
  101209. else {
  101210. defines.push("#define NUM_BONE_INFLUENCERS 0");
  101211. }
  101212. // Morph targets
  101213. var manager = mesh.morphTargetManager;
  101214. var morphInfluencers = 0;
  101215. if (manager) {
  101216. if (manager.numInfluencers > 0) {
  101217. defines.push("#define MORPHTARGETS");
  101218. morphInfluencers = manager.numInfluencers;
  101219. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  101220. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  101221. }
  101222. }
  101223. // Instances
  101224. if (useInstances) {
  101225. defines.push("#define INSTANCES");
  101226. attribs.push("world0");
  101227. attribs.push("world1");
  101228. attribs.push("world2");
  101229. attribs.push("world3");
  101230. }
  101231. // Get correct effect
  101232. var join = defines.join("\n");
  101233. if (this._cachedDefines !== join) {
  101234. this._cachedDefines = join;
  101235. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  101236. }
  101237. return this._effectLayerMapGenerationEffect.isReady();
  101238. };
  101239. /**
  101240. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  101241. */
  101242. EffectLayer.prototype.render = function () {
  101243. var currentEffect = this._mergeEffect;
  101244. // Check
  101245. if (!currentEffect.isReady())
  101246. return;
  101247. for (var i = 0; i < this._postProcesses.length; i++) {
  101248. if (!this._postProcesses[i].isReady()) {
  101249. return;
  101250. }
  101251. }
  101252. var engine = this._scene.getEngine();
  101253. this.onBeforeComposeObservable.notifyObservers(this);
  101254. // Render
  101255. engine.enableEffect(currentEffect);
  101256. engine.setState(false);
  101257. // VBOs
  101258. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  101259. // Cache
  101260. var previousAlphaMode = engine.getAlphaMode();
  101261. // Go Blend.
  101262. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  101263. // Blends the map on the main canvas.
  101264. this._internalRender(currentEffect);
  101265. // Restore Alpha
  101266. engine.setAlphaMode(previousAlphaMode);
  101267. this.onAfterComposeObservable.notifyObservers(this);
  101268. // Handle size changes.
  101269. var size = this._mainTexture.getSize();
  101270. this._setMainTextureSize();
  101271. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  101272. // Recreate RTT and post processes on size change.
  101273. this.onSizeChangedObservable.notifyObservers(this);
  101274. this._disposeTextureAndPostProcesses();
  101275. this._createMainTexture();
  101276. this._createTextureAndPostProcesses();
  101277. }
  101278. };
  101279. /**
  101280. * Determine if a given mesh will be used in the current effect.
  101281. * @param mesh mesh to test
  101282. * @returns true if the mesh will be used
  101283. */
  101284. EffectLayer.prototype.hasMesh = function (mesh) {
  101285. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  101286. return true;
  101287. }
  101288. return false;
  101289. };
  101290. /**
  101291. * Returns true if the layer contains information to display, otherwise false.
  101292. * @returns true if the glow layer should be rendered
  101293. */
  101294. EffectLayer.prototype.shouldRender = function () {
  101295. return this.isEnabled && this._shouldRender;
  101296. };
  101297. /**
  101298. * Returns true if the mesh should render, otherwise false.
  101299. * @param mesh The mesh to render
  101300. * @returns true if it should render otherwise false
  101301. */
  101302. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  101303. return true;
  101304. };
  101305. /**
  101306. * Returns true if the mesh should render, otherwise false.
  101307. * @param mesh The mesh to render
  101308. * @returns true if it should render otherwise false
  101309. */
  101310. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  101311. return true;
  101312. };
  101313. /**
  101314. * Renders the submesh passed in parameter to the generation map.
  101315. */
  101316. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  101317. var _this = this;
  101318. if (!this.shouldRender()) {
  101319. return;
  101320. }
  101321. var material = subMesh.getMaterial();
  101322. var mesh = subMesh.getRenderingMesh();
  101323. var scene = this._scene;
  101324. var engine = scene.getEngine();
  101325. if (!material) {
  101326. return;
  101327. }
  101328. // Do not block in blend mode.
  101329. if (material.needAlphaBlendingForMesh(mesh)) {
  101330. return;
  101331. }
  101332. // Culling
  101333. engine.setState(material.backFaceCulling);
  101334. // Managing instances
  101335. var batch = mesh._getInstancesRenderList(subMesh._id);
  101336. if (batch.mustReturn) {
  101337. return;
  101338. }
  101339. // Early Exit per mesh
  101340. if (!this._shouldRenderMesh(mesh)) {
  101341. return;
  101342. }
  101343. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  101344. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  101345. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  101346. engine.enableEffect(this._effectLayerMapGenerationEffect);
  101347. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  101348. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  101349. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  101350. // Alpha test
  101351. if (material && material.needAlphaTesting()) {
  101352. var alphaTexture = material.getAlphaTestTexture();
  101353. if (alphaTexture) {
  101354. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  101355. var textureMatrix = alphaTexture.getTextureMatrix();
  101356. if (textureMatrix) {
  101357. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  101358. }
  101359. }
  101360. }
  101361. // Glow emissive only
  101362. if (this._emissiveTextureAndColor.texture) {
  101363. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  101364. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  101365. }
  101366. // Bones
  101367. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  101368. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  101369. }
  101370. // Morph targets
  101371. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  101372. // Draw
  101373. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  101374. }
  101375. else {
  101376. // Need to reset refresh rate of the main map
  101377. this._mainTexture.resetRefreshCounter();
  101378. }
  101379. };
  101380. /**
  101381. * Rebuild the required buffers.
  101382. * @hidden Internal use only.
  101383. */
  101384. EffectLayer.prototype._rebuild = function () {
  101385. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  101386. if (vb) {
  101387. vb._rebuild();
  101388. }
  101389. this._generateIndexBuffer();
  101390. };
  101391. /**
  101392. * Dispose only the render target textures and post process.
  101393. */
  101394. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  101395. this._mainTexture.dispose();
  101396. for (var i = 0; i < this._postProcesses.length; i++) {
  101397. if (this._postProcesses[i]) {
  101398. this._postProcesses[i].dispose();
  101399. }
  101400. }
  101401. this._postProcesses = [];
  101402. for (var i = 0; i < this._textures.length; i++) {
  101403. if (this._textures[i]) {
  101404. this._textures[i].dispose();
  101405. }
  101406. }
  101407. this._textures = [];
  101408. };
  101409. /**
  101410. * Dispose the highlight layer and free resources.
  101411. */
  101412. EffectLayer.prototype.dispose = function () {
  101413. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  101414. if (vertexBuffer) {
  101415. vertexBuffer.dispose();
  101416. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  101417. }
  101418. if (this._indexBuffer) {
  101419. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  101420. this._indexBuffer = null;
  101421. }
  101422. // Clean textures and post processes
  101423. this._disposeTextureAndPostProcesses();
  101424. // Remove from scene
  101425. var index = this._scene.effectLayers.indexOf(this, 0);
  101426. if (index > -1) {
  101427. this._scene.effectLayers.splice(index, 1);
  101428. }
  101429. // Callback
  101430. this.onDisposeObservable.notifyObservers(this);
  101431. this.onDisposeObservable.clear();
  101432. this.onBeforeRenderMainTextureObservable.clear();
  101433. this.onBeforeComposeObservable.clear();
  101434. this.onAfterComposeObservable.clear();
  101435. this.onSizeChangedObservable.clear();
  101436. };
  101437. /**
  101438. * Gets the class name of the effect layer
  101439. * @returns the string with the class name of the effect layer
  101440. */
  101441. EffectLayer.prototype.getClassName = function () {
  101442. return "EffectLayer";
  101443. };
  101444. /**
  101445. * Creates an effect layer from parsed effect layer data
  101446. * @param parsedEffectLayer defines effect layer data
  101447. * @param scene defines the current scene
  101448. * @param rootUrl defines the root URL containing the effect layer information
  101449. * @returns a parsed effect Layer
  101450. */
  101451. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  101452. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  101453. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  101454. };
  101455. __decorate([
  101456. BABYLON.serialize()
  101457. ], EffectLayer.prototype, "name", void 0);
  101458. __decorate([
  101459. BABYLON.serializeAsColor4()
  101460. ], EffectLayer.prototype, "neutralColor", void 0);
  101461. __decorate([
  101462. BABYLON.serialize()
  101463. ], EffectLayer.prototype, "isEnabled", void 0);
  101464. __decorate([
  101465. BABYLON.serializeAsCameraReference()
  101466. ], EffectLayer.prototype, "camera", null);
  101467. __decorate([
  101468. BABYLON.serialize()
  101469. ], EffectLayer.prototype, "renderingGroupId", null);
  101470. return EffectLayer;
  101471. }());
  101472. BABYLON.EffectLayer = EffectLayer;
  101473. })(BABYLON || (BABYLON = {}));
  101474. //# sourceMappingURL=babylon.effectLayer.js.map
  101475. var BABYLON;
  101476. (function (BABYLON) {
  101477. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  101478. for (var index = 0; index < this.effectLayers.length; index++) {
  101479. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  101480. return this.effectLayers[index];
  101481. }
  101482. }
  101483. return null;
  101484. };
  101485. /**
  101486. * Special Glow Blur post process only blurring the alpha channel
  101487. * It enforces keeping the most luminous color in the color channel.
  101488. */
  101489. var GlowBlurPostProcess = /** @class */ (function (_super) {
  101490. __extends(GlowBlurPostProcess, _super);
  101491. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  101492. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  101493. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  101494. _this.direction = direction;
  101495. _this.kernel = kernel;
  101496. _this.onApplyObservable.add(function (effect) {
  101497. effect.setFloat2("screenSize", _this.width, _this.height);
  101498. effect.setVector2("direction", _this.direction);
  101499. effect.setFloat("blurWidth", _this.kernel);
  101500. });
  101501. return _this;
  101502. }
  101503. return GlowBlurPostProcess;
  101504. }(BABYLON.PostProcess));
  101505. /**
  101506. * The highlight layer Helps adding a glow effect around a mesh.
  101507. *
  101508. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  101509. * glowy meshes to your scene.
  101510. *
  101511. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  101512. */
  101513. var HighlightLayer = /** @class */ (function (_super) {
  101514. __extends(HighlightLayer, _super);
  101515. /**
  101516. * Instantiates a new highlight Layer and references it to the scene..
  101517. * @param name The name of the layer
  101518. * @param scene The scene to use the layer in
  101519. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  101520. */
  101521. function HighlightLayer(name, scene, options) {
  101522. var _this = _super.call(this, name, scene) || this;
  101523. _this.name = name;
  101524. /**
  101525. * Specifies whether or not the inner glow is ACTIVE in the layer.
  101526. */
  101527. _this.innerGlow = true;
  101528. /**
  101529. * Specifies whether or not the outer glow is ACTIVE in the layer.
  101530. */
  101531. _this.outerGlow = true;
  101532. /**
  101533. * An event triggered when the highlight layer is being blurred.
  101534. */
  101535. _this.onBeforeBlurObservable = new BABYLON.Observable();
  101536. /**
  101537. * An event triggered when the highlight layer has been blurred.
  101538. */
  101539. _this.onAfterBlurObservable = new BABYLON.Observable();
  101540. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  101541. _this._meshes = {};
  101542. _this._excludedMeshes = {};
  101543. _this.neutralColor = HighlightLayer.NeutralColor;
  101544. // Warn on stencil
  101545. if (!_this._engine.isStencilEnable) {
  101546. 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 }");
  101547. }
  101548. // Adapt options
  101549. _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);
  101550. // Initialize the layer
  101551. _this._init({
  101552. alphaBlendingMode: _this._options.alphaBlendingMode,
  101553. camera: _this._options.camera,
  101554. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  101555. mainTextureRatio: _this._options.mainTextureRatio,
  101556. renderingGroupId: _this._options.renderingGroupId
  101557. });
  101558. // Do not render as long as no meshes have been added
  101559. _this._shouldRender = false;
  101560. return _this;
  101561. }
  101562. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  101563. /**
  101564. * Gets the horizontal size of the blur.
  101565. */
  101566. get: function () {
  101567. return this._horizontalBlurPostprocess.kernel;
  101568. },
  101569. /**
  101570. * Specifies the horizontal size of the blur.
  101571. */
  101572. set: function (value) {
  101573. this._horizontalBlurPostprocess.kernel = value;
  101574. },
  101575. enumerable: true,
  101576. configurable: true
  101577. });
  101578. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  101579. /**
  101580. * Gets the vertical size of the blur.
  101581. */
  101582. get: function () {
  101583. return this._verticalBlurPostprocess.kernel;
  101584. },
  101585. /**
  101586. * Specifies the vertical size of the blur.
  101587. */
  101588. set: function (value) {
  101589. this._verticalBlurPostprocess.kernel = value;
  101590. },
  101591. enumerable: true,
  101592. configurable: true
  101593. });
  101594. /**
  101595. * Get the effect name of the layer.
  101596. * @return The effect name
  101597. */
  101598. HighlightLayer.prototype.getEffectName = function () {
  101599. return HighlightLayer.EffectName;
  101600. };
  101601. /**
  101602. * Create the merge effect. This is the shader use to blit the information back
  101603. * to the main canvas at the end of the scene rendering.
  101604. */
  101605. HighlightLayer.prototype._createMergeEffect = function () {
  101606. // Effect
  101607. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  101608. };
  101609. /**
  101610. * Creates the render target textures and post processes used in the highlight layer.
  101611. */
  101612. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  101613. var _this = this;
  101614. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  101615. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  101616. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  101617. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  101618. var textureType = 0;
  101619. if (this._engine.getCaps().textureHalfFloatRender) {
  101620. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  101621. }
  101622. else {
  101623. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101624. }
  101625. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  101626. width: blurTextureWidth,
  101627. height: blurTextureHeight
  101628. }, this._scene, false, true, textureType);
  101629. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101630. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101631. this._blurTexture.anisotropicFilteringLevel = 16;
  101632. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  101633. this._blurTexture.renderParticles = false;
  101634. this._blurTexture.ignoreCameraViewport = true;
  101635. this._textures = [this._blurTexture];
  101636. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  101637. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  101638. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  101639. effect.setTexture("textureSampler", _this._mainTexture);
  101640. });
  101641. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  101642. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  101643. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  101644. });
  101645. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  101646. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  101647. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  101648. });
  101649. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  101650. }
  101651. else {
  101652. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  101653. width: blurTextureWidth,
  101654. height: blurTextureHeight
  101655. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101656. this._horizontalBlurPostprocess.width = blurTextureWidth;
  101657. this._horizontalBlurPostprocess.height = blurTextureHeight;
  101658. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  101659. effect.setTexture("textureSampler", _this._mainTexture);
  101660. });
  101661. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  101662. width: blurTextureWidth,
  101663. height: blurTextureHeight
  101664. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101665. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  101666. }
  101667. this._mainTexture.onAfterUnbindObservable.add(function () {
  101668. _this.onBeforeBlurObservable.notifyObservers(_this);
  101669. var internalTexture = _this._blurTexture.getInternalTexture();
  101670. if (internalTexture) {
  101671. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  101672. }
  101673. _this.onAfterBlurObservable.notifyObservers(_this);
  101674. });
  101675. // Prevent autoClear.
  101676. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  101677. };
  101678. /**
  101679. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  101680. */
  101681. HighlightLayer.prototype.needStencil = function () {
  101682. return true;
  101683. };
  101684. /**
  101685. * Checks for the readiness of the element composing the layer.
  101686. * @param subMesh the mesh to check for
  101687. * @param useInstances specify wether or not to use instances to render the mesh
  101688. * @param emissiveTexture the associated emissive texture used to generate the glow
  101689. * @return true if ready otherwise, false
  101690. */
  101691. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  101692. var material = subMesh.getMaterial();
  101693. var mesh = subMesh.getRenderingMesh();
  101694. if (!material || !mesh || !this._meshes) {
  101695. return false;
  101696. }
  101697. var emissiveTexture = null;
  101698. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  101699. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  101700. emissiveTexture = material.emissiveTexture;
  101701. }
  101702. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  101703. };
  101704. /**
  101705. * Implementation specific of rendering the generating effect on the main canvas.
  101706. * @param effect The effect used to render through
  101707. */
  101708. HighlightLayer.prototype._internalRender = function (effect) {
  101709. // Texture
  101710. effect.setTexture("textureSampler", this._blurTexture);
  101711. // Cache
  101712. var engine = this._engine;
  101713. var previousStencilBuffer = engine.getStencilBuffer();
  101714. var previousStencilFunction = engine.getStencilFunction();
  101715. var previousStencilMask = engine.getStencilMask();
  101716. var previousStencilOperationPass = engine.getStencilOperationPass();
  101717. var previousStencilOperationFail = engine.getStencilOperationFail();
  101718. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  101719. var previousStencilReference = engine.getStencilFunctionReference();
  101720. // Stencil operations
  101721. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  101722. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  101723. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  101724. // Draw order
  101725. engine.setStencilMask(0x00);
  101726. engine.setStencilBuffer(true);
  101727. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  101728. // 2 passes inner outer
  101729. if (this.outerGlow) {
  101730. effect.setFloat("offset", 0);
  101731. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  101732. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  101733. }
  101734. if (this.innerGlow) {
  101735. effect.setFloat("offset", 1);
  101736. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  101737. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  101738. }
  101739. // Restore Cache
  101740. engine.setStencilFunction(previousStencilFunction);
  101741. engine.setStencilMask(previousStencilMask);
  101742. engine.setStencilBuffer(previousStencilBuffer);
  101743. engine.setStencilOperationPass(previousStencilOperationPass);
  101744. engine.setStencilOperationFail(previousStencilOperationFail);
  101745. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  101746. engine.setStencilFunctionReference(previousStencilReference);
  101747. };
  101748. /**
  101749. * Returns true if the layer contains information to display, otherwise false.
  101750. */
  101751. HighlightLayer.prototype.shouldRender = function () {
  101752. if (_super.prototype.shouldRender.call(this)) {
  101753. return this._meshes ? true : false;
  101754. }
  101755. return false;
  101756. };
  101757. /**
  101758. * Returns true if the mesh should render, otherwise false.
  101759. * @param mesh The mesh to render
  101760. * @returns true if it should render otherwise false
  101761. */
  101762. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  101763. // Excluded Mesh
  101764. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  101765. return false;
  101766. }
  101767. ;
  101768. if (!_super.prototype.hasMesh.call(this, mesh)) {
  101769. return false;
  101770. }
  101771. return true;
  101772. };
  101773. /**
  101774. * Sets the required values for both the emissive texture and and the main color.
  101775. */
  101776. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  101777. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  101778. if (highlightLayerMesh) {
  101779. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  101780. }
  101781. else {
  101782. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  101783. }
  101784. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  101785. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  101786. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  101787. }
  101788. else {
  101789. this._emissiveTextureAndColor.texture = null;
  101790. }
  101791. };
  101792. /**
  101793. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  101794. * @param mesh The mesh to exclude from the highlight layer
  101795. */
  101796. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  101797. if (!this._excludedMeshes) {
  101798. return;
  101799. }
  101800. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  101801. if (!meshExcluded) {
  101802. this._excludedMeshes[mesh.uniqueId] = {
  101803. mesh: mesh,
  101804. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  101805. mesh.getEngine().setStencilBuffer(false);
  101806. }),
  101807. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  101808. mesh.getEngine().setStencilBuffer(true);
  101809. }),
  101810. };
  101811. }
  101812. };
  101813. /**
  101814. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  101815. * @param mesh The mesh to highlight
  101816. */
  101817. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  101818. if (!this._excludedMeshes) {
  101819. return;
  101820. }
  101821. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  101822. if (meshExcluded) {
  101823. if (meshExcluded.beforeRender) {
  101824. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  101825. }
  101826. if (meshExcluded.afterRender) {
  101827. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  101828. }
  101829. }
  101830. this._excludedMeshes[mesh.uniqueId] = null;
  101831. };
  101832. /**
  101833. * Determine if a given mesh will be highlighted by the current HighlightLayer
  101834. * @param mesh mesh to test
  101835. * @returns true if the mesh will be highlighted by the current HighlightLayer
  101836. */
  101837. HighlightLayer.prototype.hasMesh = function (mesh) {
  101838. if (!this._meshes) {
  101839. return false;
  101840. }
  101841. if (!_super.prototype.hasMesh.call(this, mesh)) {
  101842. return false;
  101843. }
  101844. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  101845. };
  101846. /**
  101847. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  101848. * @param mesh The mesh to highlight
  101849. * @param color The color of the highlight
  101850. * @param glowEmissiveOnly Extract the glow from the emissive texture
  101851. */
  101852. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  101853. var _this = this;
  101854. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  101855. if (!this._meshes) {
  101856. return;
  101857. }
  101858. var meshHighlight = this._meshes[mesh.uniqueId];
  101859. if (meshHighlight) {
  101860. meshHighlight.color = color;
  101861. }
  101862. else {
  101863. this._meshes[mesh.uniqueId] = {
  101864. mesh: mesh,
  101865. color: color,
  101866. // Lambda required for capture due to Observable this context
  101867. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  101868. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  101869. _this._defaultStencilReference(mesh);
  101870. }
  101871. else {
  101872. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  101873. }
  101874. }),
  101875. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  101876. glowEmissiveOnly: glowEmissiveOnly
  101877. };
  101878. mesh.onDisposeObservable.add(function () {
  101879. _this._disposeMesh(mesh);
  101880. });
  101881. }
  101882. this._shouldRender = true;
  101883. };
  101884. /**
  101885. * Remove a mesh from the highlight layer in order to make it stop glowing.
  101886. * @param mesh The mesh to highlight
  101887. */
  101888. HighlightLayer.prototype.removeMesh = function (mesh) {
  101889. if (!this._meshes) {
  101890. return;
  101891. }
  101892. var meshHighlight = this._meshes[mesh.uniqueId];
  101893. if (meshHighlight) {
  101894. if (meshHighlight.observerHighlight) {
  101895. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  101896. }
  101897. if (meshHighlight.observerDefault) {
  101898. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  101899. }
  101900. delete this._meshes[mesh.uniqueId];
  101901. }
  101902. this._shouldRender = false;
  101903. for (var meshHighlightToCheck in this._meshes) {
  101904. if (this._meshes[meshHighlightToCheck]) {
  101905. this._shouldRender = true;
  101906. break;
  101907. }
  101908. }
  101909. };
  101910. /**
  101911. * Force the stencil to the normal expected value for none glowing parts
  101912. */
  101913. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  101914. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  101915. };
  101916. /**
  101917. * Free any resources and references associated to a mesh.
  101918. * Internal use
  101919. * @param mesh The mesh to free.
  101920. * @hidden
  101921. */
  101922. HighlightLayer.prototype._disposeMesh = function (mesh) {
  101923. this.removeMesh(mesh);
  101924. this.removeExcludedMesh(mesh);
  101925. };
  101926. /**
  101927. * Dispose the highlight layer and free resources.
  101928. */
  101929. HighlightLayer.prototype.dispose = function () {
  101930. if (this._meshes) {
  101931. // Clean mesh references
  101932. for (var id in this._meshes) {
  101933. var meshHighlight = this._meshes[id];
  101934. if (meshHighlight && meshHighlight.mesh) {
  101935. if (meshHighlight.observerHighlight) {
  101936. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  101937. }
  101938. if (meshHighlight.observerDefault) {
  101939. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  101940. }
  101941. }
  101942. }
  101943. this._meshes = null;
  101944. }
  101945. if (this._excludedMeshes) {
  101946. for (var id in this._excludedMeshes) {
  101947. var meshHighlight = this._excludedMeshes[id];
  101948. if (meshHighlight) {
  101949. if (meshHighlight.beforeRender) {
  101950. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  101951. }
  101952. if (meshHighlight.afterRender) {
  101953. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  101954. }
  101955. }
  101956. }
  101957. this._excludedMeshes = null;
  101958. }
  101959. _super.prototype.dispose.call(this);
  101960. };
  101961. /**
  101962. * Gets the class name of the effect layer
  101963. * @returns the string with the class name of the effect layer
  101964. */
  101965. HighlightLayer.prototype.getClassName = function () {
  101966. return "HighlightLayer";
  101967. };
  101968. /**
  101969. * Serializes this Highlight layer
  101970. * @returns a serialized Highlight layer object
  101971. */
  101972. HighlightLayer.prototype.serialize = function () {
  101973. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  101974. serializationObject.customType = "BABYLON.HighlightLayer";
  101975. // Highlighted meshes
  101976. serializationObject.meshes = [];
  101977. if (this._meshes) {
  101978. for (var m in this._meshes) {
  101979. var mesh = this._meshes[m];
  101980. if (mesh) {
  101981. serializationObject.meshes.push({
  101982. glowEmissiveOnly: mesh.glowEmissiveOnly,
  101983. color: mesh.color.asArray(),
  101984. meshId: mesh.mesh.id
  101985. });
  101986. }
  101987. }
  101988. }
  101989. // Excluded meshes
  101990. serializationObject.excludedMeshes = [];
  101991. if (this._excludedMeshes) {
  101992. for (var e in this._excludedMeshes) {
  101993. var excludedMesh = this._excludedMeshes[e];
  101994. if (excludedMesh) {
  101995. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  101996. }
  101997. }
  101998. }
  101999. return serializationObject;
  102000. };
  102001. /**
  102002. * Creates a Highlight layer from parsed Highlight layer data
  102003. * @param parsedHightlightLayer defines the Highlight layer data
  102004. * @param scene defines the current scene
  102005. * @param rootUrl defines the root URL containing the Highlight layer information
  102006. * @returns a parsed Highlight layer
  102007. */
  102008. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  102009. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  102010. var index;
  102011. // Excluded meshes
  102012. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  102013. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  102014. if (mesh) {
  102015. hl.addExcludedMesh(mesh);
  102016. }
  102017. }
  102018. // Included meshes
  102019. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  102020. var highlightedMesh = parsedHightlightLayer.meshes[index];
  102021. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  102022. if (mesh) {
  102023. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  102024. }
  102025. }
  102026. return hl;
  102027. };
  102028. /**
  102029. * Effect Name of the highlight layer.
  102030. */
  102031. HighlightLayer.EffectName = "HighlightLayer";
  102032. /**
  102033. * The neutral color used during the preparation of the glow effect.
  102034. * This is black by default as the blend operation is a blend operation.
  102035. */
  102036. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  102037. /**
  102038. * Stencil value used for glowing meshes.
  102039. */
  102040. HighlightLayer.GlowingMeshStencilReference = 0x02;
  102041. /**
  102042. * Stencil value used for the other meshes in the scene.
  102043. */
  102044. HighlightLayer.NormalMeshStencilReference = 0x01;
  102045. __decorate([
  102046. BABYLON.serialize()
  102047. ], HighlightLayer.prototype, "innerGlow", void 0);
  102048. __decorate([
  102049. BABYLON.serialize()
  102050. ], HighlightLayer.prototype, "outerGlow", void 0);
  102051. __decorate([
  102052. BABYLON.serialize()
  102053. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  102054. __decorate([
  102055. BABYLON.serialize()
  102056. ], HighlightLayer.prototype, "blurVerticalSize", null);
  102057. __decorate([
  102058. BABYLON.serialize("options")
  102059. ], HighlightLayer.prototype, "_options", void 0);
  102060. return HighlightLayer;
  102061. }(BABYLON.EffectLayer));
  102062. BABYLON.HighlightLayer = HighlightLayer;
  102063. })(BABYLON || (BABYLON = {}));
  102064. //# sourceMappingURL=babylon.highlightLayer.js.map
  102065. var BABYLON;
  102066. (function (BABYLON) {
  102067. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  102068. for (var index = 0; index < this.effectLayers.length; index++) {
  102069. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  102070. return this.effectLayers[index];
  102071. }
  102072. }
  102073. return null;
  102074. };
  102075. /**
  102076. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  102077. *
  102078. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  102079. * glowy meshes to your scene.
  102080. *
  102081. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  102082. */
  102083. var GlowLayer = /** @class */ (function (_super) {
  102084. __extends(GlowLayer, _super);
  102085. /**
  102086. * Instantiates a new glow Layer and references it to the scene.
  102087. * @param name The name of the layer
  102088. * @param scene The scene to use the layer in
  102089. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  102090. */
  102091. function GlowLayer(name, scene, options) {
  102092. var _this = _super.call(this, name, scene) || this;
  102093. _this._intensity = 1.0;
  102094. _this._includedOnlyMeshes = [];
  102095. _this._excludedMeshes = [];
  102096. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  102097. // Adapt options
  102098. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  102099. // Initialize the layer
  102100. _this._init({
  102101. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  102102. camera: _this._options.camera,
  102103. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  102104. mainTextureRatio: _this._options.mainTextureRatio,
  102105. renderingGroupId: _this._options.renderingGroupId
  102106. });
  102107. return _this;
  102108. }
  102109. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  102110. /**
  102111. * Gets the kernel size of the blur.
  102112. */
  102113. get: function () {
  102114. return this._horizontalBlurPostprocess1.kernel;
  102115. },
  102116. /**
  102117. * Sets the kernel size of the blur.
  102118. */
  102119. set: function (value) {
  102120. this._horizontalBlurPostprocess1.kernel = value;
  102121. this._verticalBlurPostprocess1.kernel = value;
  102122. this._horizontalBlurPostprocess2.kernel = value;
  102123. this._verticalBlurPostprocess2.kernel = value;
  102124. },
  102125. enumerable: true,
  102126. configurable: true
  102127. });
  102128. Object.defineProperty(GlowLayer.prototype, "intensity", {
  102129. /**
  102130. * Gets the glow intensity.
  102131. */
  102132. get: function () {
  102133. return this._intensity;
  102134. },
  102135. /**
  102136. * Sets the glow intensity.
  102137. */
  102138. set: function (value) {
  102139. this._intensity = value;
  102140. },
  102141. enumerable: true,
  102142. configurable: true
  102143. });
  102144. /**
  102145. * Get the effect name of the layer.
  102146. * @return The effect name
  102147. */
  102148. GlowLayer.prototype.getEffectName = function () {
  102149. return GlowLayer.EffectName;
  102150. };
  102151. /**
  102152. * Create the merge effect. This is the shader use to blit the information back
  102153. * to the main canvas at the end of the scene rendering.
  102154. */
  102155. GlowLayer.prototype._createMergeEffect = function () {
  102156. // Effect
  102157. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  102158. };
  102159. /**
  102160. * Creates the render target textures and post processes used in the glow layer.
  102161. */
  102162. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  102163. var _this = this;
  102164. var blurTextureWidth = this._mainTextureDesiredSize.width;
  102165. var blurTextureHeight = this._mainTextureDesiredSize.height;
  102166. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  102167. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  102168. var textureType = 0;
  102169. if (this._engine.getCaps().textureHalfFloatRender) {
  102170. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  102171. }
  102172. else {
  102173. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  102174. }
  102175. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  102176. width: blurTextureWidth,
  102177. height: blurTextureHeight
  102178. }, this._scene, false, true, textureType);
  102179. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102180. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102181. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102182. this._blurTexture1.renderParticles = false;
  102183. this._blurTexture1.ignoreCameraViewport = true;
  102184. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  102185. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  102186. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  102187. width: blurTextureWidth2,
  102188. height: blurTextureHeight2
  102189. }, this._scene, false, true, textureType);
  102190. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102191. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102192. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102193. this._blurTexture2.renderParticles = false;
  102194. this._blurTexture2.ignoreCameraViewport = true;
  102195. this._textures = [this._blurTexture1, this._blurTexture2];
  102196. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  102197. width: blurTextureWidth,
  102198. height: blurTextureHeight
  102199. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102200. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  102201. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  102202. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  102203. effect.setTexture("textureSampler", _this._mainTexture);
  102204. });
  102205. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  102206. width: blurTextureWidth,
  102207. height: blurTextureHeight
  102208. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102209. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  102210. width: blurTextureWidth2,
  102211. height: blurTextureHeight2
  102212. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102213. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  102214. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  102215. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  102216. effect.setTexture("textureSampler", _this._blurTexture1);
  102217. });
  102218. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  102219. width: blurTextureWidth2,
  102220. height: blurTextureHeight2
  102221. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102222. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  102223. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  102224. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  102225. this._mainTexture.samples = this._options.mainTextureSamples;
  102226. this._mainTexture.onAfterUnbindObservable.add(function () {
  102227. var internalTexture = _this._blurTexture1.getInternalTexture();
  102228. if (internalTexture) {
  102229. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  102230. internalTexture = _this._blurTexture2.getInternalTexture();
  102231. if (internalTexture) {
  102232. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  102233. }
  102234. }
  102235. });
  102236. // Prevent autoClear.
  102237. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  102238. };
  102239. /**
  102240. * Checks for the readiness of the element composing the layer.
  102241. * @param subMesh the mesh to check for
  102242. * @param useInstances specify wether or not to use instances to render the mesh
  102243. * @param emissiveTexture the associated emissive texture used to generate the glow
  102244. * @return true if ready otherwise, false
  102245. */
  102246. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  102247. var material = subMesh.getMaterial();
  102248. var mesh = subMesh.getRenderingMesh();
  102249. if (!material || !mesh) {
  102250. return false;
  102251. }
  102252. var emissiveTexture = material.emissiveTexture;
  102253. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  102254. };
  102255. /**
  102256. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  102257. */
  102258. GlowLayer.prototype.needStencil = function () {
  102259. return false;
  102260. };
  102261. /**
  102262. * Implementation specific of rendering the generating effect on the main canvas.
  102263. * @param effect The effect used to render through
  102264. */
  102265. GlowLayer.prototype._internalRender = function (effect) {
  102266. // Texture
  102267. effect.setTexture("textureSampler", this._blurTexture1);
  102268. effect.setTexture("textureSampler2", this._blurTexture2);
  102269. effect.setFloat("offset", this._intensity);
  102270. // Cache
  102271. var engine = this._engine;
  102272. var previousStencilBuffer = engine.getStencilBuffer();
  102273. // Draw order
  102274. engine.setStencilBuffer(false);
  102275. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102276. // Draw order
  102277. engine.setStencilBuffer(previousStencilBuffer);
  102278. };
  102279. /**
  102280. * Sets the required values for both the emissive texture and and the main color.
  102281. */
  102282. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  102283. var textureLevel = 1.0;
  102284. if (this.customEmissiveTextureSelector) {
  102285. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  102286. }
  102287. else {
  102288. if (material) {
  102289. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  102290. if (this._emissiveTextureAndColor.texture) {
  102291. textureLevel = this._emissiveTextureAndColor.texture.level;
  102292. }
  102293. }
  102294. else {
  102295. this._emissiveTextureAndColor.texture = null;
  102296. }
  102297. }
  102298. if (this.customEmissiveColorSelector) {
  102299. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  102300. }
  102301. else {
  102302. if (material.emissiveColor) {
  102303. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  102304. }
  102305. else {
  102306. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  102307. }
  102308. }
  102309. };
  102310. /**
  102311. * Returns true if the mesh should render, otherwise false.
  102312. * @param mesh The mesh to render
  102313. * @returns true if it should render otherwise false
  102314. */
  102315. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  102316. return this.hasMesh(mesh);
  102317. };
  102318. /**
  102319. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  102320. * @param mesh The mesh to exclude from the glow layer
  102321. */
  102322. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  102323. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  102324. this._excludedMeshes.push(mesh.uniqueId);
  102325. }
  102326. };
  102327. /**
  102328. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  102329. * @param mesh The mesh to remove
  102330. */
  102331. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  102332. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  102333. if (index !== -1) {
  102334. this._excludedMeshes.splice(index, 1);
  102335. }
  102336. };
  102337. /**
  102338. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  102339. * @param mesh The mesh to include in the glow layer
  102340. */
  102341. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  102342. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  102343. this._includedOnlyMeshes.push(mesh.uniqueId);
  102344. }
  102345. };
  102346. /**
  102347. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  102348. * @param mesh The mesh to remove
  102349. */
  102350. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  102351. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  102352. if (index !== -1) {
  102353. this._includedOnlyMeshes.splice(index, 1);
  102354. }
  102355. };
  102356. /**
  102357. * Determine if a given mesh will be used in the glow layer
  102358. * @param mesh The mesh to test
  102359. * @returns true if the mesh will be highlighted by the current glow layer
  102360. */
  102361. GlowLayer.prototype.hasMesh = function (mesh) {
  102362. if (!_super.prototype.hasMesh.call(this, mesh)) {
  102363. return false;
  102364. }
  102365. // Included Mesh
  102366. if (this._includedOnlyMeshes.length) {
  102367. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  102368. }
  102369. ;
  102370. // Excluded Mesh
  102371. if (this._excludedMeshes.length) {
  102372. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  102373. }
  102374. ;
  102375. return true;
  102376. };
  102377. /**
  102378. * Free any resources and references associated to a mesh.
  102379. * Internal use
  102380. * @param mesh The mesh to free.
  102381. * @hidden
  102382. */
  102383. GlowLayer.prototype._disposeMesh = function (mesh) {
  102384. this.removeIncludedOnlyMesh(mesh);
  102385. this.removeExcludedMesh(mesh);
  102386. };
  102387. /**
  102388. * Gets the class name of the effect layer
  102389. * @returns the string with the class name of the effect layer
  102390. */
  102391. GlowLayer.prototype.getClassName = function () {
  102392. return "GlowLayer";
  102393. };
  102394. /**
  102395. * Serializes this glow layer
  102396. * @returns a serialized glow layer object
  102397. */
  102398. GlowLayer.prototype.serialize = function () {
  102399. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  102400. serializationObject.customType = "BABYLON.GlowLayer";
  102401. var index;
  102402. // Included meshes
  102403. serializationObject.includedMeshes = [];
  102404. if (this._includedOnlyMeshes.length) {
  102405. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  102406. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  102407. if (mesh) {
  102408. serializationObject.includedMeshes.push(mesh.id);
  102409. }
  102410. }
  102411. }
  102412. // Excluded meshes
  102413. serializationObject.excludedMeshes = [];
  102414. if (this._excludedMeshes.length) {
  102415. for (index = 0; index < this._excludedMeshes.length; index++) {
  102416. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  102417. if (mesh) {
  102418. serializationObject.excludedMeshes.push(mesh.id);
  102419. }
  102420. }
  102421. }
  102422. return serializationObject;
  102423. };
  102424. /**
  102425. * Creates a Glow Layer from parsed glow layer data
  102426. * @param parsedGlowLayer defines glow layer data
  102427. * @param scene defines the current scene
  102428. * @param rootUrl defines the root URL containing the glow layer information
  102429. * @returns a parsed Glow Layer
  102430. */
  102431. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  102432. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  102433. var index;
  102434. // Excluded meshes
  102435. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  102436. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  102437. if (mesh) {
  102438. gl.addExcludedMesh(mesh);
  102439. }
  102440. }
  102441. // Included meshes
  102442. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  102443. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  102444. if (mesh) {
  102445. gl.addIncludedOnlyMesh(mesh);
  102446. }
  102447. }
  102448. return gl;
  102449. };
  102450. /**
  102451. * Effect Name of the layer.
  102452. */
  102453. GlowLayer.EffectName = "GlowLayer";
  102454. /**
  102455. * The default blur kernel size used for the glow.
  102456. */
  102457. GlowLayer.DefaultBlurKernelSize = 32;
  102458. /**
  102459. * The default texture size ratio used for the glow.
  102460. */
  102461. GlowLayer.DefaultTextureRatio = 0.5;
  102462. __decorate([
  102463. BABYLON.serialize()
  102464. ], GlowLayer.prototype, "blurKernelSize", null);
  102465. __decorate([
  102466. BABYLON.serialize()
  102467. ], GlowLayer.prototype, "intensity", null);
  102468. __decorate([
  102469. BABYLON.serialize("options")
  102470. ], GlowLayer.prototype, "_options", void 0);
  102471. return GlowLayer;
  102472. }(BABYLON.EffectLayer));
  102473. BABYLON.GlowLayer = GlowLayer;
  102474. })(BABYLON || (BABYLON = {}));
  102475. //# sourceMappingURL=babylon.glowLayer.js.map
  102476. var BABYLON;
  102477. (function (BABYLON) {
  102478. /**
  102479. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  102480. */
  102481. var AssetTaskState;
  102482. (function (AssetTaskState) {
  102483. /**
  102484. * Initialization
  102485. */
  102486. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  102487. /**
  102488. * Running
  102489. */
  102490. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  102491. /**
  102492. * Done
  102493. */
  102494. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  102495. /**
  102496. * Error
  102497. */
  102498. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  102499. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  102500. /**
  102501. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  102502. */
  102503. var AbstractAssetTask = /** @class */ (function () {
  102504. /**
  102505. * Creates a new {BABYLON.AssetsManager}
  102506. * @param name defines the name of the task
  102507. */
  102508. function AbstractAssetTask(
  102509. /**
  102510. * Task name
  102511. */ name) {
  102512. this.name = name;
  102513. this._isCompleted = false;
  102514. this._taskState = AssetTaskState.INIT;
  102515. }
  102516. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  102517. /**
  102518. * Get if the task is completed
  102519. */
  102520. get: function () {
  102521. return this._isCompleted;
  102522. },
  102523. enumerable: true,
  102524. configurable: true
  102525. });
  102526. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  102527. /**
  102528. * Gets the current state of the task
  102529. */
  102530. get: function () {
  102531. return this._taskState;
  102532. },
  102533. enumerable: true,
  102534. configurable: true
  102535. });
  102536. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  102537. /**
  102538. * Gets the current error object (if task is in error)
  102539. */
  102540. get: function () {
  102541. return this._errorObject;
  102542. },
  102543. enumerable: true,
  102544. configurable: true
  102545. });
  102546. /**
  102547. * Internal only
  102548. * @hidden
  102549. */
  102550. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  102551. if (this._errorObject) {
  102552. return;
  102553. }
  102554. this._errorObject = {
  102555. message: message,
  102556. exception: exception
  102557. };
  102558. };
  102559. /**
  102560. * Execute the current task
  102561. * @param scene defines the scene where you want your assets to be loaded
  102562. * @param onSuccess is a callback called when the task is successfully executed
  102563. * @param onError is a callback called if an error occurs
  102564. */
  102565. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  102566. var _this = this;
  102567. this._taskState = AssetTaskState.RUNNING;
  102568. this.runTask(scene, function () {
  102569. _this.onDoneCallback(onSuccess, onError);
  102570. }, function (msg, exception) {
  102571. _this.onErrorCallback(onError, msg, exception);
  102572. });
  102573. };
  102574. /**
  102575. * Execute the current task
  102576. * @param scene defines the scene where you want your assets to be loaded
  102577. * @param onSuccess is a callback called when the task is successfully executed
  102578. * @param onError is a callback called if an error occurs
  102579. */
  102580. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102581. throw new Error("runTask is not implemented");
  102582. };
  102583. /**
  102584. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  102585. * This can be used with failed tasks that have the reason for failure fixed.
  102586. */
  102587. AbstractAssetTask.prototype.reset = function () {
  102588. this._taskState = AssetTaskState.INIT;
  102589. };
  102590. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  102591. this._taskState = AssetTaskState.ERROR;
  102592. this._errorObject = {
  102593. message: message,
  102594. exception: exception
  102595. };
  102596. if (this.onError) {
  102597. this.onError(this, message, exception);
  102598. }
  102599. onError();
  102600. };
  102601. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  102602. try {
  102603. this._taskState = AssetTaskState.DONE;
  102604. this._isCompleted = true;
  102605. if (this.onSuccess) {
  102606. this.onSuccess(this);
  102607. }
  102608. onSuccess();
  102609. }
  102610. catch (e) {
  102611. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  102612. }
  102613. };
  102614. return AbstractAssetTask;
  102615. }());
  102616. BABYLON.AbstractAssetTask = AbstractAssetTask;
  102617. /**
  102618. * Class used to share progress information about assets loading
  102619. */
  102620. var AssetsProgressEvent = /** @class */ (function () {
  102621. /**
  102622. * Creates a {BABYLON.AssetsProgressEvent}
  102623. * @param remainingCount defines the number of remaining tasks to process
  102624. * @param totalCount defines the total number of tasks
  102625. * @param task defines the task that was just processed
  102626. */
  102627. function AssetsProgressEvent(remainingCount, totalCount, task) {
  102628. this.remainingCount = remainingCount;
  102629. this.totalCount = totalCount;
  102630. this.task = task;
  102631. }
  102632. return AssetsProgressEvent;
  102633. }());
  102634. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  102635. /**
  102636. * Define a task used by {BABYLON.AssetsManager} to load meshes
  102637. */
  102638. var MeshAssetTask = /** @class */ (function (_super) {
  102639. __extends(MeshAssetTask, _super);
  102640. /**
  102641. * Creates a new {BABYLON.MeshAssetTask}
  102642. * @param name defines the name of the task
  102643. * @param meshesNames defines the list of mesh's names you want to load
  102644. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  102645. * @param sceneFilename defines the filename of the scene to load from
  102646. */
  102647. function MeshAssetTask(
  102648. /**
  102649. * Defines the name of the task
  102650. */
  102651. name,
  102652. /**
  102653. * Defines the list of mesh's names you want to load
  102654. */
  102655. meshesNames,
  102656. /**
  102657. * Defines the root url to use as a base to load your meshes and associated resources
  102658. */
  102659. rootUrl,
  102660. /**
  102661. * Defines the filename of the scene to load from
  102662. */
  102663. sceneFilename) {
  102664. var _this = _super.call(this, name) || this;
  102665. _this.name = name;
  102666. _this.meshesNames = meshesNames;
  102667. _this.rootUrl = rootUrl;
  102668. _this.sceneFilename = sceneFilename;
  102669. return _this;
  102670. }
  102671. /**
  102672. * Execute the current task
  102673. * @param scene defines the scene where you want your assets to be loaded
  102674. * @param onSuccess is a callback called when the task is successfully executed
  102675. * @param onError is a callback called if an error occurs
  102676. */
  102677. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102678. var _this = this;
  102679. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  102680. _this.loadedMeshes = meshes;
  102681. _this.loadedParticleSystems = particleSystems;
  102682. _this.loadedSkeletons = skeletons;
  102683. onSuccess();
  102684. }, null, function (scene, message, exception) {
  102685. onError(message, exception);
  102686. });
  102687. };
  102688. return MeshAssetTask;
  102689. }(AbstractAssetTask));
  102690. BABYLON.MeshAssetTask = MeshAssetTask;
  102691. /**
  102692. * Define a task used by {BABYLON.AssetsManager} to load text content
  102693. */
  102694. var TextFileAssetTask = /** @class */ (function (_super) {
  102695. __extends(TextFileAssetTask, _super);
  102696. /**
  102697. * Creates a new TextFileAssetTask object
  102698. * @param name defines the name of the task
  102699. * @param url defines the location of the file to load
  102700. */
  102701. function TextFileAssetTask(
  102702. /**
  102703. * Defines the name of the task
  102704. */
  102705. name,
  102706. /**
  102707. * Defines the location of the file to load
  102708. */
  102709. url) {
  102710. var _this = _super.call(this, name) || this;
  102711. _this.name = name;
  102712. _this.url = url;
  102713. return _this;
  102714. }
  102715. /**
  102716. * Execute the current task
  102717. * @param scene defines the scene where you want your assets to be loaded
  102718. * @param onSuccess is a callback called when the task is successfully executed
  102719. * @param onError is a callback called if an error occurs
  102720. */
  102721. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102722. var _this = this;
  102723. scene._loadFile(this.url, function (data) {
  102724. _this.text = data;
  102725. onSuccess();
  102726. }, undefined, false, false, function (request, exception) {
  102727. if (request) {
  102728. onError(request.status + " " + request.statusText, exception);
  102729. }
  102730. });
  102731. };
  102732. return TextFileAssetTask;
  102733. }(AbstractAssetTask));
  102734. BABYLON.TextFileAssetTask = TextFileAssetTask;
  102735. /**
  102736. * Define a task used by {BABYLON.AssetsManager} to load binary data
  102737. */
  102738. var BinaryFileAssetTask = /** @class */ (function (_super) {
  102739. __extends(BinaryFileAssetTask, _super);
  102740. /**
  102741. * Creates a new BinaryFileAssetTask object
  102742. * @param name defines the name of the new task
  102743. * @param url defines the location of the file to load
  102744. */
  102745. function BinaryFileAssetTask(
  102746. /**
  102747. * Defines the name of the task
  102748. */
  102749. name,
  102750. /**
  102751. * Defines the location of the file to load
  102752. */
  102753. url) {
  102754. var _this = _super.call(this, name) || this;
  102755. _this.name = name;
  102756. _this.url = url;
  102757. return _this;
  102758. }
  102759. /**
  102760. * Execute the current task
  102761. * @param scene defines the scene where you want your assets to be loaded
  102762. * @param onSuccess is a callback called when the task is successfully executed
  102763. * @param onError is a callback called if an error occurs
  102764. */
  102765. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102766. var _this = this;
  102767. scene._loadFile(this.url, function (data) {
  102768. _this.data = data;
  102769. onSuccess();
  102770. }, undefined, true, true, function (request, exception) {
  102771. if (request) {
  102772. onError(request.status + " " + request.statusText, exception);
  102773. }
  102774. });
  102775. };
  102776. return BinaryFileAssetTask;
  102777. }(AbstractAssetTask));
  102778. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  102779. /**
  102780. * Define a task used by {BABYLON.AssetsManager} to load images
  102781. */
  102782. var ImageAssetTask = /** @class */ (function (_super) {
  102783. __extends(ImageAssetTask, _super);
  102784. /**
  102785. * Creates a new ImageAssetTask
  102786. * @param name defines the name of the task
  102787. * @param url defines the location of the image to load
  102788. */
  102789. function ImageAssetTask(
  102790. /**
  102791. * Defines the name of the task
  102792. */
  102793. name,
  102794. /**
  102795. * Defines the location of the image to load
  102796. */
  102797. url) {
  102798. var _this = _super.call(this, name) || this;
  102799. _this.name = name;
  102800. _this.url = url;
  102801. return _this;
  102802. }
  102803. /**
  102804. * Execute the current task
  102805. * @param scene defines the scene where you want your assets to be loaded
  102806. * @param onSuccess is a callback called when the task is successfully executed
  102807. * @param onError is a callback called if an error occurs
  102808. */
  102809. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102810. var _this = this;
  102811. var img = new Image();
  102812. BABYLON.Tools.SetCorsBehavior(this.url, img);
  102813. img.onload = function () {
  102814. _this.image = img;
  102815. onSuccess();
  102816. };
  102817. img.onerror = function (err) {
  102818. onError("Error loading image", err);
  102819. };
  102820. img.src = this.url;
  102821. };
  102822. return ImageAssetTask;
  102823. }(AbstractAssetTask));
  102824. BABYLON.ImageAssetTask = ImageAssetTask;
  102825. /**
  102826. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  102827. */
  102828. var TextureAssetTask = /** @class */ (function (_super) {
  102829. __extends(TextureAssetTask, _super);
  102830. /**
  102831. * Creates a new TextureAssetTask object
  102832. * @param name defines the name of the task
  102833. * @param url defines the location of the file to load
  102834. * @param noMipmap defines if mipmap should not be generated (default is false)
  102835. * @param invertY defines if texture must be inverted on Y axis (default is false)
  102836. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  102837. */
  102838. function TextureAssetTask(
  102839. /**
  102840. * Defines the name of the task
  102841. */
  102842. name,
  102843. /**
  102844. * Defines the location of the file to load
  102845. */
  102846. url,
  102847. /**
  102848. * Defines if mipmap should not be generated (default is false)
  102849. */
  102850. noMipmap,
  102851. /**
  102852. * Defines if texture must be inverted on Y axis (default is false)
  102853. */
  102854. invertY,
  102855. /**
  102856. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  102857. */
  102858. samplingMode) {
  102859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  102860. var _this = _super.call(this, name) || this;
  102861. _this.name = name;
  102862. _this.url = url;
  102863. _this.noMipmap = noMipmap;
  102864. _this.invertY = invertY;
  102865. _this.samplingMode = samplingMode;
  102866. return _this;
  102867. }
  102868. /**
  102869. * Execute the current task
  102870. * @param scene defines the scene where you want your assets to be loaded
  102871. * @param onSuccess is a callback called when the task is successfully executed
  102872. * @param onError is a callback called if an error occurs
  102873. */
  102874. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102875. var onload = function () {
  102876. onSuccess();
  102877. };
  102878. var onerror = function (message, exception) {
  102879. onError(message, exception);
  102880. };
  102881. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  102882. };
  102883. return TextureAssetTask;
  102884. }(AbstractAssetTask));
  102885. BABYLON.TextureAssetTask = TextureAssetTask;
  102886. /**
  102887. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  102888. */
  102889. var CubeTextureAssetTask = /** @class */ (function (_super) {
  102890. __extends(CubeTextureAssetTask, _super);
  102891. /**
  102892. * Creates a new CubeTextureAssetTask
  102893. * @param name defines the name of the task
  102894. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  102895. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  102896. * @param noMipmap defines if mipmaps should not be generated (default is false)
  102897. * @param files defines the explicit list of files (undefined by default)
  102898. */
  102899. function CubeTextureAssetTask(
  102900. /**
  102901. * Defines the name of the task
  102902. */
  102903. name,
  102904. /**
  102905. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  102906. */
  102907. url,
  102908. /**
  102909. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  102910. */
  102911. extensions,
  102912. /**
  102913. * Defines if mipmaps should not be generated (default is false)
  102914. */
  102915. noMipmap,
  102916. /**
  102917. * Defines the explicit list of files (undefined by default)
  102918. */
  102919. files) {
  102920. var _this = _super.call(this, name) || this;
  102921. _this.name = name;
  102922. _this.url = url;
  102923. _this.extensions = extensions;
  102924. _this.noMipmap = noMipmap;
  102925. _this.files = files;
  102926. return _this;
  102927. }
  102928. /**
  102929. * Execute the current task
  102930. * @param scene defines the scene where you want your assets to be loaded
  102931. * @param onSuccess is a callback called when the task is successfully executed
  102932. * @param onError is a callback called if an error occurs
  102933. */
  102934. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102935. var onload = function () {
  102936. onSuccess();
  102937. };
  102938. var onerror = function (message, exception) {
  102939. onError(message, exception);
  102940. };
  102941. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  102942. };
  102943. return CubeTextureAssetTask;
  102944. }(AbstractAssetTask));
  102945. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  102946. /**
  102947. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  102948. */
  102949. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  102950. __extends(HDRCubeTextureAssetTask, _super);
  102951. /**
  102952. * Creates a new HDRCubeTextureAssetTask object
  102953. * @param name defines the name of the task
  102954. * @param url defines the location of the file to load
  102955. * @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.
  102956. * @param noMipmap defines if mipmaps should not be generated (default is false)
  102957. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  102958. * @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)
  102959. * @param reserved Internal use only
  102960. */
  102961. function HDRCubeTextureAssetTask(
  102962. /**
  102963. * Defines the name of the task
  102964. */
  102965. name,
  102966. /**
  102967. * Defines the location of the file to load
  102968. */
  102969. url,
  102970. /**
  102971. * Defines the desired size (the more it increases the longer the generation will be)
  102972. */
  102973. size,
  102974. /**
  102975. * Defines if mipmaps should not be generated (default is false)
  102976. */
  102977. noMipmap,
  102978. /**
  102979. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  102980. */
  102981. generateHarmonics,
  102982. /**
  102983. * 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)
  102984. */
  102985. gammaSpace,
  102986. /**
  102987. * Internal Use Only
  102988. */
  102989. reserved) {
  102990. if (noMipmap === void 0) { noMipmap = false; }
  102991. if (generateHarmonics === void 0) { generateHarmonics = true; }
  102992. if (gammaSpace === void 0) { gammaSpace = false; }
  102993. if (reserved === void 0) { reserved = false; }
  102994. var _this = _super.call(this, name) || this;
  102995. _this.name = name;
  102996. _this.url = url;
  102997. _this.size = size;
  102998. _this.noMipmap = noMipmap;
  102999. _this.generateHarmonics = generateHarmonics;
  103000. _this.gammaSpace = gammaSpace;
  103001. _this.reserved = reserved;
  103002. return _this;
  103003. }
  103004. /**
  103005. * Execute the current task
  103006. * @param scene defines the scene where you want your assets to be loaded
  103007. * @param onSuccess is a callback called when the task is successfully executed
  103008. * @param onError is a callback called if an error occurs
  103009. */
  103010. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  103011. var onload = function () {
  103012. onSuccess();
  103013. };
  103014. var onerror = function (message, exception) {
  103015. onError(message, exception);
  103016. };
  103017. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  103018. };
  103019. return HDRCubeTextureAssetTask;
  103020. }(AbstractAssetTask));
  103021. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  103022. /**
  103023. * This class can be used to easily import assets into a scene
  103024. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  103025. */
  103026. var AssetsManager = /** @class */ (function () {
  103027. /**
  103028. * Creates a new AssetsManager
  103029. * @param scene defines the scene to work on
  103030. */
  103031. function AssetsManager(scene) {
  103032. this._isLoading = false;
  103033. this._tasks = new Array();
  103034. this._waitingTasksCount = 0;
  103035. this._totalTasksCount = 0;
  103036. /**
  103037. * Observable called when all tasks are processed
  103038. */
  103039. this.onTaskSuccessObservable = new BABYLON.Observable();
  103040. /**
  103041. * Observable called when a task had an error
  103042. */
  103043. this.onTaskErrorObservable = new BABYLON.Observable();
  103044. /**
  103045. * Observable called when a task is successful
  103046. */
  103047. this.onTasksDoneObservable = new BABYLON.Observable();
  103048. /**
  103049. * Observable called when a task is done (whatever the result is)
  103050. */
  103051. this.onProgressObservable = new BABYLON.Observable();
  103052. /**
  103053. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  103054. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  103055. */
  103056. this.useDefaultLoadingScreen = true;
  103057. this._scene = scene;
  103058. }
  103059. /**
  103060. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  103061. * @param taskName defines the name of the new task
  103062. * @param meshesNames defines the name of meshes to load
  103063. * @param rootUrl defines the root url to use to locate files
  103064. * @param sceneFilename defines the filename of the scene file
  103065. * @returns a new {BABYLON.MeshAssetTask} object
  103066. */
  103067. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  103068. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  103069. this._tasks.push(task);
  103070. return task;
  103071. };
  103072. /**
  103073. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  103074. * @param taskName defines the name of the new task
  103075. * @param url defines the url of the file to load
  103076. * @returns a new {BABYLON.TextFileAssetTask} object
  103077. */
  103078. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  103079. var task = new TextFileAssetTask(taskName, url);
  103080. this._tasks.push(task);
  103081. return task;
  103082. };
  103083. /**
  103084. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  103085. * @param taskName defines the name of the new task
  103086. * @param url defines the url of the file to load
  103087. * @returns a new {BABYLON.BinaryFileAssetTask} object
  103088. */
  103089. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  103090. var task = new BinaryFileAssetTask(taskName, url);
  103091. this._tasks.push(task);
  103092. return task;
  103093. };
  103094. /**
  103095. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  103096. * @param taskName defines the name of the new task
  103097. * @param url defines the url of the file to load
  103098. * @returns a new {BABYLON.ImageAssetTask} object
  103099. */
  103100. AssetsManager.prototype.addImageTask = function (taskName, url) {
  103101. var task = new ImageAssetTask(taskName, url);
  103102. this._tasks.push(task);
  103103. return task;
  103104. };
  103105. /**
  103106. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  103107. * @param taskName defines the name of the new task
  103108. * @param url defines the url of the file to load
  103109. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  103110. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  103111. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  103112. * @returns a new {BABYLON.TextureAssetTask} object
  103113. */
  103114. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  103115. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  103116. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  103117. this._tasks.push(task);
  103118. return task;
  103119. };
  103120. /**
  103121. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  103122. * @param taskName defines the name of the new task
  103123. * @param url defines the url of the file to load
  103124. * @param extensions defines the extension to use to load the cube map (can be null)
  103125. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  103126. * @param files defines the list of files to load (can be null)
  103127. * @returns a new {BABYLON.CubeTextureAssetTask} object
  103128. */
  103129. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  103130. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  103131. this._tasks.push(task);
  103132. return task;
  103133. };
  103134. /**
  103135. *
  103136. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  103137. * @param taskName defines the name of the new task
  103138. * @param url defines the url of the file to load
  103139. * @param size defines the size you want for the cubemap (can be null)
  103140. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  103141. * @param generateHarmonics defines if you want to automatically generate (true by default)
  103142. * @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)
  103143. * @param reserved Internal use only
  103144. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  103145. */
  103146. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  103147. if (noMipmap === void 0) { noMipmap = false; }
  103148. if (generateHarmonics === void 0) { generateHarmonics = true; }
  103149. if (gammaSpace === void 0) { gammaSpace = false; }
  103150. if (reserved === void 0) { reserved = false; }
  103151. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  103152. this._tasks.push(task);
  103153. return task;
  103154. };
  103155. /**
  103156. * Remove a task from the assets manager.
  103157. * @param task the task to remove
  103158. */
  103159. AssetsManager.prototype.removeTask = function (task) {
  103160. var index = this._tasks.indexOf(task);
  103161. if (index > -1) {
  103162. this._tasks.splice(index, 1);
  103163. }
  103164. };
  103165. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  103166. this._waitingTasksCount--;
  103167. try {
  103168. if (this.onProgress) {
  103169. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  103170. }
  103171. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  103172. }
  103173. catch (e) {
  103174. BABYLON.Tools.Error("Error running progress callbacks.");
  103175. console.log(e);
  103176. }
  103177. if (this._waitingTasksCount === 0) {
  103178. try {
  103179. if (this.onFinish) {
  103180. this.onFinish(this._tasks);
  103181. }
  103182. // Let's remove successfull tasks
  103183. var currentTasks = this._tasks.slice();
  103184. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  103185. var task = currentTasks_1[_i];
  103186. if (task.taskState === AssetTaskState.DONE) {
  103187. var index = this._tasks.indexOf(task);
  103188. if (index > -1) {
  103189. this._tasks.splice(index, 1);
  103190. }
  103191. }
  103192. }
  103193. this.onTasksDoneObservable.notifyObservers(this._tasks);
  103194. }
  103195. catch (e) {
  103196. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  103197. console.log(e);
  103198. }
  103199. this._isLoading = false;
  103200. this._scene.getEngine().hideLoadingUI();
  103201. }
  103202. };
  103203. AssetsManager.prototype._runTask = function (task) {
  103204. var _this = this;
  103205. var done = function () {
  103206. try {
  103207. if (_this.onTaskSuccess) {
  103208. _this.onTaskSuccess(task);
  103209. }
  103210. _this.onTaskSuccessObservable.notifyObservers(task);
  103211. _this._decreaseWaitingTasksCount(task);
  103212. }
  103213. catch (e) {
  103214. error("Error executing task success callbacks", e);
  103215. }
  103216. };
  103217. var error = function (message, exception) {
  103218. task._setErrorObject(message, exception);
  103219. if (_this.onTaskError) {
  103220. _this.onTaskError(task);
  103221. }
  103222. _this.onTaskErrorObservable.notifyObservers(task);
  103223. _this._decreaseWaitingTasksCount(task);
  103224. };
  103225. task.run(this._scene, done, error);
  103226. };
  103227. /**
  103228. * Reset the {BABYLON.AssetsManager} and remove all tasks
  103229. * @return the current instance of the {BABYLON.AssetsManager}
  103230. */
  103231. AssetsManager.prototype.reset = function () {
  103232. this._isLoading = false;
  103233. this._tasks = new Array();
  103234. return this;
  103235. };
  103236. /**
  103237. * Start the loading process
  103238. * @return the current instance of the {BABYLON.AssetsManager}
  103239. */
  103240. AssetsManager.prototype.load = function () {
  103241. if (this._isLoading) {
  103242. return this;
  103243. }
  103244. this._isLoading = true;
  103245. this._waitingTasksCount = this._tasks.length;
  103246. this._totalTasksCount = this._tasks.length;
  103247. if (this._waitingTasksCount === 0) {
  103248. this._isLoading = false;
  103249. if (this.onFinish) {
  103250. this.onFinish(this._tasks);
  103251. }
  103252. this.onTasksDoneObservable.notifyObservers(this._tasks);
  103253. return this;
  103254. }
  103255. if (this.useDefaultLoadingScreen) {
  103256. this._scene.getEngine().displayLoadingUI();
  103257. }
  103258. for (var index = 0; index < this._tasks.length; index++) {
  103259. var task = this._tasks[index];
  103260. if (task.taskState === AssetTaskState.INIT) {
  103261. this._runTask(task);
  103262. }
  103263. }
  103264. return this;
  103265. };
  103266. return AssetsManager;
  103267. }());
  103268. BABYLON.AssetsManager = AssetsManager;
  103269. })(BABYLON || (BABYLON = {}));
  103270. //# sourceMappingURL=babylon.assetsManager.js.map
  103271. var BABYLON;
  103272. (function (BABYLON) {
  103273. var serializedGeometries = [];
  103274. var serializeGeometry = function (geometry, serializationGeometries) {
  103275. if (serializedGeometries[geometry.id]) {
  103276. return;
  103277. }
  103278. if (geometry.doNotSerialize) {
  103279. return;
  103280. }
  103281. if (geometry instanceof BABYLON.BoxGeometry) {
  103282. serializationGeometries.boxes.push(geometry.serialize());
  103283. }
  103284. else if (geometry instanceof BABYLON.SphereGeometry) {
  103285. serializationGeometries.spheres.push(geometry.serialize());
  103286. }
  103287. else if (geometry instanceof BABYLON.CylinderGeometry) {
  103288. serializationGeometries.cylinders.push(geometry.serialize());
  103289. }
  103290. else if (geometry instanceof BABYLON.TorusGeometry) {
  103291. serializationGeometries.toruses.push(geometry.serialize());
  103292. }
  103293. else if (geometry instanceof BABYLON.GroundGeometry) {
  103294. serializationGeometries.grounds.push(geometry.serialize());
  103295. }
  103296. else if (geometry instanceof BABYLON.Plane) {
  103297. serializationGeometries.planes.push(geometry.serialize());
  103298. }
  103299. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  103300. serializationGeometries.torusKnots.push(geometry.serialize());
  103301. }
  103302. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  103303. throw new Error("Unknown primitive type");
  103304. }
  103305. else {
  103306. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  103307. }
  103308. serializedGeometries[geometry.id] = true;
  103309. };
  103310. var serializeMesh = function (mesh, serializationScene) {
  103311. var serializationObject = {};
  103312. // Geometry
  103313. var geometry = mesh._geometry;
  103314. if (geometry) {
  103315. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  103316. // 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
  103317. serializeGeometry(geometry, serializationScene.geometries);
  103318. }
  103319. }
  103320. // Custom
  103321. if (mesh.serialize) {
  103322. mesh.serialize(serializationObject);
  103323. }
  103324. return serializationObject;
  103325. };
  103326. var finalizeSingleMesh = function (mesh, serializationObject) {
  103327. //only works if the mesh is already loaded
  103328. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  103329. //serialize material
  103330. if (mesh.material) {
  103331. if (mesh.material instanceof BABYLON.MultiMaterial) {
  103332. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  103333. serializationObject.materials = serializationObject.materials || [];
  103334. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  103335. serializationObject.multiMaterials.push(mesh.material.serialize());
  103336. var _loop_1 = function (submaterial) {
  103337. if (submaterial) {
  103338. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  103339. serializationObject.materials.push(submaterial.serialize());
  103340. }
  103341. }
  103342. };
  103343. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  103344. var submaterial = _a[_i];
  103345. _loop_1(submaterial);
  103346. }
  103347. }
  103348. }
  103349. else {
  103350. serializationObject.materials = serializationObject.materials || [];
  103351. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  103352. serializationObject.materials.push(mesh.material.serialize());
  103353. }
  103354. }
  103355. }
  103356. //serialize geometry
  103357. var geometry = mesh._geometry;
  103358. if (geometry) {
  103359. if (!serializationObject.geometries) {
  103360. serializationObject.geometries = {};
  103361. serializationObject.geometries.boxes = [];
  103362. serializationObject.geometries.spheres = [];
  103363. serializationObject.geometries.cylinders = [];
  103364. serializationObject.geometries.toruses = [];
  103365. serializationObject.geometries.grounds = [];
  103366. serializationObject.geometries.planes = [];
  103367. serializationObject.geometries.torusKnots = [];
  103368. serializationObject.geometries.vertexData = [];
  103369. }
  103370. serializeGeometry(geometry, serializationObject.geometries);
  103371. }
  103372. // Skeletons
  103373. if (mesh.skeleton) {
  103374. serializationObject.skeletons = serializationObject.skeletons || [];
  103375. serializationObject.skeletons.push(mesh.skeleton.serialize());
  103376. }
  103377. //serialize the actual mesh
  103378. serializationObject.meshes = serializationObject.meshes || [];
  103379. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  103380. }
  103381. };
  103382. var SceneSerializer = /** @class */ (function () {
  103383. function SceneSerializer() {
  103384. }
  103385. SceneSerializer.ClearCache = function () {
  103386. serializedGeometries = [];
  103387. };
  103388. SceneSerializer.Serialize = function (scene) {
  103389. var serializationObject = {};
  103390. SceneSerializer.ClearCache();
  103391. // Scene
  103392. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  103393. serializationObject.autoClear = scene.autoClear;
  103394. serializationObject.clearColor = scene.clearColor.asArray();
  103395. serializationObject.ambientColor = scene.ambientColor.asArray();
  103396. serializationObject.gravity = scene.gravity.asArray();
  103397. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  103398. serializationObject.workerCollisions = scene.workerCollisions;
  103399. // Fog
  103400. if (scene.fogMode && scene.fogMode !== 0) {
  103401. serializationObject.fogMode = scene.fogMode;
  103402. serializationObject.fogColor = scene.fogColor.asArray();
  103403. serializationObject.fogStart = scene.fogStart;
  103404. serializationObject.fogEnd = scene.fogEnd;
  103405. serializationObject.fogDensity = scene.fogDensity;
  103406. }
  103407. //Physics
  103408. if (scene.isPhysicsEnabled()) {
  103409. var physicEngine = scene.getPhysicsEngine();
  103410. if (physicEngine) {
  103411. serializationObject.physicsEnabled = true;
  103412. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  103413. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  103414. }
  103415. }
  103416. // Metadata
  103417. if (scene.metadata) {
  103418. serializationObject.metadata = scene.metadata;
  103419. }
  103420. // Morph targets
  103421. serializationObject.morphTargetManagers = [];
  103422. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  103423. var abstractMesh = _a[_i];
  103424. var manager = abstractMesh.morphTargetManager;
  103425. if (manager) {
  103426. serializationObject.morphTargetManagers.push(manager.serialize());
  103427. }
  103428. }
  103429. // Lights
  103430. serializationObject.lights = [];
  103431. var index;
  103432. var light;
  103433. for (index = 0; index < scene.lights.length; index++) {
  103434. light = scene.lights[index];
  103435. if (!light.doNotSerialize) {
  103436. serializationObject.lights.push(light.serialize());
  103437. }
  103438. }
  103439. // Cameras
  103440. serializationObject.cameras = [];
  103441. for (index = 0; index < scene.cameras.length; index++) {
  103442. var camera = scene.cameras[index];
  103443. if (!camera.doNotSerialize) {
  103444. serializationObject.cameras.push(camera.serialize());
  103445. }
  103446. }
  103447. if (scene.activeCamera) {
  103448. serializationObject.activeCameraID = scene.activeCamera.id;
  103449. }
  103450. // Animations
  103451. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  103452. // Materials
  103453. serializationObject.materials = [];
  103454. serializationObject.multiMaterials = [];
  103455. var material;
  103456. for (index = 0; index < scene.materials.length; index++) {
  103457. material = scene.materials[index];
  103458. if (!material.doNotSerialize) {
  103459. serializationObject.materials.push(material.serialize());
  103460. }
  103461. }
  103462. // MultiMaterials
  103463. serializationObject.multiMaterials = [];
  103464. for (index = 0; index < scene.multiMaterials.length; index++) {
  103465. var multiMaterial = scene.multiMaterials[index];
  103466. serializationObject.multiMaterials.push(multiMaterial.serialize());
  103467. }
  103468. // Environment texture
  103469. if (scene.environmentTexture) {
  103470. serializationObject.environmentTexture = scene.environmentTexture.name;
  103471. }
  103472. // Skeletons
  103473. serializationObject.skeletons = [];
  103474. for (index = 0; index < scene.skeletons.length; index++) {
  103475. var skeleton = scene.skeletons[index];
  103476. if (!skeleton.doNotSerialize) {
  103477. serializationObject.skeletons.push(skeleton.serialize());
  103478. }
  103479. }
  103480. // Transform nodes
  103481. serializationObject.transformNodes = [];
  103482. for (index = 0; index < scene.transformNodes.length; index++) {
  103483. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  103484. }
  103485. // Geometries
  103486. serializationObject.geometries = {};
  103487. serializationObject.geometries.boxes = [];
  103488. serializationObject.geometries.spheres = [];
  103489. serializationObject.geometries.cylinders = [];
  103490. serializationObject.geometries.toruses = [];
  103491. serializationObject.geometries.grounds = [];
  103492. serializationObject.geometries.planes = [];
  103493. serializationObject.geometries.torusKnots = [];
  103494. serializationObject.geometries.vertexData = [];
  103495. serializedGeometries = [];
  103496. var geometries = scene.getGeometries();
  103497. for (index = 0; index < geometries.length; index++) {
  103498. var geometry = geometries[index];
  103499. if (geometry.isReady()) {
  103500. serializeGeometry(geometry, serializationObject.geometries);
  103501. }
  103502. }
  103503. // Meshes
  103504. serializationObject.meshes = [];
  103505. for (index = 0; index < scene.meshes.length; index++) {
  103506. var abstractMesh = scene.meshes[index];
  103507. if (abstractMesh instanceof BABYLON.Mesh) {
  103508. var mesh = abstractMesh;
  103509. if (!mesh.doNotSerialize) {
  103510. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  103511. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  103512. }
  103513. }
  103514. }
  103515. }
  103516. // Particles Systems
  103517. serializationObject.particleSystems = [];
  103518. for (index = 0; index < scene.particleSystems.length; index++) {
  103519. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  103520. }
  103521. // Action Manager
  103522. if (scene.actionManager) {
  103523. serializationObject.actions = scene.actionManager.serialize("scene");
  103524. }
  103525. // Audio
  103526. serializationObject.sounds = [];
  103527. for (index = 0; index < scene.soundTracks.length; index++) {
  103528. var soundtrack = scene.soundTracks[index];
  103529. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  103530. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  103531. }
  103532. }
  103533. // Components
  103534. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  103535. var component = _c[_b];
  103536. component.serialize(serializationObject);
  103537. }
  103538. return serializationObject;
  103539. };
  103540. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  103541. if (withParents === void 0) { withParents = false; }
  103542. if (withChildren === void 0) { withChildren = false; }
  103543. var serializationObject = {};
  103544. SceneSerializer.ClearCache();
  103545. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  103546. if (withParents || withChildren) {
  103547. //deliberate for loop! not for each, appended should be processed as well.
  103548. for (var i = 0; i < toSerialize.length; ++i) {
  103549. if (withChildren) {
  103550. toSerialize[i].getDescendants().forEach(function (node) {
  103551. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  103552. toSerialize.push(node);
  103553. }
  103554. });
  103555. }
  103556. //make sure the array doesn't contain the object already
  103557. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  103558. toSerialize.push(toSerialize[i].parent);
  103559. }
  103560. }
  103561. }
  103562. toSerialize.forEach(function (mesh) {
  103563. finalizeSingleMesh(mesh, serializationObject);
  103564. });
  103565. return serializationObject;
  103566. };
  103567. return SceneSerializer;
  103568. }());
  103569. BABYLON.SceneSerializer = SceneSerializer;
  103570. })(BABYLON || (BABYLON = {}));
  103571. //# sourceMappingURL=babylon.sceneSerializer.js.map
  103572. var BABYLON;
  103573. (function (BABYLON) {
  103574. /**
  103575. * Class used to generate realtime reflection / refraction cube textures
  103576. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  103577. */
  103578. var ReflectionProbe = /** @class */ (function () {
  103579. /**
  103580. * Creates a new reflection probe
  103581. * @param name defines the name of the probe
  103582. * @param size defines the texture resolution (for each face)
  103583. * @param scene defines the hosting scene
  103584. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  103585. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  103586. */
  103587. function ReflectionProbe(
  103588. /** defines the name of the probe */
  103589. name, size, scene, generateMipMaps, useFloat) {
  103590. if (generateMipMaps === void 0) { generateMipMaps = true; }
  103591. if (useFloat === void 0) { useFloat = false; }
  103592. var _this = this;
  103593. this.name = name;
  103594. this._viewMatrix = BABYLON.Matrix.Identity();
  103595. this._target = BABYLON.Vector3.Zero();
  103596. this._add = BABYLON.Vector3.Zero();
  103597. this._invertYAxis = false;
  103598. /** Gets or sets probe position (center of the cube map) */
  103599. this.position = BABYLON.Vector3.Zero();
  103600. this._scene = scene;
  103601. this._scene.reflectionProbes.push(this);
  103602. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  103603. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  103604. switch (faceIndex) {
  103605. case 0:
  103606. _this._add.copyFromFloats(1, 0, 0);
  103607. break;
  103608. case 1:
  103609. _this._add.copyFromFloats(-1, 0, 0);
  103610. break;
  103611. case 2:
  103612. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  103613. break;
  103614. case 3:
  103615. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  103616. break;
  103617. case 4:
  103618. _this._add.copyFromFloats(0, 0, 1);
  103619. break;
  103620. case 5:
  103621. _this._add.copyFromFloats(0, 0, -1);
  103622. break;
  103623. }
  103624. if (_this._attachedMesh) {
  103625. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  103626. }
  103627. _this.position.addToRef(_this._add, _this._target);
  103628. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  103629. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  103630. scene._forcedViewPosition = _this.position;
  103631. });
  103632. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  103633. scene._forcedViewPosition = null;
  103634. scene.updateTransformMatrix(true);
  103635. });
  103636. if (scene.activeCamera) {
  103637. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  103638. }
  103639. }
  103640. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  103641. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  103642. get: function () {
  103643. return this._renderTargetTexture.samples;
  103644. },
  103645. set: function (value) {
  103646. this._renderTargetTexture.samples = value;
  103647. },
  103648. enumerable: true,
  103649. configurable: true
  103650. });
  103651. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  103652. /** Gets or sets the refresh rate to use (on every frame by default) */
  103653. get: function () {
  103654. return this._renderTargetTexture.refreshRate;
  103655. },
  103656. set: function (value) {
  103657. this._renderTargetTexture.refreshRate = value;
  103658. },
  103659. enumerable: true,
  103660. configurable: true
  103661. });
  103662. /**
  103663. * Gets the hosting scene
  103664. * @returns a Scene
  103665. */
  103666. ReflectionProbe.prototype.getScene = function () {
  103667. return this._scene;
  103668. };
  103669. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  103670. /** Gets the internal CubeTexture used to render to */
  103671. get: function () {
  103672. return this._renderTargetTexture;
  103673. },
  103674. enumerable: true,
  103675. configurable: true
  103676. });
  103677. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  103678. /** Gets the list of meshes to render */
  103679. get: function () {
  103680. return this._renderTargetTexture.renderList;
  103681. },
  103682. enumerable: true,
  103683. configurable: true
  103684. });
  103685. /**
  103686. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  103687. * @param mesh defines the mesh to attach to
  103688. */
  103689. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  103690. this._attachedMesh = mesh;
  103691. };
  103692. /**
  103693. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  103694. * @param renderingGroupId The rendering group id corresponding to its index
  103695. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  103696. */
  103697. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  103698. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  103699. };
  103700. /**
  103701. * Clean all associated resources
  103702. */
  103703. ReflectionProbe.prototype.dispose = function () {
  103704. var index = this._scene.reflectionProbes.indexOf(this);
  103705. if (index !== -1) {
  103706. // Remove from the scene if found
  103707. this._scene.reflectionProbes.splice(index, 1);
  103708. }
  103709. if (this._renderTargetTexture) {
  103710. this._renderTargetTexture.dispose();
  103711. this._renderTargetTexture = null;
  103712. }
  103713. };
  103714. return ReflectionProbe;
  103715. }());
  103716. BABYLON.ReflectionProbe = ReflectionProbe;
  103717. })(BABYLON || (BABYLON = {}));
  103718. //# sourceMappingURL=babylon.reflectionProbe.js.map
  103719. var BABYLON;
  103720. (function (BABYLON) {
  103721. /**
  103722. * Defines the layer scene component responsible to manage any layers
  103723. * in a given scene.
  103724. */
  103725. var LayerSceneComponent = /** @class */ (function () {
  103726. /**
  103727. * Creates a new instance of the component for the given scene
  103728. * @param scene Defines the scene to register the component in
  103729. */
  103730. function LayerSceneComponent(scene) {
  103731. /**
  103732. * The component name helpfull to identify the component in the list of scene components.
  103733. */
  103734. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  103735. this.scene = scene;
  103736. this._engine = scene.getEngine();
  103737. scene.layers = new Array();
  103738. }
  103739. /**
  103740. * Registers the component in a given scene
  103741. */
  103742. LayerSceneComponent.prototype.register = function () {
  103743. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  103744. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  103745. };
  103746. /**
  103747. * Rebuilds the elements related to this component in case of
  103748. * context lost for instance.
  103749. */
  103750. LayerSceneComponent.prototype.rebuild = function () {
  103751. var layers = this.scene.layers;
  103752. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  103753. var layer = layers_1[_i];
  103754. layer._rebuild();
  103755. }
  103756. };
  103757. /**
  103758. * Disposes the component and the associated ressources.
  103759. */
  103760. LayerSceneComponent.prototype.dispose = function () {
  103761. var layers = this.scene.layers;
  103762. while (layers.length) {
  103763. layers[0].dispose();
  103764. }
  103765. };
  103766. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  103767. var layers = this.scene.layers;
  103768. if (layers.length) {
  103769. this._engine.setDepthBuffer(false);
  103770. var cameraLayerMask = camera.layerMask;
  103771. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  103772. var layer = layers_2[_i];
  103773. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  103774. layer.render();
  103775. }
  103776. }
  103777. this._engine.setDepthBuffer(true);
  103778. }
  103779. };
  103780. LayerSceneComponent.prototype._drawBackground = function (camera) {
  103781. this._draw(camera, true);
  103782. };
  103783. LayerSceneComponent.prototype._drawForeground = function (camera) {
  103784. this._draw(camera, false);
  103785. };
  103786. return LayerSceneComponent;
  103787. }());
  103788. BABYLON.LayerSceneComponent = LayerSceneComponent;
  103789. })(BABYLON || (BABYLON = {}));
  103790. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  103791. var BABYLON;
  103792. (function (BABYLON) {
  103793. var Layer = /** @class */ (function () {
  103794. function Layer(name, imgUrl, scene, isBackground, color) {
  103795. this.name = name;
  103796. this.scale = new BABYLON.Vector2(1, 1);
  103797. this.offset = new BABYLON.Vector2(0, 0);
  103798. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  103799. this.layerMask = 0x0FFFFFFF;
  103800. this._vertexBuffers = {};
  103801. // Events
  103802. /**
  103803. * An event triggered when the layer is disposed.
  103804. */
  103805. this.onDisposeObservable = new BABYLON.Observable();
  103806. /**
  103807. * An event triggered before rendering the scene
  103808. */
  103809. this.onBeforeRenderObservable = new BABYLON.Observable();
  103810. /**
  103811. * An event triggered after rendering the scene
  103812. */
  103813. this.onAfterRenderObservable = new BABYLON.Observable();
  103814. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  103815. this.isBackground = isBackground === undefined ? true : isBackground;
  103816. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  103817. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  103818. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  103819. if (!layerComponent) {
  103820. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  103821. this._scene._addComponent(layerComponent);
  103822. }
  103823. this._scene.layers.push(this);
  103824. var engine = this._scene.getEngine();
  103825. // VBO
  103826. var vertices = [];
  103827. vertices.push(1, 1);
  103828. vertices.push(-1, 1);
  103829. vertices.push(-1, -1);
  103830. vertices.push(1, -1);
  103831. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  103832. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  103833. this._createIndexBuffer();
  103834. // Effects
  103835. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  103836. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  103837. }
  103838. Object.defineProperty(Layer.prototype, "onDispose", {
  103839. set: function (callback) {
  103840. if (this._onDisposeObserver) {
  103841. this.onDisposeObservable.remove(this._onDisposeObserver);
  103842. }
  103843. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  103844. },
  103845. enumerable: true,
  103846. configurable: true
  103847. });
  103848. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  103849. set: function (callback) {
  103850. if (this._onBeforeRenderObserver) {
  103851. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  103852. }
  103853. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  103854. },
  103855. enumerable: true,
  103856. configurable: true
  103857. });
  103858. Object.defineProperty(Layer.prototype, "onAfterRender", {
  103859. set: function (callback) {
  103860. if (this._onAfterRenderObserver) {
  103861. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  103862. }
  103863. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  103864. },
  103865. enumerable: true,
  103866. configurable: true
  103867. });
  103868. Layer.prototype._createIndexBuffer = function () {
  103869. var engine = this._scene.getEngine();
  103870. // Indices
  103871. var indices = [];
  103872. indices.push(0);
  103873. indices.push(1);
  103874. indices.push(2);
  103875. indices.push(0);
  103876. indices.push(2);
  103877. indices.push(3);
  103878. this._indexBuffer = engine.createIndexBuffer(indices);
  103879. };
  103880. /** @hidden */
  103881. Layer.prototype._rebuild = function () {
  103882. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  103883. if (vb) {
  103884. vb._rebuild();
  103885. }
  103886. this._createIndexBuffer();
  103887. };
  103888. Layer.prototype.render = function () {
  103889. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  103890. // Check
  103891. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  103892. return;
  103893. var engine = this._scene.getEngine();
  103894. this.onBeforeRenderObservable.notifyObservers(this);
  103895. // Render
  103896. engine.enableEffect(currentEffect);
  103897. engine.setState(false);
  103898. // Texture
  103899. currentEffect.setTexture("textureSampler", this.texture);
  103900. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  103901. // Color
  103902. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  103903. // Scale / offset
  103904. currentEffect.setVector2("offset", this.offset);
  103905. currentEffect.setVector2("scale", this.scale);
  103906. // VBOs
  103907. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  103908. // Draw order
  103909. if (!this.alphaTest) {
  103910. engine.setAlphaMode(this.alphaBlendingMode);
  103911. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103912. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  103913. }
  103914. else {
  103915. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103916. }
  103917. this.onAfterRenderObservable.notifyObservers(this);
  103918. };
  103919. Layer.prototype.dispose = function () {
  103920. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  103921. if (vertexBuffer) {
  103922. vertexBuffer.dispose();
  103923. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  103924. }
  103925. if (this._indexBuffer) {
  103926. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  103927. this._indexBuffer = null;
  103928. }
  103929. if (this.texture) {
  103930. this.texture.dispose();
  103931. this.texture = null;
  103932. }
  103933. // Remove from scene
  103934. var index = this._scene.layers.indexOf(this);
  103935. this._scene.layers.splice(index, 1);
  103936. // Callback
  103937. this.onDisposeObservable.notifyObservers(this);
  103938. this.onDisposeObservable.clear();
  103939. this.onAfterRenderObservable.clear();
  103940. this.onBeforeRenderObservable.clear();
  103941. };
  103942. return Layer;
  103943. }());
  103944. BABYLON.Layer = Layer;
  103945. })(BABYLON || (BABYLON = {}));
  103946. //# sourceMappingURL=babylon.layer.js.map
  103947. var BABYLON;
  103948. (function (BABYLON) {
  103949. var TextureTools = /** @class */ (function () {
  103950. function TextureTools() {
  103951. }
  103952. /**
  103953. * Uses the GPU to create a copy texture rescaled at a given size
  103954. * @param texture Texture to copy from
  103955. * @param width Desired width
  103956. * @param height Desired height
  103957. * @return Generated texture
  103958. */
  103959. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  103960. if (useBilinearMode === void 0) { useBilinearMode = true; }
  103961. var scene = texture.getScene();
  103962. var engine = scene.getEngine();
  103963. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  103964. rtt.wrapU = texture.wrapU;
  103965. rtt.wrapV = texture.wrapV;
  103966. rtt.uOffset = texture.uOffset;
  103967. rtt.vOffset = texture.vOffset;
  103968. rtt.uScale = texture.uScale;
  103969. rtt.vScale = texture.vScale;
  103970. rtt.uAng = texture.uAng;
  103971. rtt.vAng = texture.vAng;
  103972. rtt.wAng = texture.wAng;
  103973. rtt.coordinatesIndex = texture.coordinatesIndex;
  103974. rtt.level = texture.level;
  103975. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  103976. rtt._texture.isReady = false;
  103977. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103978. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103979. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  103980. passPostProcess.getEffect().executeWhenCompiled(function () {
  103981. passPostProcess.onApply = function (effect) {
  103982. effect.setTexture("textureSampler", texture);
  103983. };
  103984. var internalTexture = rtt.getInternalTexture();
  103985. if (internalTexture) {
  103986. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  103987. engine.unBindFramebuffer(internalTexture);
  103988. rtt.disposeFramebufferObjects();
  103989. passPostProcess.dispose();
  103990. internalTexture.isReady = true;
  103991. }
  103992. });
  103993. return rtt;
  103994. };
  103995. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  103996. if (!scene._environmentBRDFTexture) {
  103997. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  103998. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103999. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104000. scene._environmentBRDFTexture = texture;
  104001. }
  104002. return scene._environmentBRDFTexture;
  104003. };
  104004. 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=";
  104005. return TextureTools;
  104006. }());
  104007. BABYLON.TextureTools = TextureTools;
  104008. })(BABYLON || (BABYLON = {}));
  104009. //# sourceMappingURL=babylon.textureTools.js.map
  104010. var BABYLON;
  104011. (function (BABYLON) {
  104012. var FramingBehavior = /** @class */ (function () {
  104013. function FramingBehavior() {
  104014. this._mode = FramingBehavior.FitFrustumSidesMode;
  104015. this._radiusScale = 1.0;
  104016. this._positionScale = 0.5;
  104017. this._defaultElevation = 0.3;
  104018. this._elevationReturnTime = 1500;
  104019. this._elevationReturnWaitTime = 1000;
  104020. this._zoomStopsAnimation = false;
  104021. this._framingTime = 1500;
  104022. this._isPointerDown = false;
  104023. this._lastInteractionTime = -Infinity;
  104024. // Framing control
  104025. this._animatables = new Array();
  104026. this._betaIsAnimating = false;
  104027. }
  104028. Object.defineProperty(FramingBehavior.prototype, "name", {
  104029. get: function () {
  104030. return "Framing";
  104031. },
  104032. enumerable: true,
  104033. configurable: true
  104034. });
  104035. Object.defineProperty(FramingBehavior.prototype, "mode", {
  104036. /**
  104037. * Gets current mode used by the behavior.
  104038. */
  104039. get: function () {
  104040. return this._mode;
  104041. },
  104042. /**
  104043. * Sets the current mode used by the behavior
  104044. */
  104045. set: function (mode) {
  104046. this._mode = mode;
  104047. },
  104048. enumerable: true,
  104049. configurable: true
  104050. });
  104051. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  104052. /**
  104053. * Gets the scale applied to the radius
  104054. */
  104055. get: function () {
  104056. return this._radiusScale;
  104057. },
  104058. /**
  104059. * Sets the scale applied to the radius (1 by default)
  104060. */
  104061. set: function (radius) {
  104062. this._radiusScale = radius;
  104063. },
  104064. enumerable: true,
  104065. configurable: true
  104066. });
  104067. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  104068. /**
  104069. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  104070. */
  104071. get: function () {
  104072. return this._positionScale;
  104073. },
  104074. /**
  104075. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  104076. */
  104077. set: function (scale) {
  104078. this._positionScale = scale;
  104079. },
  104080. enumerable: true,
  104081. configurable: true
  104082. });
  104083. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  104084. /**
  104085. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  104086. * behaviour is triggered, in radians.
  104087. */
  104088. get: function () {
  104089. return this._defaultElevation;
  104090. },
  104091. /**
  104092. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  104093. * behaviour is triggered, in radians.
  104094. */
  104095. set: function (elevation) {
  104096. this._defaultElevation = elevation;
  104097. },
  104098. enumerable: true,
  104099. configurable: true
  104100. });
  104101. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  104102. /**
  104103. * Gets the time (in milliseconds) taken to return to the default beta position.
  104104. * Negative value indicates camera should not return to default.
  104105. */
  104106. get: function () {
  104107. return this._elevationReturnTime;
  104108. },
  104109. /**
  104110. * Sets the time (in milliseconds) taken to return to the default beta position.
  104111. * Negative value indicates camera should not return to default.
  104112. */
  104113. set: function (speed) {
  104114. this._elevationReturnTime = speed;
  104115. },
  104116. enumerable: true,
  104117. configurable: true
  104118. });
  104119. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  104120. /**
  104121. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  104122. */
  104123. get: function () {
  104124. return this._elevationReturnWaitTime;
  104125. },
  104126. /**
  104127. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  104128. */
  104129. set: function (time) {
  104130. this._elevationReturnWaitTime = time;
  104131. },
  104132. enumerable: true,
  104133. configurable: true
  104134. });
  104135. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  104136. /**
  104137. * Gets the flag that indicates if user zooming should stop animation.
  104138. */
  104139. get: function () {
  104140. return this._zoomStopsAnimation;
  104141. },
  104142. /**
  104143. * Sets the flag that indicates if user zooming should stop animation.
  104144. */
  104145. set: function (flag) {
  104146. this._zoomStopsAnimation = flag;
  104147. },
  104148. enumerable: true,
  104149. configurable: true
  104150. });
  104151. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  104152. /**
  104153. * Gets the transition time when framing the mesh, in milliseconds
  104154. */
  104155. get: function () {
  104156. return this._framingTime;
  104157. },
  104158. /**
  104159. * Sets the transition time when framing the mesh, in milliseconds
  104160. */
  104161. set: function (time) {
  104162. this._framingTime = time;
  104163. },
  104164. enumerable: true,
  104165. configurable: true
  104166. });
  104167. FramingBehavior.prototype.init = function () {
  104168. // Do notihng
  104169. };
  104170. FramingBehavior.prototype.attach = function (camera) {
  104171. var _this = this;
  104172. this._attachedCamera = camera;
  104173. var scene = this._attachedCamera.getScene();
  104174. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  104175. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  104176. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  104177. _this._isPointerDown = true;
  104178. return;
  104179. }
  104180. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  104181. _this._isPointerDown = false;
  104182. }
  104183. });
  104184. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  104185. if (mesh) {
  104186. _this.zoomOnMesh(mesh);
  104187. }
  104188. });
  104189. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  104190. // Stop the animation if there is user interaction and the animation should stop for this interaction
  104191. _this._applyUserInteraction();
  104192. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  104193. // back to the default position after a given timeout
  104194. _this._maintainCameraAboveGround();
  104195. });
  104196. };
  104197. FramingBehavior.prototype.detach = function () {
  104198. if (!this._attachedCamera) {
  104199. return;
  104200. }
  104201. var scene = this._attachedCamera.getScene();
  104202. if (this._onPrePointerObservableObserver) {
  104203. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  104204. }
  104205. if (this._onAfterCheckInputsObserver) {
  104206. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  104207. }
  104208. if (this._onMeshTargetChangedObserver) {
  104209. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  104210. }
  104211. this._attachedCamera = null;
  104212. };
  104213. /**
  104214. * Targets the given mesh and updates zoom level accordingly.
  104215. * @param mesh The mesh to target.
  104216. * @param radius Optional. If a cached radius position already exists, overrides default.
  104217. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104218. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104219. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104220. */
  104221. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  104222. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104223. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104224. mesh.computeWorldMatrix(true);
  104225. var boundingBox = mesh.getBoundingInfo().boundingBox;
  104226. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  104227. };
  104228. /**
  104229. * Targets the given mesh with its children and updates zoom level accordingly.
  104230. * @param mesh The mesh to target.
  104231. * @param radius Optional. If a cached radius position already exists, overrides default.
  104232. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104233. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104234. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104235. */
  104236. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  104237. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104238. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104239. mesh.computeWorldMatrix(true);
  104240. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  104241. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  104242. };
  104243. /**
  104244. * Targets the given meshes with their children and updates zoom level accordingly.
  104245. * @param meshes The mesh to target.
  104246. * @param radius Optional. If a cached radius position already exists, overrides default.
  104247. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104248. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104249. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104250. */
  104251. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  104252. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104253. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104254. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  104255. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  104256. for (var i = 0; i < meshes.length; i++) {
  104257. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  104258. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  104259. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  104260. }
  104261. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  104262. };
  104263. /**
  104264. * Targets the given mesh and updates zoom level accordingly.
  104265. * @param mesh The mesh to target.
  104266. * @param radius Optional. If a cached radius position already exists, overrides default.
  104267. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104268. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104269. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104270. */
  104271. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  104272. var _this = this;
  104273. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104274. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104275. var zoomTarget;
  104276. if (!this._attachedCamera) {
  104277. return;
  104278. }
  104279. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  104280. var bottom = minimumWorld.y;
  104281. var top = maximumWorld.y;
  104282. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  104283. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  104284. if (focusOnOriginXZ) {
  104285. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  104286. }
  104287. else {
  104288. var centerWorld = minimumWorld.add(radiusWorld);
  104289. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  104290. }
  104291. if (!this._vectorTransition) {
  104292. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  104293. }
  104294. this._betaIsAnimating = true;
  104295. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  104296. if (animatable) {
  104297. this._animatables.push(animatable);
  104298. }
  104299. // sets the radius and lower radius bounds
  104300. // Small delta ensures camera is not always at lower zoom limit.
  104301. var radius = 0;
  104302. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  104303. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  104304. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  104305. radius = position;
  104306. }
  104307. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  104308. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  104309. if (this._attachedCamera.lowerRadiusLimit === null) {
  104310. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  104311. }
  104312. }
  104313. // Set sensibilities
  104314. var extend = maximumWorld.subtract(minimumWorld).length();
  104315. this._attachedCamera.panningSensibility = 5000 / extend;
  104316. this._attachedCamera.wheelPrecision = 100 / radius;
  104317. // transition to new radius
  104318. if (!this._radiusTransition) {
  104319. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  104320. }
  104321. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  104322. _this.stopAllAnimations();
  104323. if (onAnimationEnd) {
  104324. onAnimationEnd();
  104325. }
  104326. if (_this._attachedCamera) {
  104327. _this._attachedCamera.storeState();
  104328. }
  104329. });
  104330. if (animatable) {
  104331. this._animatables.push(animatable);
  104332. }
  104333. };
  104334. /**
  104335. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  104336. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  104337. * frustum width.
  104338. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  104339. * to fully enclose the mesh in the viewing frustum.
  104340. */
  104341. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  104342. var size = maximumWorld.subtract(minimumWorld);
  104343. var boxVectorGlobalDiagonal = size.length();
  104344. var frustumSlope = this._getFrustumSlope();
  104345. // Formula for setting distance
  104346. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  104347. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  104348. // Horizon distance
  104349. var radius = radiusWithoutFraming * this._radiusScale;
  104350. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  104351. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  104352. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  104353. var camera = this._attachedCamera;
  104354. if (!camera) {
  104355. return 0;
  104356. }
  104357. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  104358. // Don't exceed the requested limit
  104359. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  104360. }
  104361. // Don't exceed the upper radius limit
  104362. if (camera.upperRadiusLimit) {
  104363. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  104364. }
  104365. return distance;
  104366. };
  104367. /**
  104368. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  104369. * is automatically returned to its default position (expected to be above ground plane).
  104370. */
  104371. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  104372. var _this = this;
  104373. if (this._elevationReturnTime < 0) {
  104374. return;
  104375. }
  104376. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  104377. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  104378. var limitBeta = Math.PI * 0.5;
  104379. // Bring the camera back up if below the ground plane
  104380. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  104381. this._betaIsAnimating = true;
  104382. //Transition to new position
  104383. this.stopAllAnimations();
  104384. if (!this._betaTransition) {
  104385. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  104386. }
  104387. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  104388. _this._clearAnimationLocks();
  104389. _this.stopAllAnimations();
  104390. });
  104391. if (animatabe) {
  104392. this._animatables.push(animatabe);
  104393. }
  104394. }
  104395. };
  104396. /**
  104397. * Returns the frustum slope based on the canvas ratio and camera FOV
  104398. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  104399. */
  104400. FramingBehavior.prototype._getFrustumSlope = function () {
  104401. // Calculate the viewport ratio
  104402. // Aspect Ratio is Height/Width.
  104403. var camera = this._attachedCamera;
  104404. if (!camera) {
  104405. return BABYLON.Vector2.Zero();
  104406. }
  104407. var engine = camera.getScene().getEngine();
  104408. var aspectRatio = engine.getAspectRatio(camera);
  104409. // Camera FOV is the vertical field of view (top-bottom) in radians.
  104410. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  104411. var frustumSlopeY = Math.tan(camera.fov / 2);
  104412. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  104413. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  104414. // along the forward vector.
  104415. var frustumSlopeX = frustumSlopeY * aspectRatio;
  104416. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  104417. };
  104418. /**
  104419. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  104420. */
  104421. FramingBehavior.prototype._clearAnimationLocks = function () {
  104422. this._betaIsAnimating = false;
  104423. };
  104424. /**
  104425. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  104426. */
  104427. FramingBehavior.prototype._applyUserInteraction = function () {
  104428. if (this.isUserIsMoving) {
  104429. this._lastInteractionTime = BABYLON.Tools.Now;
  104430. this.stopAllAnimations();
  104431. this._clearAnimationLocks();
  104432. }
  104433. };
  104434. /**
  104435. * Stops and removes all animations that have been applied to the camera
  104436. */
  104437. FramingBehavior.prototype.stopAllAnimations = function () {
  104438. if (this._attachedCamera) {
  104439. this._attachedCamera.animations = [];
  104440. }
  104441. while (this._animatables.length) {
  104442. if (this._animatables[0]) {
  104443. this._animatables[0].onAnimationEnd = null;
  104444. this._animatables[0].stop();
  104445. }
  104446. this._animatables.shift();
  104447. }
  104448. };
  104449. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  104450. /**
  104451. * Gets a value indicating if the user is moving the camera
  104452. */
  104453. get: function () {
  104454. if (!this._attachedCamera) {
  104455. return false;
  104456. }
  104457. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  104458. this._attachedCamera.inertialBetaOffset !== 0 ||
  104459. this._attachedCamera.inertialRadiusOffset !== 0 ||
  104460. this._attachedCamera.inertialPanningX !== 0 ||
  104461. this._attachedCamera.inertialPanningY !== 0 ||
  104462. this._isPointerDown;
  104463. },
  104464. enumerable: true,
  104465. configurable: true
  104466. });
  104467. /**
  104468. * The easing function used by animations
  104469. */
  104470. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  104471. /**
  104472. * The easing mode used by animations
  104473. */
  104474. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  104475. // Statics
  104476. /**
  104477. * The camera can move all the way towards the mesh.
  104478. */
  104479. FramingBehavior.IgnoreBoundsSizeMode = 0;
  104480. /**
  104481. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  104482. */
  104483. FramingBehavior.FitFrustumSidesMode = 1;
  104484. return FramingBehavior;
  104485. }());
  104486. BABYLON.FramingBehavior = FramingBehavior;
  104487. })(BABYLON || (BABYLON = {}));
  104488. //# sourceMappingURL=babylon.framingBehavior.js.map
  104489. var BABYLON;
  104490. (function (BABYLON) {
  104491. /**
  104492. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  104493. */
  104494. var BouncingBehavior = /** @class */ (function () {
  104495. function BouncingBehavior() {
  104496. /**
  104497. * The duration of the animation, in milliseconds
  104498. */
  104499. this.transitionDuration = 450;
  104500. /**
  104501. * Length of the distance animated by the transition when lower radius is reached
  104502. */
  104503. this.lowerRadiusTransitionRange = 2;
  104504. /**
  104505. * Length of the distance animated by the transition when upper radius is reached
  104506. */
  104507. this.upperRadiusTransitionRange = -2;
  104508. this._autoTransitionRange = false;
  104509. // Animations
  104510. this._radiusIsAnimating = false;
  104511. this._radiusBounceTransition = null;
  104512. this._animatables = new Array();
  104513. }
  104514. Object.defineProperty(BouncingBehavior.prototype, "name", {
  104515. get: function () {
  104516. return "Bouncing";
  104517. },
  104518. enumerable: true,
  104519. configurable: true
  104520. });
  104521. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  104522. /**
  104523. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  104524. */
  104525. get: function () {
  104526. return this._autoTransitionRange;
  104527. },
  104528. /**
  104529. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  104530. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  104531. */
  104532. set: function (value) {
  104533. var _this = this;
  104534. if (this._autoTransitionRange === value) {
  104535. return;
  104536. }
  104537. this._autoTransitionRange = value;
  104538. var camera = this._attachedCamera;
  104539. if (!camera) {
  104540. return;
  104541. }
  104542. if (value) {
  104543. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  104544. if (!mesh) {
  104545. return;
  104546. }
  104547. mesh.computeWorldMatrix(true);
  104548. var diagonal = mesh.getBoundingInfo().diagonalLength;
  104549. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  104550. _this.upperRadiusTransitionRange = diagonal * 0.05;
  104551. });
  104552. }
  104553. else if (this._onMeshTargetChangedObserver) {
  104554. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  104555. }
  104556. },
  104557. enumerable: true,
  104558. configurable: true
  104559. });
  104560. BouncingBehavior.prototype.init = function () {
  104561. // Do notihng
  104562. };
  104563. BouncingBehavior.prototype.attach = function (camera) {
  104564. var _this = this;
  104565. this._attachedCamera = camera;
  104566. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  104567. if (!_this._attachedCamera) {
  104568. return;
  104569. }
  104570. // Add the bounce animation to the lower radius limit
  104571. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  104572. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  104573. }
  104574. // Add the bounce animation to the upper radius limit
  104575. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  104576. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  104577. }
  104578. });
  104579. };
  104580. BouncingBehavior.prototype.detach = function () {
  104581. if (!this._attachedCamera) {
  104582. return;
  104583. }
  104584. if (this._onAfterCheckInputsObserver) {
  104585. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  104586. }
  104587. if (this._onMeshTargetChangedObserver) {
  104588. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  104589. }
  104590. this._attachedCamera = null;
  104591. };
  104592. /**
  104593. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  104594. * @param radiusLimit The limit to check against.
  104595. * @return Bool to indicate if at limit.
  104596. */
  104597. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  104598. if (!this._attachedCamera) {
  104599. return false;
  104600. }
  104601. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  104602. return true;
  104603. }
  104604. return false;
  104605. };
  104606. /**
  104607. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  104608. * @param radiusDelta The delta by which to animate to. Can be negative.
  104609. */
  104610. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  104611. var _this = this;
  104612. if (!this._attachedCamera) {
  104613. return;
  104614. }
  104615. if (!this._radiusBounceTransition) {
  104616. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  104617. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  104618. }
  104619. // Prevent zoom until bounce has completed
  104620. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  104621. this._attachedCamera.wheelPrecision = Infinity;
  104622. this._attachedCamera.inertialRadiusOffset = 0;
  104623. // Animate to the radius limit
  104624. this.stopAllAnimations();
  104625. this._radiusIsAnimating = true;
  104626. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  104627. if (animatable) {
  104628. this._animatables.push(animatable);
  104629. }
  104630. };
  104631. /**
  104632. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  104633. */
  104634. BouncingBehavior.prototype._clearAnimationLocks = function () {
  104635. this._radiusIsAnimating = false;
  104636. if (this._attachedCamera) {
  104637. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  104638. }
  104639. };
  104640. /**
  104641. * Stops and removes all animations that have been applied to the camera
  104642. */
  104643. BouncingBehavior.prototype.stopAllAnimations = function () {
  104644. if (this._attachedCamera) {
  104645. this._attachedCamera.animations = [];
  104646. }
  104647. while (this._animatables.length) {
  104648. this._animatables[0].onAnimationEnd = null;
  104649. this._animatables[0].stop();
  104650. this._animatables.shift();
  104651. }
  104652. };
  104653. /**
  104654. * The easing function used by animations
  104655. */
  104656. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  104657. /**
  104658. * The easing mode used by animations
  104659. */
  104660. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  104661. return BouncingBehavior;
  104662. }());
  104663. BABYLON.BouncingBehavior = BouncingBehavior;
  104664. })(BABYLON || (BABYLON = {}));
  104665. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  104666. var BABYLON;
  104667. (function (BABYLON) {
  104668. var AutoRotationBehavior = /** @class */ (function () {
  104669. function AutoRotationBehavior() {
  104670. this._zoomStopsAnimation = false;
  104671. this._idleRotationSpeed = 0.05;
  104672. this._idleRotationWaitTime = 2000;
  104673. this._idleRotationSpinupTime = 2000;
  104674. this._isPointerDown = false;
  104675. this._lastFrameTime = null;
  104676. this._lastInteractionTime = -Infinity;
  104677. this._cameraRotationSpeed = 0;
  104678. this._lastFrameRadius = 0;
  104679. }
  104680. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  104681. get: function () {
  104682. return "AutoRotation";
  104683. },
  104684. enumerable: true,
  104685. configurable: true
  104686. });
  104687. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  104688. /**
  104689. * Gets the flag that indicates if user zooming should stop animation.
  104690. */
  104691. get: function () {
  104692. return this._zoomStopsAnimation;
  104693. },
  104694. /**
  104695. * Sets the flag that indicates if user zooming should stop animation.
  104696. */
  104697. set: function (flag) {
  104698. this._zoomStopsAnimation = flag;
  104699. },
  104700. enumerable: true,
  104701. configurable: true
  104702. });
  104703. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  104704. /**
  104705. * Gets the default speed at which the camera rotates around the model.
  104706. */
  104707. get: function () {
  104708. return this._idleRotationSpeed;
  104709. },
  104710. /**
  104711. * Sets the default speed at which the camera rotates around the model.
  104712. */
  104713. set: function (speed) {
  104714. this._idleRotationSpeed = speed;
  104715. },
  104716. enumerable: true,
  104717. configurable: true
  104718. });
  104719. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  104720. /**
  104721. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  104722. */
  104723. get: function () {
  104724. return this._idleRotationWaitTime;
  104725. },
  104726. /**
  104727. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  104728. */
  104729. set: function (time) {
  104730. this._idleRotationWaitTime = time;
  104731. },
  104732. enumerable: true,
  104733. configurable: true
  104734. });
  104735. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  104736. /**
  104737. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  104738. */
  104739. get: function () {
  104740. return this._idleRotationSpinupTime;
  104741. },
  104742. /**
  104743. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  104744. */
  104745. set: function (time) {
  104746. this._idleRotationSpinupTime = time;
  104747. },
  104748. enumerable: true,
  104749. configurable: true
  104750. });
  104751. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  104752. /**
  104753. * Gets a value indicating if the camera is currently rotating because of this behavior
  104754. */
  104755. get: function () {
  104756. return Math.abs(this._cameraRotationSpeed) > 0;
  104757. },
  104758. enumerable: true,
  104759. configurable: true
  104760. });
  104761. AutoRotationBehavior.prototype.init = function () {
  104762. // Do notihng
  104763. };
  104764. AutoRotationBehavior.prototype.attach = function (camera) {
  104765. var _this = this;
  104766. this._attachedCamera = camera;
  104767. var scene = this._attachedCamera.getScene();
  104768. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  104769. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  104770. _this._isPointerDown = true;
  104771. return;
  104772. }
  104773. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  104774. _this._isPointerDown = false;
  104775. }
  104776. });
  104777. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  104778. var now = BABYLON.Tools.Now;
  104779. var dt = 0;
  104780. if (_this._lastFrameTime != null) {
  104781. dt = now - _this._lastFrameTime;
  104782. }
  104783. _this._lastFrameTime = now;
  104784. // Stop the animation if there is user interaction and the animation should stop for this interaction
  104785. _this._applyUserInteraction();
  104786. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  104787. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  104788. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  104789. // Step camera rotation by rotation speed
  104790. if (_this._attachedCamera) {
  104791. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  104792. }
  104793. });
  104794. };
  104795. AutoRotationBehavior.prototype.detach = function () {
  104796. if (!this._attachedCamera) {
  104797. return;
  104798. }
  104799. var scene = this._attachedCamera.getScene();
  104800. if (this._onPrePointerObservableObserver) {
  104801. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  104802. }
  104803. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  104804. this._attachedCamera = null;
  104805. };
  104806. /**
  104807. * Returns true if user is scrolling.
  104808. * @return true if user is scrolling.
  104809. */
  104810. AutoRotationBehavior.prototype._userIsZooming = function () {
  104811. if (!this._attachedCamera) {
  104812. return false;
  104813. }
  104814. return this._attachedCamera.inertialRadiusOffset !== 0;
  104815. };
  104816. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  104817. if (!this._attachedCamera) {
  104818. return false;
  104819. }
  104820. var zoomHasHitLimit = false;
  104821. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  104822. zoomHasHitLimit = true;
  104823. }
  104824. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  104825. this._lastFrameRadius = this._attachedCamera.radius;
  104826. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  104827. };
  104828. /**
  104829. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  104830. */
  104831. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  104832. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  104833. this._lastInteractionTime = BABYLON.Tools.Now;
  104834. }
  104835. };
  104836. // Tools
  104837. AutoRotationBehavior.prototype._userIsMoving = function () {
  104838. if (!this._attachedCamera) {
  104839. return false;
  104840. }
  104841. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  104842. this._attachedCamera.inertialBetaOffset !== 0 ||
  104843. this._attachedCamera.inertialRadiusOffset !== 0 ||
  104844. this._attachedCamera.inertialPanningX !== 0 ||
  104845. this._attachedCamera.inertialPanningY !== 0 ||
  104846. this._isPointerDown;
  104847. };
  104848. return AutoRotationBehavior;
  104849. }());
  104850. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  104851. })(BABYLON || (BABYLON = {}));
  104852. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  104853. var BABYLON;
  104854. (function (BABYLON) {
  104855. var NullEngineOptions = /** @class */ (function () {
  104856. function NullEngineOptions() {
  104857. this.renderWidth = 512;
  104858. this.renderHeight = 256;
  104859. this.textureSize = 512;
  104860. this.deterministicLockstep = false;
  104861. this.lockstepMaxSteps = 4;
  104862. }
  104863. return NullEngineOptions;
  104864. }());
  104865. BABYLON.NullEngineOptions = NullEngineOptions;
  104866. /**
  104867. * The null engine class provides support for headless version of babylon.js.
  104868. * This can be used in server side scenario or for testing purposes
  104869. */
  104870. var NullEngine = /** @class */ (function (_super) {
  104871. __extends(NullEngine, _super);
  104872. function NullEngine(options) {
  104873. if (options === void 0) { options = new NullEngineOptions(); }
  104874. var _this = _super.call(this, null) || this;
  104875. if (options.deterministicLockstep === undefined) {
  104876. options.deterministicLockstep = false;
  104877. }
  104878. if (options.lockstepMaxSteps === undefined) {
  104879. options.lockstepMaxSteps = 4;
  104880. }
  104881. _this._options = options;
  104882. // Init caps
  104883. // We consider we are on a webgl1 capable device
  104884. _this._caps = new BABYLON.EngineCapabilities();
  104885. _this._caps.maxTexturesImageUnits = 16;
  104886. _this._caps.maxVertexTextureImageUnits = 16;
  104887. _this._caps.maxTextureSize = 512;
  104888. _this._caps.maxCubemapTextureSize = 512;
  104889. _this._caps.maxRenderTextureSize = 512;
  104890. _this._caps.maxVertexAttribs = 16;
  104891. _this._caps.maxVaryingVectors = 16;
  104892. _this._caps.maxFragmentUniformVectors = 16;
  104893. _this._caps.maxVertexUniformVectors = 16;
  104894. // Extensions
  104895. _this._caps.standardDerivatives = false;
  104896. _this._caps.astc = null;
  104897. _this._caps.s3tc = null;
  104898. _this._caps.pvrtc = null;
  104899. _this._caps.etc1 = null;
  104900. _this._caps.etc2 = null;
  104901. _this._caps.textureAnisotropicFilterExtension = null;
  104902. _this._caps.maxAnisotropy = 0;
  104903. _this._caps.uintIndices = false;
  104904. _this._caps.fragmentDepthSupported = false;
  104905. _this._caps.highPrecisionShaderSupported = true;
  104906. _this._caps.colorBufferFloat = false;
  104907. _this._caps.textureFloat = false;
  104908. _this._caps.textureFloatLinearFiltering = false;
  104909. _this._caps.textureFloatRender = false;
  104910. _this._caps.textureHalfFloat = false;
  104911. _this._caps.textureHalfFloatLinearFiltering = false;
  104912. _this._caps.textureHalfFloatRender = false;
  104913. _this._caps.textureLOD = false;
  104914. _this._caps.drawBuffersExtension = false;
  104915. _this._caps.depthTextureExtension = false;
  104916. _this._caps.vertexArrayObject = false;
  104917. _this._caps.instancedArrays = false;
  104918. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  104919. // Wrappers
  104920. if (typeof URL === "undefined") {
  104921. URL = {
  104922. createObjectURL: function () { },
  104923. revokeObjectURL: function () { }
  104924. };
  104925. }
  104926. if (typeof Blob === "undefined") {
  104927. Blob = function () { };
  104928. }
  104929. return _this;
  104930. }
  104931. NullEngine.prototype.isDeterministicLockStep = function () {
  104932. return this._options.deterministicLockstep;
  104933. };
  104934. NullEngine.prototype.getLockstepMaxSteps = function () {
  104935. return this._options.lockstepMaxSteps;
  104936. };
  104937. NullEngine.prototype.getHardwareScalingLevel = function () {
  104938. return 1.0;
  104939. };
  104940. NullEngine.prototype.createVertexBuffer = function (vertices) {
  104941. return {
  104942. capacity: 0,
  104943. references: 1,
  104944. is32Bits: false
  104945. };
  104946. };
  104947. NullEngine.prototype.createIndexBuffer = function (indices) {
  104948. return {
  104949. capacity: 0,
  104950. references: 1,
  104951. is32Bits: false
  104952. };
  104953. };
  104954. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  104955. if (stencil === void 0) { stencil = false; }
  104956. };
  104957. NullEngine.prototype.getRenderWidth = function (useScreen) {
  104958. if (useScreen === void 0) { useScreen = false; }
  104959. if (!useScreen && this._currentRenderTarget) {
  104960. return this._currentRenderTarget.width;
  104961. }
  104962. return this._options.renderWidth;
  104963. };
  104964. NullEngine.prototype.getRenderHeight = function (useScreen) {
  104965. if (useScreen === void 0) { useScreen = false; }
  104966. if (!useScreen && this._currentRenderTarget) {
  104967. return this._currentRenderTarget.height;
  104968. }
  104969. return this._options.renderHeight;
  104970. };
  104971. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  104972. this._cachedViewport = viewport;
  104973. };
  104974. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  104975. return {
  104976. transformFeedback: null,
  104977. __SPECTOR_rebuildProgram: null
  104978. };
  104979. };
  104980. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  104981. return [];
  104982. };
  104983. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  104984. return [];
  104985. };
  104986. NullEngine.prototype.bindSamplers = function (effect) {
  104987. this._currentEffect = null;
  104988. };
  104989. NullEngine.prototype.enableEffect = function (effect) {
  104990. this._currentEffect = effect;
  104991. if (effect.onBind) {
  104992. effect.onBind(effect);
  104993. }
  104994. if (effect._onBindObservable) {
  104995. effect._onBindObservable.notifyObservers(effect);
  104996. }
  104997. };
  104998. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  104999. if (zOffset === void 0) { zOffset = 0; }
  105000. if (reverseSide === void 0) { reverseSide = false; }
  105001. };
  105002. NullEngine.prototype.setIntArray = function (uniform, array) {
  105003. };
  105004. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  105005. };
  105006. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  105007. };
  105008. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  105009. };
  105010. NullEngine.prototype.setFloatArray = function (uniform, array) {
  105011. };
  105012. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  105013. };
  105014. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  105015. };
  105016. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  105017. };
  105018. NullEngine.prototype.setArray = function (uniform, array) {
  105019. };
  105020. NullEngine.prototype.setArray2 = function (uniform, array) {
  105021. };
  105022. NullEngine.prototype.setArray3 = function (uniform, array) {
  105023. };
  105024. NullEngine.prototype.setArray4 = function (uniform, array) {
  105025. };
  105026. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  105027. };
  105028. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  105029. };
  105030. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  105031. };
  105032. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  105033. };
  105034. NullEngine.prototype.setFloat = function (uniform, value) {
  105035. };
  105036. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  105037. };
  105038. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  105039. };
  105040. NullEngine.prototype.setBool = function (uniform, bool) {
  105041. };
  105042. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  105043. };
  105044. NullEngine.prototype.setColor3 = function (uniform, color3) {
  105045. };
  105046. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  105047. };
  105048. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  105049. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  105050. if (this._alphaMode === mode) {
  105051. return;
  105052. }
  105053. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  105054. if (!noDepthWriteChange) {
  105055. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  105056. }
  105057. this._alphaMode = mode;
  105058. };
  105059. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  105060. };
  105061. NullEngine.prototype.wipeCaches = function (bruteForce) {
  105062. if (this.preventCacheWipeBetweenFrames) {
  105063. return;
  105064. }
  105065. this.resetTextureCache();
  105066. this._currentEffect = null;
  105067. if (bruteForce) {
  105068. this._currentProgram = null;
  105069. this._stencilState.reset();
  105070. this._depthCullingState.reset();
  105071. this._alphaState.reset();
  105072. }
  105073. this._cachedVertexBuffers = null;
  105074. this._cachedIndexBuffer = null;
  105075. this._cachedEffectForVertexBuffers = null;
  105076. };
  105077. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  105078. };
  105079. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  105080. };
  105081. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  105082. };
  105083. /** @hidden */
  105084. NullEngine.prototype._createTexture = function () {
  105085. return {};
  105086. };
  105087. /** @hidden */
  105088. NullEngine.prototype._releaseTexture = function (texture) {
  105089. };
  105090. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  105091. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  105092. if (onLoad === void 0) { onLoad = null; }
  105093. if (onError === void 0) { onError = null; }
  105094. if (buffer === void 0) { buffer = null; }
  105095. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  105096. var url = String(urlArg);
  105097. texture.url = url;
  105098. texture.generateMipMaps = !noMipmap;
  105099. texture.samplingMode = samplingMode;
  105100. texture.invertY = invertY;
  105101. texture.baseWidth = this._options.textureSize;
  105102. texture.baseHeight = this._options.textureSize;
  105103. texture.width = this._options.textureSize;
  105104. texture.height = this._options.textureSize;
  105105. if (format) {
  105106. texture.format = format;
  105107. }
  105108. texture.isReady = true;
  105109. if (onLoad) {
  105110. onLoad();
  105111. }
  105112. this._internalTexturesCache.push(texture);
  105113. return texture;
  105114. };
  105115. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  105116. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  105117. if (options !== undefined && typeof options === "object") {
  105118. fullOptions.generateMipMaps = options.generateMipMaps;
  105119. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  105120. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  105121. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  105122. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  105123. }
  105124. else {
  105125. fullOptions.generateMipMaps = options;
  105126. fullOptions.generateDepthBuffer = true;
  105127. fullOptions.generateStencilBuffer = false;
  105128. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  105129. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  105130. }
  105131. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  105132. var width = size.width || size;
  105133. var height = size.height || size;
  105134. texture._depthStencilBuffer = {};
  105135. texture._framebuffer = {};
  105136. texture.baseWidth = width;
  105137. texture.baseHeight = height;
  105138. texture.width = width;
  105139. texture.height = height;
  105140. texture.isReady = true;
  105141. texture.samples = 1;
  105142. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  105143. texture.samplingMode = fullOptions.samplingMode;
  105144. texture.type = fullOptions.type;
  105145. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  105146. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  105147. this._internalTexturesCache.push(texture);
  105148. return texture;
  105149. };
  105150. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  105151. texture.samplingMode = samplingMode;
  105152. };
  105153. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  105154. if (this._currentRenderTarget) {
  105155. this.unBindFramebuffer(this._currentRenderTarget);
  105156. }
  105157. this._currentRenderTarget = texture;
  105158. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  105159. if (this._cachedViewport && !forceFullscreenViewport) {
  105160. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  105161. }
  105162. };
  105163. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  105164. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  105165. this._currentRenderTarget = null;
  105166. if (onBeforeUnbind) {
  105167. if (texture._MSAAFramebuffer) {
  105168. this._currentFramebuffer = texture._framebuffer;
  105169. }
  105170. onBeforeUnbind();
  105171. }
  105172. this._currentFramebuffer = null;
  105173. };
  105174. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  105175. var vbo = {
  105176. capacity: 1,
  105177. references: 1,
  105178. is32Bits: false
  105179. };
  105180. return vbo;
  105181. };
  105182. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  105183. if (premulAlpha === void 0) { premulAlpha = false; }
  105184. };
  105185. /**
  105186. * @hidden
  105187. * Get the current error code of the webGL context
  105188. * @returns the error code
  105189. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  105190. */
  105191. NullEngine.prototype.getError = function () {
  105192. return 0;
  105193. };
  105194. /** @hidden */
  105195. NullEngine.prototype._getUnpackAlignement = function () {
  105196. return 1;
  105197. };
  105198. /** @hidden */
  105199. NullEngine.prototype._unpackFlipY = function (value) {
  105200. };
  105201. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  105202. if (offset === void 0) { offset = 0; }
  105203. };
  105204. /**
  105205. * Updates a dynamic vertex buffer.
  105206. * @param vertexBuffer the vertex buffer to update
  105207. * @param data the data used to update the vertex buffer
  105208. * @param byteOffset the byte offset of the data (optional)
  105209. * @param byteLength the byte length of the data (optional)
  105210. */
  105211. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  105212. };
  105213. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  105214. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  105215. this._boundTexturesCache[this._activeChannel] = texture;
  105216. return true;
  105217. }
  105218. return false;
  105219. };
  105220. /** @hidden */
  105221. NullEngine.prototype._bindTexture = function (channel, texture) {
  105222. if (channel < 0) {
  105223. return;
  105224. }
  105225. this._bindTextureDirectly(0, texture);
  105226. };
  105227. /** @hidden */
  105228. NullEngine.prototype._releaseBuffer = function (buffer) {
  105229. buffer.references--;
  105230. if (buffer.references === 0) {
  105231. return true;
  105232. }
  105233. return false;
  105234. };
  105235. NullEngine.prototype.releaseEffects = function () {
  105236. };
  105237. NullEngine.prototype.displayLoadingUI = function () {
  105238. };
  105239. NullEngine.prototype.hideLoadingUI = function () {
  105240. };
  105241. /** @hidden */
  105242. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  105243. if (faceIndex === void 0) { faceIndex = 0; }
  105244. if (lod === void 0) { lod = 0; }
  105245. };
  105246. /** @hidden */
  105247. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  105248. if (faceIndex === void 0) { faceIndex = 0; }
  105249. if (lod === void 0) { lod = 0; }
  105250. };
  105251. /** @hidden */
  105252. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  105253. if (faceIndex === void 0) { faceIndex = 0; }
  105254. if (lod === void 0) { lod = 0; }
  105255. };
  105256. /** @hidden */
  105257. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  105258. if (faceIndex === void 0) { faceIndex = 0; }
  105259. if (lod === void 0) { lod = 0; }
  105260. };
  105261. return NullEngine;
  105262. }(BABYLON.Engine));
  105263. BABYLON.NullEngine = NullEngine;
  105264. })(BABYLON || (BABYLON = {}));
  105265. //# sourceMappingURL=babylon.nullEngine.js.map
  105266. var BABYLON;
  105267. (function (BABYLON) {
  105268. /**
  105269. * This class can be used to get instrumentation data from a Babylon engine
  105270. */
  105271. var EngineInstrumentation = /** @class */ (function () {
  105272. function EngineInstrumentation(engine) {
  105273. this.engine = engine;
  105274. this._captureGPUFrameTime = false;
  105275. this._gpuFrameTime = new BABYLON.PerfCounter();
  105276. this._captureShaderCompilationTime = false;
  105277. this._shaderCompilationTime = new BABYLON.PerfCounter();
  105278. // Observers
  105279. this._onBeginFrameObserver = null;
  105280. this._onEndFrameObserver = null;
  105281. this._onBeforeShaderCompilationObserver = null;
  105282. this._onAfterShaderCompilationObserver = null;
  105283. }
  105284. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  105285. // Properties
  105286. /**
  105287. * Gets the perf counter used for GPU frame time
  105288. */
  105289. get: function () {
  105290. return this._gpuFrameTime;
  105291. },
  105292. enumerable: true,
  105293. configurable: true
  105294. });
  105295. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  105296. /**
  105297. * Gets the GPU frame time capture status
  105298. */
  105299. get: function () {
  105300. return this._captureGPUFrameTime;
  105301. },
  105302. /**
  105303. * Enable or disable the GPU frame time capture
  105304. */
  105305. set: function (value) {
  105306. var _this = this;
  105307. if (value === this._captureGPUFrameTime) {
  105308. return;
  105309. }
  105310. this._captureGPUFrameTime = value;
  105311. if (value) {
  105312. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  105313. if (!_this._gpuFrameTimeToken) {
  105314. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  105315. }
  105316. });
  105317. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  105318. if (!_this._gpuFrameTimeToken) {
  105319. return;
  105320. }
  105321. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  105322. if (time > -1) {
  105323. _this._gpuFrameTimeToken = null;
  105324. _this._gpuFrameTime.fetchNewFrame();
  105325. _this._gpuFrameTime.addCount(time, true);
  105326. }
  105327. });
  105328. }
  105329. else {
  105330. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  105331. this._onBeginFrameObserver = null;
  105332. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  105333. this._onEndFrameObserver = null;
  105334. }
  105335. },
  105336. enumerable: true,
  105337. configurable: true
  105338. });
  105339. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  105340. /**
  105341. * Gets the perf counter used for shader compilation time
  105342. */
  105343. get: function () {
  105344. return this._shaderCompilationTime;
  105345. },
  105346. enumerable: true,
  105347. configurable: true
  105348. });
  105349. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  105350. /**
  105351. * Gets the shader compilation time capture status
  105352. */
  105353. get: function () {
  105354. return this._captureShaderCompilationTime;
  105355. },
  105356. /**
  105357. * Enable or disable the shader compilation time capture
  105358. */
  105359. set: function (value) {
  105360. var _this = this;
  105361. if (value === this._captureShaderCompilationTime) {
  105362. return;
  105363. }
  105364. this._captureShaderCompilationTime = value;
  105365. if (value) {
  105366. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  105367. _this._shaderCompilationTime.fetchNewFrame();
  105368. _this._shaderCompilationTime.beginMonitoring();
  105369. });
  105370. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  105371. _this._shaderCompilationTime.endMonitoring();
  105372. });
  105373. }
  105374. else {
  105375. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  105376. this._onBeforeShaderCompilationObserver = null;
  105377. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  105378. this._onAfterShaderCompilationObserver = null;
  105379. }
  105380. },
  105381. enumerable: true,
  105382. configurable: true
  105383. });
  105384. EngineInstrumentation.prototype.dispose = function () {
  105385. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  105386. this._onBeginFrameObserver = null;
  105387. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  105388. this._onEndFrameObserver = null;
  105389. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  105390. this._onBeforeShaderCompilationObserver = null;
  105391. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  105392. this._onAfterShaderCompilationObserver = null;
  105393. this.engine = null;
  105394. };
  105395. return EngineInstrumentation;
  105396. }());
  105397. BABYLON.EngineInstrumentation = EngineInstrumentation;
  105398. })(BABYLON || (BABYLON = {}));
  105399. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  105400. var BABYLON;
  105401. (function (BABYLON) {
  105402. /**
  105403. * This class can be used to get instrumentation data from a Babylon engine
  105404. */
  105405. var SceneInstrumentation = /** @class */ (function () {
  105406. function SceneInstrumentation(scene) {
  105407. var _this = this;
  105408. this.scene = scene;
  105409. this._captureActiveMeshesEvaluationTime = false;
  105410. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  105411. this._captureRenderTargetsRenderTime = false;
  105412. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  105413. this._captureFrameTime = false;
  105414. this._frameTime = new BABYLON.PerfCounter();
  105415. this._captureRenderTime = false;
  105416. this._renderTime = new BABYLON.PerfCounter();
  105417. this._captureInterFrameTime = false;
  105418. this._interFrameTime = new BABYLON.PerfCounter();
  105419. this._captureParticlesRenderTime = false;
  105420. this._particlesRenderTime = new BABYLON.PerfCounter();
  105421. this._captureSpritesRenderTime = false;
  105422. this._spritesRenderTime = new BABYLON.PerfCounter();
  105423. this._capturePhysicsTime = false;
  105424. this._physicsTime = new BABYLON.PerfCounter();
  105425. this._captureAnimationsTime = false;
  105426. this._animationsTime = new BABYLON.PerfCounter();
  105427. this._captureCameraRenderTime = false;
  105428. this._cameraRenderTime = new BABYLON.PerfCounter();
  105429. // Observers
  105430. this._onBeforeActiveMeshesEvaluationObserver = null;
  105431. this._onAfterActiveMeshesEvaluationObserver = null;
  105432. this._onBeforeRenderTargetsRenderObserver = null;
  105433. this._onAfterRenderTargetsRenderObserver = null;
  105434. this._onAfterRenderObserver = null;
  105435. this._onBeforeDrawPhaseObserver = null;
  105436. this._onAfterDrawPhaseObserver = null;
  105437. this._onBeforeAnimationsObserver = null;
  105438. this._onBeforeParticlesRenderingObserver = null;
  105439. this._onAfterParticlesRenderingObserver = null;
  105440. this._onBeforeSpritesRenderingObserver = null;
  105441. this._onAfterSpritesRenderingObserver = null;
  105442. this._onBeforePhysicsObserver = null;
  105443. this._onAfterPhysicsObserver = null;
  105444. this._onAfterAnimationsObserver = null;
  105445. this._onBeforeCameraRenderObserver = null;
  105446. this._onAfterCameraRenderObserver = null;
  105447. // Before render
  105448. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  105449. if (_this._captureActiveMeshesEvaluationTime) {
  105450. _this._activeMeshesEvaluationTime.fetchNewFrame();
  105451. }
  105452. if (_this._captureRenderTargetsRenderTime) {
  105453. _this._renderTargetsRenderTime.fetchNewFrame();
  105454. }
  105455. if (_this._captureFrameTime) {
  105456. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  105457. _this._frameTime.beginMonitoring();
  105458. }
  105459. if (_this._captureInterFrameTime) {
  105460. _this._interFrameTime.endMonitoring();
  105461. }
  105462. if (_this._captureParticlesRenderTime) {
  105463. _this._particlesRenderTime.fetchNewFrame();
  105464. }
  105465. if (_this._captureSpritesRenderTime) {
  105466. _this._spritesRenderTime.fetchNewFrame();
  105467. }
  105468. if (_this._captureAnimationsTime) {
  105469. _this._animationsTime.beginMonitoring();
  105470. }
  105471. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  105472. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  105473. });
  105474. // After render
  105475. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  105476. if (_this._captureFrameTime) {
  105477. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  105478. _this._frameTime.endMonitoring();
  105479. }
  105480. if (_this._captureRenderTime) {
  105481. _this._renderTime.endMonitoring(false);
  105482. }
  105483. if (_this._captureInterFrameTime) {
  105484. _this._interFrameTime.beginMonitoring();
  105485. }
  105486. });
  105487. }
  105488. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  105489. // Properties
  105490. /**
  105491. * Gets the perf counter used for active meshes evaluation time
  105492. */
  105493. get: function () {
  105494. return this._activeMeshesEvaluationTime;
  105495. },
  105496. enumerable: true,
  105497. configurable: true
  105498. });
  105499. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  105500. /**
  105501. * Gets the active meshes evaluation time capture status
  105502. */
  105503. get: function () {
  105504. return this._captureActiveMeshesEvaluationTime;
  105505. },
  105506. /**
  105507. * Enable or disable the active meshes evaluation time capture
  105508. */
  105509. set: function (value) {
  105510. var _this = this;
  105511. if (value === this._captureActiveMeshesEvaluationTime) {
  105512. return;
  105513. }
  105514. this._captureActiveMeshesEvaluationTime = value;
  105515. if (value) {
  105516. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  105517. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  105518. _this._activeMeshesEvaluationTime.beginMonitoring();
  105519. });
  105520. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  105521. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  105522. _this._activeMeshesEvaluationTime.endMonitoring();
  105523. });
  105524. }
  105525. else {
  105526. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  105527. this._onBeforeActiveMeshesEvaluationObserver = null;
  105528. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  105529. this._onAfterActiveMeshesEvaluationObserver = null;
  105530. }
  105531. },
  105532. enumerable: true,
  105533. configurable: true
  105534. });
  105535. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  105536. /**
  105537. * Gets the perf counter used for render targets render time
  105538. */
  105539. get: function () {
  105540. return this._renderTargetsRenderTime;
  105541. },
  105542. enumerable: true,
  105543. configurable: true
  105544. });
  105545. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  105546. /**
  105547. * Gets the render targets render time capture status
  105548. */
  105549. get: function () {
  105550. return this._captureRenderTargetsRenderTime;
  105551. },
  105552. /**
  105553. * Enable or disable the render targets render time capture
  105554. */
  105555. set: function (value) {
  105556. var _this = this;
  105557. if (value === this._captureRenderTargetsRenderTime) {
  105558. return;
  105559. }
  105560. this._captureRenderTargetsRenderTime = value;
  105561. if (value) {
  105562. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  105563. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  105564. _this._renderTargetsRenderTime.beginMonitoring();
  105565. });
  105566. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  105567. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  105568. _this._renderTargetsRenderTime.endMonitoring(false);
  105569. });
  105570. }
  105571. else {
  105572. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  105573. this._onBeforeRenderTargetsRenderObserver = null;
  105574. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  105575. this._onAfterRenderTargetsRenderObserver = null;
  105576. }
  105577. },
  105578. enumerable: true,
  105579. configurable: true
  105580. });
  105581. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  105582. /**
  105583. * Gets the perf counter used for particles render time
  105584. */
  105585. get: function () {
  105586. return this._particlesRenderTime;
  105587. },
  105588. enumerable: true,
  105589. configurable: true
  105590. });
  105591. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  105592. /**
  105593. * Gets the particles render time capture status
  105594. */
  105595. get: function () {
  105596. return this._captureParticlesRenderTime;
  105597. },
  105598. /**
  105599. * Enable or disable the particles render time capture
  105600. */
  105601. set: function (value) {
  105602. var _this = this;
  105603. if (value === this._captureParticlesRenderTime) {
  105604. return;
  105605. }
  105606. this._captureParticlesRenderTime = value;
  105607. if (value) {
  105608. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  105609. BABYLON.Tools.StartPerformanceCounter("Particles");
  105610. _this._particlesRenderTime.beginMonitoring();
  105611. });
  105612. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  105613. BABYLON.Tools.EndPerformanceCounter("Particles");
  105614. _this._particlesRenderTime.endMonitoring(false);
  105615. });
  105616. }
  105617. else {
  105618. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  105619. this._onBeforeParticlesRenderingObserver = null;
  105620. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  105621. this._onAfterParticlesRenderingObserver = null;
  105622. }
  105623. },
  105624. enumerable: true,
  105625. configurable: true
  105626. });
  105627. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  105628. /**
  105629. * Gets the perf counter used for sprites render time
  105630. */
  105631. get: function () {
  105632. return this._spritesRenderTime;
  105633. },
  105634. enumerable: true,
  105635. configurable: true
  105636. });
  105637. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  105638. /**
  105639. * Gets the sprites render time capture status
  105640. */
  105641. get: function () {
  105642. return this._captureSpritesRenderTime;
  105643. },
  105644. /**
  105645. * Enable or disable the sprites render time capture
  105646. */
  105647. set: function (value) {
  105648. var _this = this;
  105649. if (value === this._captureSpritesRenderTime) {
  105650. return;
  105651. }
  105652. this._captureSpritesRenderTime = value;
  105653. if (!this.scene.spriteManagers) {
  105654. return;
  105655. }
  105656. if (value) {
  105657. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  105658. BABYLON.Tools.StartPerformanceCounter("Sprites");
  105659. _this._spritesRenderTime.beginMonitoring();
  105660. });
  105661. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  105662. BABYLON.Tools.EndPerformanceCounter("Sprites");
  105663. _this._spritesRenderTime.endMonitoring(false);
  105664. });
  105665. }
  105666. else {
  105667. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  105668. this._onBeforeSpritesRenderingObserver = null;
  105669. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  105670. this._onAfterSpritesRenderingObserver = null;
  105671. }
  105672. },
  105673. enumerable: true,
  105674. configurable: true
  105675. });
  105676. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  105677. /**
  105678. * Gets the perf counter used for physics time
  105679. */
  105680. get: function () {
  105681. return this._physicsTime;
  105682. },
  105683. enumerable: true,
  105684. configurable: true
  105685. });
  105686. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  105687. /**
  105688. * Gets the physics time capture status
  105689. */
  105690. get: function () {
  105691. return this._capturePhysicsTime;
  105692. },
  105693. /**
  105694. * Enable or disable the physics time capture
  105695. */
  105696. set: function (value) {
  105697. var _this = this;
  105698. if (value === this._capturePhysicsTime) {
  105699. return;
  105700. }
  105701. this._capturePhysicsTime = value;
  105702. if (value) {
  105703. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  105704. BABYLON.Tools.StartPerformanceCounter("Physics");
  105705. _this._physicsTime.beginMonitoring();
  105706. });
  105707. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  105708. BABYLON.Tools.EndPerformanceCounter("Physics");
  105709. _this._physicsTime.endMonitoring();
  105710. });
  105711. }
  105712. else {
  105713. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  105714. this._onBeforePhysicsObserver = null;
  105715. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  105716. this._onAfterPhysicsObserver = null;
  105717. }
  105718. },
  105719. enumerable: true,
  105720. configurable: true
  105721. });
  105722. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  105723. /**
  105724. * Gets the perf counter used for animations time
  105725. */
  105726. get: function () {
  105727. return this._animationsTime;
  105728. },
  105729. enumerable: true,
  105730. configurable: true
  105731. });
  105732. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  105733. /**
  105734. * Gets the animations time capture status
  105735. */
  105736. get: function () {
  105737. return this._captureAnimationsTime;
  105738. },
  105739. /**
  105740. * Enable or disable the animations time capture
  105741. */
  105742. set: function (value) {
  105743. var _this = this;
  105744. if (value === this._captureAnimationsTime) {
  105745. return;
  105746. }
  105747. this._captureAnimationsTime = value;
  105748. if (value) {
  105749. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  105750. _this._animationsTime.endMonitoring();
  105751. });
  105752. }
  105753. else {
  105754. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  105755. this._onAfterAnimationsObserver = null;
  105756. }
  105757. },
  105758. enumerable: true,
  105759. configurable: true
  105760. });
  105761. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  105762. /**
  105763. * Gets the perf counter used for frame time capture
  105764. */
  105765. get: function () {
  105766. return this._frameTime;
  105767. },
  105768. enumerable: true,
  105769. configurable: true
  105770. });
  105771. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  105772. /**
  105773. * Gets the frame time capture status
  105774. */
  105775. get: function () {
  105776. return this._captureFrameTime;
  105777. },
  105778. /**
  105779. * Enable or disable the frame time capture
  105780. */
  105781. set: function (value) {
  105782. this._captureFrameTime = value;
  105783. },
  105784. enumerable: true,
  105785. configurable: true
  105786. });
  105787. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  105788. /**
  105789. * Gets the perf counter used for inter-frames time capture
  105790. */
  105791. get: function () {
  105792. return this._interFrameTime;
  105793. },
  105794. enumerable: true,
  105795. configurable: true
  105796. });
  105797. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  105798. /**
  105799. * Gets the inter-frames time capture status
  105800. */
  105801. get: function () {
  105802. return this._captureInterFrameTime;
  105803. },
  105804. /**
  105805. * Enable or disable the inter-frames time capture
  105806. */
  105807. set: function (value) {
  105808. this._captureInterFrameTime = value;
  105809. },
  105810. enumerable: true,
  105811. configurable: true
  105812. });
  105813. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  105814. /**
  105815. * Gets the perf counter used for render time capture
  105816. */
  105817. get: function () {
  105818. return this._renderTime;
  105819. },
  105820. enumerable: true,
  105821. configurable: true
  105822. });
  105823. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  105824. /**
  105825. * Gets the render time capture status
  105826. */
  105827. get: function () {
  105828. return this._captureRenderTime;
  105829. },
  105830. /**
  105831. * Enable or disable the render time capture
  105832. */
  105833. set: function (value) {
  105834. var _this = this;
  105835. if (value === this._captureRenderTime) {
  105836. return;
  105837. }
  105838. this._captureRenderTime = value;
  105839. if (value) {
  105840. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  105841. _this._renderTime.beginMonitoring();
  105842. BABYLON.Tools.StartPerformanceCounter("Main render");
  105843. });
  105844. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  105845. _this._renderTime.endMonitoring(false);
  105846. BABYLON.Tools.EndPerformanceCounter("Main render");
  105847. });
  105848. }
  105849. else {
  105850. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  105851. this._onBeforeDrawPhaseObserver = null;
  105852. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  105853. this._onAfterDrawPhaseObserver = null;
  105854. }
  105855. },
  105856. enumerable: true,
  105857. configurable: true
  105858. });
  105859. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  105860. /**
  105861. * Gets the perf counter used for camera render time capture
  105862. */
  105863. get: function () {
  105864. return this._cameraRenderTime;
  105865. },
  105866. enumerable: true,
  105867. configurable: true
  105868. });
  105869. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  105870. /**
  105871. * Gets the camera render time capture status
  105872. */
  105873. get: function () {
  105874. return this._captureCameraRenderTime;
  105875. },
  105876. /**
  105877. * Enable or disable the camera render time capture
  105878. */
  105879. set: function (value) {
  105880. var _this = this;
  105881. if (value === this._captureCameraRenderTime) {
  105882. return;
  105883. }
  105884. this._captureCameraRenderTime = value;
  105885. if (value) {
  105886. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  105887. _this._cameraRenderTime.beginMonitoring();
  105888. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  105889. });
  105890. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  105891. _this._cameraRenderTime.endMonitoring(false);
  105892. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  105893. });
  105894. }
  105895. else {
  105896. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  105897. this._onBeforeCameraRenderObserver = null;
  105898. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  105899. this._onAfterCameraRenderObserver = null;
  105900. }
  105901. },
  105902. enumerable: true,
  105903. configurable: true
  105904. });
  105905. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  105906. /**
  105907. * Gets the perf counter used for draw calls
  105908. */
  105909. get: function () {
  105910. return this.scene.getEngine()._drawCalls;
  105911. },
  105912. enumerable: true,
  105913. configurable: true
  105914. });
  105915. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  105916. /**
  105917. * Gets the perf counter used for texture collisions
  105918. */
  105919. get: function () {
  105920. return this.scene.getEngine()._textureCollisions;
  105921. },
  105922. enumerable: true,
  105923. configurable: true
  105924. });
  105925. SceneInstrumentation.prototype.dispose = function () {
  105926. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  105927. this._onAfterRenderObserver = null;
  105928. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  105929. this._onBeforeActiveMeshesEvaluationObserver = null;
  105930. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  105931. this._onAfterActiveMeshesEvaluationObserver = null;
  105932. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  105933. this._onBeforeRenderTargetsRenderObserver = null;
  105934. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  105935. this._onAfterRenderTargetsRenderObserver = null;
  105936. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  105937. this._onBeforeAnimationsObserver = null;
  105938. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  105939. this._onBeforeParticlesRenderingObserver = null;
  105940. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  105941. this._onAfterParticlesRenderingObserver = null;
  105942. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  105943. this._onBeforeSpritesRenderingObserver = null;
  105944. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  105945. this._onAfterSpritesRenderingObserver = null;
  105946. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  105947. this._onBeforeDrawPhaseObserver = null;
  105948. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  105949. this._onAfterDrawPhaseObserver = null;
  105950. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  105951. this._onBeforePhysicsObserver = null;
  105952. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  105953. this._onAfterPhysicsObserver = null;
  105954. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  105955. this._onAfterAnimationsObserver = null;
  105956. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  105957. this._onBeforeCameraRenderObserver = null;
  105958. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  105959. this._onAfterCameraRenderObserver = null;
  105960. this.scene = null;
  105961. };
  105962. return SceneInstrumentation;
  105963. }());
  105964. BABYLON.SceneInstrumentation = SceneInstrumentation;
  105965. })(BABYLON || (BABYLON = {}));
  105966. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  105967. var BABYLON;
  105968. (function (BABYLON) {
  105969. /**
  105970. * @hidden
  105971. **/
  105972. var _TimeToken = /** @class */ (function () {
  105973. function _TimeToken() {
  105974. this._timeElapsedQueryEnded = false;
  105975. }
  105976. return _TimeToken;
  105977. }());
  105978. BABYLON._TimeToken = _TimeToken;
  105979. })(BABYLON || (BABYLON = {}));
  105980. //# sourceMappingURL=babylon.timeToken.js.map
  105981. var BABYLON;
  105982. (function (BABYLON) {
  105983. /**
  105984. * Background material defines definition.
  105985. * @hidden Mainly internal Use
  105986. */
  105987. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  105988. __extends(BackgroundMaterialDefines, _super);
  105989. /**
  105990. * Constructor of the defines.
  105991. */
  105992. function BackgroundMaterialDefines() {
  105993. var _this = _super.call(this) || this;
  105994. /**
  105995. * True if the diffuse texture is in use.
  105996. */
  105997. _this.DIFFUSE = false;
  105998. /**
  105999. * The direct UV channel to use.
  106000. */
  106001. _this.DIFFUSEDIRECTUV = 0;
  106002. /**
  106003. * True if the diffuse texture is in gamma space.
  106004. */
  106005. _this.GAMMADIFFUSE = false;
  106006. /**
  106007. * True if the diffuse texture has opacity in the alpha channel.
  106008. */
  106009. _this.DIFFUSEHASALPHA = false;
  106010. /**
  106011. * True if you want the material to fade to transparent at grazing angle.
  106012. */
  106013. _this.OPACITYFRESNEL = false;
  106014. /**
  106015. * True if an extra blur needs to be added in the reflection.
  106016. */
  106017. _this.REFLECTIONBLUR = false;
  106018. /**
  106019. * True if you want the material to fade to reflection at grazing angle.
  106020. */
  106021. _this.REFLECTIONFRESNEL = false;
  106022. /**
  106023. * True if you want the material to falloff as far as you move away from the scene center.
  106024. */
  106025. _this.REFLECTIONFALLOFF = false;
  106026. /**
  106027. * False if the current Webgl implementation does not support the texture lod extension.
  106028. */
  106029. _this.TEXTURELODSUPPORT = false;
  106030. /**
  106031. * True to ensure the data are premultiplied.
  106032. */
  106033. _this.PREMULTIPLYALPHA = false;
  106034. /**
  106035. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  106036. */
  106037. _this.USERGBCOLOR = false;
  106038. /**
  106039. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  106040. * stays aligned with the desired configuration.
  106041. */
  106042. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  106043. /**
  106044. * True to add noise in order to reduce the banding effect.
  106045. */
  106046. _this.NOISE = false;
  106047. /**
  106048. * is the reflection texture in BGR color scheme?
  106049. * Mainly used to solve a bug in ios10 video tag
  106050. */
  106051. _this.REFLECTIONBGR = false;
  106052. _this.IMAGEPROCESSING = false;
  106053. _this.VIGNETTE = false;
  106054. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  106055. _this.VIGNETTEBLENDMODEOPAQUE = false;
  106056. _this.TONEMAPPING = false;
  106057. _this.TONEMAPPING_ACES = false;
  106058. _this.CONTRAST = false;
  106059. _this.COLORCURVES = false;
  106060. _this.COLORGRADING = false;
  106061. _this.COLORGRADING3D = false;
  106062. _this.SAMPLER3DGREENDEPTH = false;
  106063. _this.SAMPLER3DBGRMAP = false;
  106064. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  106065. _this.EXPOSURE = false;
  106066. // Reflection.
  106067. _this.REFLECTION = false;
  106068. _this.REFLECTIONMAP_3D = false;
  106069. _this.REFLECTIONMAP_SPHERICAL = false;
  106070. _this.REFLECTIONMAP_PLANAR = false;
  106071. _this.REFLECTIONMAP_CUBIC = false;
  106072. _this.REFLECTIONMAP_PROJECTION = false;
  106073. _this.REFLECTIONMAP_SKYBOX = false;
  106074. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  106075. _this.REFLECTIONMAP_EXPLICIT = false;
  106076. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  106077. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  106078. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  106079. _this.INVERTCUBICMAP = false;
  106080. _this.REFLECTIONMAP_OPPOSITEZ = false;
  106081. _this.LODINREFLECTIONALPHA = false;
  106082. _this.GAMMAREFLECTION = false;
  106083. _this.RGBDREFLECTION = false;
  106084. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  106085. // Default BJS.
  106086. _this.MAINUV1 = false;
  106087. _this.MAINUV2 = false;
  106088. _this.UV1 = false;
  106089. _this.UV2 = false;
  106090. _this.CLIPPLANE = false;
  106091. _this.CLIPPLANE2 = false;
  106092. _this.CLIPPLANE3 = false;
  106093. _this.CLIPPLANE4 = false;
  106094. _this.POINTSIZE = false;
  106095. _this.FOG = false;
  106096. _this.NORMAL = false;
  106097. _this.NUM_BONE_INFLUENCERS = 0;
  106098. _this.BonesPerMesh = 0;
  106099. _this.INSTANCES = false;
  106100. _this.SHADOWFLOAT = false;
  106101. _this.rebuild();
  106102. return _this;
  106103. }
  106104. return BackgroundMaterialDefines;
  106105. }(BABYLON.MaterialDefines));
  106106. /**
  106107. * Background material used to create an efficient environement around your scene.
  106108. */
  106109. var BackgroundMaterial = /** @class */ (function (_super) {
  106110. __extends(BackgroundMaterial, _super);
  106111. /**
  106112. * Instantiates a Background Material in the given scene
  106113. * @param name The friendly name of the material
  106114. * @param scene The scene to add the material to
  106115. */
  106116. function BackgroundMaterial(name, scene) {
  106117. var _this = _super.call(this, name, scene) || this;
  106118. /**
  106119. * Key light Color (multiply against the environement texture)
  106120. */
  106121. _this.primaryColor = BABYLON.Color3.White();
  106122. _this._primaryColorShadowLevel = 0;
  106123. _this._primaryColorHighlightLevel = 0;
  106124. /**
  106125. * Reflection Texture used in the material.
  106126. * Should be author in a specific way for the best result (refer to the documentation).
  106127. */
  106128. _this.reflectionTexture = null;
  106129. /**
  106130. * Reflection Texture level of blur.
  106131. *
  106132. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  106133. * texture twice.
  106134. */
  106135. _this.reflectionBlur = 0;
  106136. /**
  106137. * Diffuse Texture used in the material.
  106138. * Should be author in a specific way for the best result (refer to the documentation).
  106139. */
  106140. _this.diffuseTexture = null;
  106141. _this._shadowLights = null;
  106142. /**
  106143. * Specify the list of lights casting shadow on the material.
  106144. * All scene shadow lights will be included if null.
  106145. */
  106146. _this.shadowLights = null;
  106147. /**
  106148. * Helps adjusting the shadow to a softer level if required.
  106149. * 0 means black shadows and 1 means no shadows.
  106150. */
  106151. _this.shadowLevel = 0;
  106152. /**
  106153. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  106154. * It is usually zero but might be interesting to modify according to your setup.
  106155. */
  106156. _this.sceneCenter = BABYLON.Vector3.Zero();
  106157. /**
  106158. * This helps specifying that the material is falling off to the sky box at grazing angle.
  106159. * This helps ensuring a nice transition when the camera goes under the ground.
  106160. */
  106161. _this.opacityFresnel = true;
  106162. /**
  106163. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  106164. * This helps adding a mirror texture on the ground.
  106165. */
  106166. _this.reflectionFresnel = false;
  106167. /**
  106168. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  106169. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  106170. */
  106171. _this.reflectionFalloffDistance = 0.0;
  106172. /**
  106173. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  106174. */
  106175. _this.reflectionAmount = 1.0;
  106176. /**
  106177. * This specifies the weight of the reflection at grazing angle.
  106178. */
  106179. _this.reflectionReflectance0 = 0.05;
  106180. /**
  106181. * This specifies the weight of the reflection at a perpendicular point of view.
  106182. */
  106183. _this.reflectionReflectance90 = 0.5;
  106184. /**
  106185. * Helps to directly use the maps channels instead of their level.
  106186. */
  106187. _this.useRGBColor = true;
  106188. /**
  106189. * This helps reducing the banding effect that could occur on the background.
  106190. */
  106191. _this.enableNoise = false;
  106192. _this._fovMultiplier = 1.0;
  106193. /**
  106194. * Enable the FOV adjustment feature controlled by fovMultiplier.
  106195. */
  106196. _this.useEquirectangularFOV = false;
  106197. _this._maxSimultaneousLights = 4;
  106198. /**
  106199. * Number of Simultaneous lights allowed on the material.
  106200. */
  106201. _this.maxSimultaneousLights = 4;
  106202. /**
  106203. * Keep track of the image processing observer to allow dispose and replace.
  106204. */
  106205. _this._imageProcessingObserver = null;
  106206. /**
  106207. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  106208. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  106209. */
  106210. _this.switchToBGR = false;
  106211. // Temp values kept as cache in the material.
  106212. _this._renderTargets = new BABYLON.SmartArray(16);
  106213. _this._reflectionControls = BABYLON.Vector4.Zero();
  106214. _this._white = BABYLON.Color3.White();
  106215. _this._primaryShadowColor = BABYLON.Color3.Black();
  106216. _this._primaryHighlightColor = BABYLON.Color3.Black();
  106217. // Setup the default processing configuration to the scene.
  106218. _this._attachImageProcessingConfiguration(null);
  106219. _this.getRenderTargetTextures = function () {
  106220. _this._renderTargets.reset();
  106221. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  106222. _this._renderTargets.push(_this._diffuseTexture);
  106223. }
  106224. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  106225. _this._renderTargets.push(_this._reflectionTexture);
  106226. }
  106227. return _this._renderTargets;
  106228. };
  106229. return _this;
  106230. }
  106231. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  106232. /**
  106233. * Experimental Internal Use Only.
  106234. *
  106235. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  106236. * This acts as a helper to set the primary color to a more "human friendly" value.
  106237. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  106238. * output color as close as possible from the chosen value.
  106239. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  106240. * part of lighting setup.)
  106241. */
  106242. get: function () {
  106243. return this.__perceptualColor;
  106244. },
  106245. set: function (value) {
  106246. this.__perceptualColor = value;
  106247. this._computePrimaryColorFromPerceptualColor();
  106248. this._markAllSubMeshesAsLightsDirty();
  106249. },
  106250. enumerable: true,
  106251. configurable: true
  106252. });
  106253. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  106254. /**
  106255. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  106256. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  106257. */
  106258. get: function () {
  106259. return this._primaryColorShadowLevel;
  106260. },
  106261. set: function (value) {
  106262. this._primaryColorShadowLevel = value;
  106263. this._computePrimaryColors();
  106264. this._markAllSubMeshesAsLightsDirty();
  106265. },
  106266. enumerable: true,
  106267. configurable: true
  106268. });
  106269. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  106270. /**
  106271. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  106272. * The primary color is used at the level chosen to define what the white area would look.
  106273. */
  106274. get: function () {
  106275. return this._primaryColorHighlightLevel;
  106276. },
  106277. set: function (value) {
  106278. this._primaryColorHighlightLevel = value;
  106279. this._computePrimaryColors();
  106280. this._markAllSubMeshesAsLightsDirty();
  106281. },
  106282. enumerable: true,
  106283. configurable: true
  106284. });
  106285. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  106286. /**
  106287. * Sets the reflection reflectance fresnel values according to the default standard
  106288. * empirically know to work well :-)
  106289. */
  106290. set: function (value) {
  106291. var reflectionWeight = value;
  106292. if (reflectionWeight < 0.5) {
  106293. reflectionWeight = reflectionWeight * 2.0;
  106294. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  106295. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  106296. }
  106297. else {
  106298. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  106299. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  106300. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  106301. }
  106302. },
  106303. enumerable: true,
  106304. configurable: true
  106305. });
  106306. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  106307. /**
  106308. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  106309. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  106310. * Recommended to be keep at 1.0 except for special cases.
  106311. */
  106312. get: function () {
  106313. return this._fovMultiplier;
  106314. },
  106315. set: function (value) {
  106316. if (isNaN(value)) {
  106317. value = 1.0;
  106318. }
  106319. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  106320. },
  106321. enumerable: true,
  106322. configurable: true
  106323. });
  106324. /**
  106325. * Attaches a new image processing configuration to the PBR Material.
  106326. * @param configuration (if null the scene configuration will be use)
  106327. */
  106328. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  106329. var _this = this;
  106330. if (configuration === this._imageProcessingConfiguration) {
  106331. return;
  106332. }
  106333. // Detaches observer.
  106334. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  106335. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  106336. }
  106337. // Pick the scene configuration if needed.
  106338. if (!configuration) {
  106339. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  106340. }
  106341. else {
  106342. this._imageProcessingConfiguration = configuration;
  106343. }
  106344. // Attaches observer.
  106345. if (this._imageProcessingConfiguration) {
  106346. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  106347. _this._computePrimaryColorFromPerceptualColor();
  106348. _this._markAllSubMeshesAsImageProcessingDirty();
  106349. });
  106350. }
  106351. };
  106352. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  106353. /**
  106354. * Gets the image processing configuration used either in this material.
  106355. */
  106356. get: function () {
  106357. return this._imageProcessingConfiguration;
  106358. },
  106359. /**
  106360. * Sets the Default image processing configuration used either in the this material.
  106361. *
  106362. * If sets to null, the scene one is in use.
  106363. */
  106364. set: function (value) {
  106365. this._attachImageProcessingConfiguration(value);
  106366. // Ensure the effect will be rebuilt.
  106367. this._markAllSubMeshesAsTexturesDirty();
  106368. },
  106369. enumerable: true,
  106370. configurable: true
  106371. });
  106372. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  106373. /**
  106374. * Gets wether the color curves effect is enabled.
  106375. */
  106376. get: function () {
  106377. return this.imageProcessingConfiguration.colorCurvesEnabled;
  106378. },
  106379. /**
  106380. * Sets wether the color curves effect is enabled.
  106381. */
  106382. set: function (value) {
  106383. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  106384. },
  106385. enumerable: true,
  106386. configurable: true
  106387. });
  106388. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  106389. /**
  106390. * Gets wether the color grading effect is enabled.
  106391. */
  106392. get: function () {
  106393. return this.imageProcessingConfiguration.colorGradingEnabled;
  106394. },
  106395. /**
  106396. * Gets wether the color grading effect is enabled.
  106397. */
  106398. set: function (value) {
  106399. this.imageProcessingConfiguration.colorGradingEnabled = value;
  106400. },
  106401. enumerable: true,
  106402. configurable: true
  106403. });
  106404. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  106405. /**
  106406. * Gets wether tonemapping is enabled or not.
  106407. */
  106408. get: function () {
  106409. return this._imageProcessingConfiguration.toneMappingEnabled;
  106410. },
  106411. /**
  106412. * Sets wether tonemapping is enabled or not
  106413. */
  106414. set: function (value) {
  106415. this._imageProcessingConfiguration.toneMappingEnabled = value;
  106416. },
  106417. enumerable: true,
  106418. configurable: true
  106419. });
  106420. ;
  106421. ;
  106422. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  106423. /**
  106424. * The camera exposure used on this material.
  106425. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  106426. * This corresponds to a photographic exposure.
  106427. */
  106428. get: function () {
  106429. return this._imageProcessingConfiguration.exposure;
  106430. },
  106431. /**
  106432. * The camera exposure used on this material.
  106433. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  106434. * This corresponds to a photographic exposure.
  106435. */
  106436. set: function (value) {
  106437. this._imageProcessingConfiguration.exposure = value;
  106438. },
  106439. enumerable: true,
  106440. configurable: true
  106441. });
  106442. ;
  106443. ;
  106444. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  106445. /**
  106446. * Gets The camera contrast used on this material.
  106447. */
  106448. get: function () {
  106449. return this._imageProcessingConfiguration.contrast;
  106450. },
  106451. /**
  106452. * Sets The camera contrast used on this material.
  106453. */
  106454. set: function (value) {
  106455. this._imageProcessingConfiguration.contrast = value;
  106456. },
  106457. enumerable: true,
  106458. configurable: true
  106459. });
  106460. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  106461. /**
  106462. * Gets the Color Grading 2D Lookup Texture.
  106463. */
  106464. get: function () {
  106465. return this._imageProcessingConfiguration.colorGradingTexture;
  106466. },
  106467. /**
  106468. * Sets the Color Grading 2D Lookup Texture.
  106469. */
  106470. set: function (value) {
  106471. this.imageProcessingConfiguration.colorGradingTexture = value;
  106472. },
  106473. enumerable: true,
  106474. configurable: true
  106475. });
  106476. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  106477. /**
  106478. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  106479. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  106480. * 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;
  106481. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  106482. */
  106483. get: function () {
  106484. return this.imageProcessingConfiguration.colorCurves;
  106485. },
  106486. /**
  106487. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  106488. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  106489. * 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;
  106490. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  106491. */
  106492. set: function (value) {
  106493. this.imageProcessingConfiguration.colorCurves = value;
  106494. },
  106495. enumerable: true,
  106496. configurable: true
  106497. });
  106498. /**
  106499. * The entire material has been created in order to prevent overdraw.
  106500. * @returns false
  106501. */
  106502. BackgroundMaterial.prototype.needAlphaTesting = function () {
  106503. return true;
  106504. };
  106505. /**
  106506. * The entire material has been created in order to prevent overdraw.
  106507. * @returns true if blending is enable
  106508. */
  106509. BackgroundMaterial.prototype.needAlphaBlending = function () {
  106510. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  106511. };
  106512. /**
  106513. * Checks wether the material is ready to be rendered for a given mesh.
  106514. * @param mesh The mesh to render
  106515. * @param subMesh The submesh to check against
  106516. * @param useInstances Specify wether or not the material is used with instances
  106517. * @returns true if all the dependencies are ready (Textures, Effects...)
  106518. */
  106519. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  106520. var _this = this;
  106521. if (useInstances === void 0) { useInstances = false; }
  106522. if (subMesh.effect && this.isFrozen) {
  106523. if (this._wasPreviouslyReady) {
  106524. return true;
  106525. }
  106526. }
  106527. if (!subMesh._materialDefines) {
  106528. subMesh._materialDefines = new BackgroundMaterialDefines();
  106529. }
  106530. var scene = this.getScene();
  106531. var defines = subMesh._materialDefines;
  106532. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  106533. if (defines._renderId === scene.getRenderId()) {
  106534. return true;
  106535. }
  106536. }
  106537. var engine = scene.getEngine();
  106538. // Lights
  106539. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  106540. defines._needNormals = true;
  106541. // Textures
  106542. if (defines._areTexturesDirty) {
  106543. defines._needUVs = false;
  106544. if (scene.texturesEnabled) {
  106545. if (scene.getEngine().getCaps().textureLOD) {
  106546. defines.TEXTURELODSUPPORT = true;
  106547. }
  106548. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  106549. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  106550. return false;
  106551. }
  106552. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  106553. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  106554. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  106555. defines.OPACITYFRESNEL = this._opacityFresnel;
  106556. }
  106557. else {
  106558. defines.DIFFUSE = false;
  106559. defines.DIFFUSEHASALPHA = false;
  106560. defines.GAMMADIFFUSE = false;
  106561. defines.OPACITYFRESNEL = false;
  106562. }
  106563. var reflectionTexture = this._reflectionTexture;
  106564. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  106565. if (!reflectionTexture.isReadyOrNotBlocking()) {
  106566. return false;
  106567. }
  106568. defines.REFLECTION = true;
  106569. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  106570. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  106571. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  106572. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  106573. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  106574. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  106575. defines.REFLECTIONBGR = this.switchToBGR;
  106576. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  106577. defines.INVERTCUBICMAP = true;
  106578. }
  106579. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  106580. switch (reflectionTexture.coordinatesMode) {
  106581. case BABYLON.Texture.EXPLICIT_MODE:
  106582. defines.REFLECTIONMAP_EXPLICIT = true;
  106583. break;
  106584. case BABYLON.Texture.PLANAR_MODE:
  106585. defines.REFLECTIONMAP_PLANAR = true;
  106586. break;
  106587. case BABYLON.Texture.PROJECTION_MODE:
  106588. defines.REFLECTIONMAP_PROJECTION = true;
  106589. break;
  106590. case BABYLON.Texture.SKYBOX_MODE:
  106591. defines.REFLECTIONMAP_SKYBOX = true;
  106592. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  106593. break;
  106594. case BABYLON.Texture.SPHERICAL_MODE:
  106595. defines.REFLECTIONMAP_SPHERICAL = true;
  106596. break;
  106597. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  106598. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  106599. break;
  106600. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  106601. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  106602. break;
  106603. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  106604. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  106605. break;
  106606. case BABYLON.Texture.CUBIC_MODE:
  106607. case BABYLON.Texture.INVCUBIC_MODE:
  106608. default:
  106609. defines.REFLECTIONMAP_CUBIC = true;
  106610. break;
  106611. }
  106612. if (this.reflectionFresnel) {
  106613. defines.REFLECTIONFRESNEL = true;
  106614. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  106615. this._reflectionControls.x = this.reflectionAmount;
  106616. this._reflectionControls.y = this.reflectionReflectance0;
  106617. this._reflectionControls.z = this.reflectionReflectance90;
  106618. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  106619. }
  106620. else {
  106621. defines.REFLECTIONFRESNEL = false;
  106622. defines.REFLECTIONFALLOFF = false;
  106623. }
  106624. }
  106625. else {
  106626. defines.REFLECTION = false;
  106627. defines.REFLECTIONFRESNEL = false;
  106628. defines.REFLECTIONFALLOFF = false;
  106629. defines.REFLECTIONBLUR = false;
  106630. defines.REFLECTIONMAP_3D = false;
  106631. defines.REFLECTIONMAP_SPHERICAL = false;
  106632. defines.REFLECTIONMAP_PLANAR = false;
  106633. defines.REFLECTIONMAP_CUBIC = false;
  106634. defines.REFLECTIONMAP_PROJECTION = false;
  106635. defines.REFLECTIONMAP_SKYBOX = false;
  106636. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  106637. defines.REFLECTIONMAP_EXPLICIT = false;
  106638. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  106639. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  106640. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  106641. defines.INVERTCUBICMAP = false;
  106642. defines.REFLECTIONMAP_OPPOSITEZ = false;
  106643. defines.LODINREFLECTIONALPHA = false;
  106644. defines.GAMMAREFLECTION = false;
  106645. defines.RGBDREFLECTION = false;
  106646. }
  106647. }
  106648. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  106649. defines.USERGBCOLOR = this._useRGBColor;
  106650. defines.NOISE = this._enableNoise;
  106651. }
  106652. if (defines._areLightsDirty) {
  106653. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  106654. }
  106655. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  106656. if (!this._imageProcessingConfiguration.isReady()) {
  106657. return false;
  106658. }
  106659. this._imageProcessingConfiguration.prepareDefines(defines);
  106660. }
  106661. // Misc.
  106662. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  106663. // Values that need to be evaluated on every frame
  106664. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  106665. // Attribs
  106666. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  106667. if (mesh) {
  106668. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  106669. mesh.createNormals(true);
  106670. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  106671. }
  106672. }
  106673. }
  106674. // Get correct effect
  106675. if (defines.isDirty) {
  106676. defines.markAsProcessed();
  106677. scene.resetCachedMaterial();
  106678. // Fallbacks
  106679. var fallbacks = new BABYLON.EffectFallbacks();
  106680. if (defines.FOG) {
  106681. fallbacks.addFallback(0, "FOG");
  106682. }
  106683. if (defines.POINTSIZE) {
  106684. fallbacks.addFallback(1, "POINTSIZE");
  106685. }
  106686. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  106687. if (defines.NUM_BONE_INFLUENCERS > 0) {
  106688. fallbacks.addCPUSkinningFallback(0, mesh);
  106689. }
  106690. //Attributes
  106691. var attribs = [BABYLON.VertexBuffer.PositionKind];
  106692. if (defines.NORMAL) {
  106693. attribs.push(BABYLON.VertexBuffer.NormalKind);
  106694. }
  106695. if (defines.UV1) {
  106696. attribs.push(BABYLON.VertexBuffer.UVKind);
  106697. }
  106698. if (defines.UV2) {
  106699. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  106700. }
  106701. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  106702. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  106703. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  106704. "vFogInfos", "vFogColor", "pointSize",
  106705. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  106706. "vPrimaryColor", "vPrimaryColorShadow",
  106707. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  106708. "shadowLevel", "alpha",
  106709. "vBackgroundCenter", "vReflectionControl",
  106710. "vDiffuseInfos", "diffuseMatrix",
  106711. ];
  106712. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  106713. var uniformBuffers = ["Material", "Scene"];
  106714. if (BABYLON.ImageProcessingConfiguration) {
  106715. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  106716. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  106717. }
  106718. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  106719. uniformsNames: uniforms,
  106720. uniformBuffersNames: uniformBuffers,
  106721. samplers: samplers,
  106722. defines: defines,
  106723. maxSimultaneousLights: this._maxSimultaneousLights
  106724. });
  106725. var onCompiled = function (effect) {
  106726. if (_this.onCompiled) {
  106727. _this.onCompiled(effect);
  106728. }
  106729. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  106730. };
  106731. var join = defines.toString();
  106732. subMesh.setEffect(scene.getEngine().createEffect("background", {
  106733. attributes: attribs,
  106734. uniformsNames: uniforms,
  106735. uniformBuffersNames: uniformBuffers,
  106736. samplers: samplers,
  106737. defines: join,
  106738. fallbacks: fallbacks,
  106739. onCompiled: onCompiled,
  106740. onError: this.onError,
  106741. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  106742. }, engine), defines);
  106743. this.buildUniformLayout();
  106744. }
  106745. if (!subMesh.effect || !subMesh.effect.isReady()) {
  106746. return false;
  106747. }
  106748. defines._renderId = scene.getRenderId();
  106749. this._wasPreviouslyReady = true;
  106750. return true;
  106751. };
  106752. /**
  106753. * Compute the primary color according to the chosen perceptual color.
  106754. */
  106755. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  106756. if (!this.__perceptualColor) {
  106757. return;
  106758. }
  106759. this._primaryColor.copyFrom(this.__perceptualColor);
  106760. // Revert gamma space.
  106761. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  106762. // Revert image processing configuration.
  106763. if (this._imageProcessingConfiguration) {
  106764. // Revert Exposure.
  106765. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  106766. }
  106767. this._computePrimaryColors();
  106768. };
  106769. /**
  106770. * Compute the highlights and shadow colors according to their chosen levels.
  106771. */
  106772. BackgroundMaterial.prototype._computePrimaryColors = function () {
  106773. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  106774. return;
  106775. }
  106776. // Find the highlight color based on the configuration.
  106777. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  106778. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  106779. // Find the shadow color based on the configuration.
  106780. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  106781. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  106782. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  106783. };
  106784. /**
  106785. * Build the uniform buffer used in the material.
  106786. */
  106787. BackgroundMaterial.prototype.buildUniformLayout = function () {
  106788. // Order is important !
  106789. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  106790. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  106791. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  106792. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  106793. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  106794. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  106795. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  106796. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  106797. this._uniformBuffer.addUniform("pointSize", 1);
  106798. this._uniformBuffer.addUniform("shadowLevel", 1);
  106799. this._uniformBuffer.addUniform("alpha", 1);
  106800. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  106801. this._uniformBuffer.addUniform("vReflectionControl", 4);
  106802. this._uniformBuffer.create();
  106803. };
  106804. /**
  106805. * Unbind the material.
  106806. */
  106807. BackgroundMaterial.prototype.unbind = function () {
  106808. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  106809. this._uniformBuffer.setTexture("diffuseSampler", null);
  106810. }
  106811. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  106812. this._uniformBuffer.setTexture("reflectionSampler", null);
  106813. }
  106814. _super.prototype.unbind.call(this);
  106815. };
  106816. /**
  106817. * Bind only the world matrix to the material.
  106818. * @param world The world matrix to bind.
  106819. */
  106820. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  106821. this._activeEffect.setMatrix("world", world);
  106822. };
  106823. /**
  106824. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  106825. * @param world The world matrix to bind.
  106826. * @param subMesh The submesh to bind for.
  106827. */
  106828. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  106829. var scene = this.getScene();
  106830. var defines = subMesh._materialDefines;
  106831. if (!defines) {
  106832. return;
  106833. }
  106834. var effect = subMesh.effect;
  106835. if (!effect) {
  106836. return;
  106837. }
  106838. this._activeEffect = effect;
  106839. // Matrices
  106840. this.bindOnlyWorldMatrix(world);
  106841. // Bones
  106842. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  106843. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  106844. if (mustRebind) {
  106845. this._uniformBuffer.bindToEffect(effect, "Material");
  106846. this.bindViewProjection(effect);
  106847. var reflectionTexture = this._reflectionTexture;
  106848. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  106849. // Texture uniforms
  106850. if (scene.texturesEnabled) {
  106851. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  106852. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  106853. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  106854. }
  106855. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  106856. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  106857. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  106858. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  106859. }
  106860. }
  106861. if (this.shadowLevel > 0) {
  106862. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  106863. }
  106864. this._uniformBuffer.updateFloat("alpha", this.alpha);
  106865. // Point size
  106866. if (this.pointsCloud) {
  106867. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  106868. }
  106869. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  106870. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  106871. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  106872. }
  106873. else {
  106874. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  106875. }
  106876. }
  106877. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  106878. // Textures
  106879. if (scene.texturesEnabled) {
  106880. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  106881. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  106882. }
  106883. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  106884. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  106885. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  106886. }
  106887. else if (!defines.REFLECTIONBLUR) {
  106888. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  106889. }
  106890. else {
  106891. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  106892. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  106893. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  106894. }
  106895. if (defines.REFLECTIONFRESNEL) {
  106896. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  106897. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  106898. }
  106899. }
  106900. }
  106901. // Clip plane
  106902. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  106903. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  106904. }
  106905. if (mustRebind || !this.isFrozen) {
  106906. if (scene.lightsEnabled) {
  106907. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  106908. }
  106909. // View
  106910. this.bindView(effect);
  106911. // Fog
  106912. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  106913. // image processing
  106914. if (this._imageProcessingConfiguration) {
  106915. this._imageProcessingConfiguration.bind(this._activeEffect);
  106916. }
  106917. }
  106918. this._uniformBuffer.update();
  106919. this._afterBind(mesh, this._activeEffect);
  106920. };
  106921. /**
  106922. * Dispose the material.
  106923. * @param forceDisposeEffect Force disposal of the associated effect.
  106924. * @param forceDisposeTextures Force disposal of the associated textures.
  106925. */
  106926. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  106927. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  106928. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  106929. if (forceDisposeTextures) {
  106930. if (this.diffuseTexture) {
  106931. this.diffuseTexture.dispose();
  106932. }
  106933. if (this.reflectionTexture) {
  106934. this.reflectionTexture.dispose();
  106935. }
  106936. }
  106937. this._renderTargets.dispose();
  106938. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  106939. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  106940. }
  106941. _super.prototype.dispose.call(this, forceDisposeEffect);
  106942. };
  106943. /**
  106944. * Clones the material.
  106945. * @param name The cloned name.
  106946. * @returns The cloned material.
  106947. */
  106948. BackgroundMaterial.prototype.clone = function (name) {
  106949. var _this = this;
  106950. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  106951. };
  106952. /**
  106953. * Serializes the current material to its JSON representation.
  106954. * @returns The JSON representation.
  106955. */
  106956. BackgroundMaterial.prototype.serialize = function () {
  106957. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  106958. serializationObject.customType = "BABYLON.BackgroundMaterial";
  106959. return serializationObject;
  106960. };
  106961. /**
  106962. * Gets the class name of the material
  106963. * @returns "BackgroundMaterial"
  106964. */
  106965. BackgroundMaterial.prototype.getClassName = function () {
  106966. return "BackgroundMaterial";
  106967. };
  106968. /**
  106969. * Parse a JSON input to create back a background material.
  106970. * @param source The JSON data to parse
  106971. * @param scene The scene to create the parsed material in
  106972. * @param rootUrl The root url of the assets the material depends upon
  106973. * @returns the instantiated BackgroundMaterial.
  106974. */
  106975. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  106976. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  106977. };
  106978. /**
  106979. * Standard reflectance value at parallel view angle.
  106980. */
  106981. BackgroundMaterial.StandardReflectance0 = 0.05;
  106982. /**
  106983. * Standard reflectance value at grazing angle.
  106984. */
  106985. BackgroundMaterial.StandardReflectance90 = 0.5;
  106986. __decorate([
  106987. BABYLON.serializeAsColor3()
  106988. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  106989. __decorate([
  106990. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  106991. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  106992. __decorate([
  106993. BABYLON.serializeAsColor3()
  106994. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  106995. __decorate([
  106996. BABYLON.serialize()
  106997. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  106998. __decorate([
  106999. BABYLON.serialize()
  107000. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  107001. __decorate([
  107002. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  107003. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  107004. __decorate([
  107005. BABYLON.serializeAsTexture()
  107006. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  107007. __decorate([
  107008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107009. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  107010. __decorate([
  107011. BABYLON.serialize()
  107012. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  107013. __decorate([
  107014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107015. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  107016. __decorate([
  107017. BABYLON.serializeAsTexture()
  107018. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  107019. __decorate([
  107020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107021. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  107022. __decorate([
  107023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107024. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  107025. __decorate([
  107026. BABYLON.serialize()
  107027. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  107028. __decorate([
  107029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107030. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  107031. __decorate([
  107032. BABYLON.serializeAsVector3()
  107033. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  107034. __decorate([
  107035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107036. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  107037. __decorate([
  107038. BABYLON.serialize()
  107039. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  107040. __decorate([
  107041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107042. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  107043. __decorate([
  107044. BABYLON.serialize()
  107045. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  107046. __decorate([
  107047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107048. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  107049. __decorate([
  107050. BABYLON.serialize()
  107051. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  107052. __decorate([
  107053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107054. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  107055. __decorate([
  107056. BABYLON.serialize()
  107057. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  107058. __decorate([
  107059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107060. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  107061. __decorate([
  107062. BABYLON.serialize()
  107063. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  107064. __decorate([
  107065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107066. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  107067. __decorate([
  107068. BABYLON.serialize()
  107069. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  107070. __decorate([
  107071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107072. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  107073. __decorate([
  107074. BABYLON.serialize()
  107075. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  107076. __decorate([
  107077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107078. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  107079. __decorate([
  107080. BABYLON.serialize()
  107081. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  107082. __decorate([
  107083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107084. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  107085. __decorate([
  107086. BABYLON.serialize()
  107087. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  107088. __decorate([
  107089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107090. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  107091. __decorate([
  107092. BABYLON.serializeAsImageProcessingConfiguration()
  107093. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  107094. return BackgroundMaterial;
  107095. }(BABYLON.PushMaterial));
  107096. BABYLON.BackgroundMaterial = BackgroundMaterial;
  107097. })(BABYLON || (BABYLON = {}));
  107098. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  107099. var __assign = (this && this.__assign) || function () {
  107100. __assign = Object.assign || function(t) {
  107101. for (var s, i = 1, n = arguments.length; i < n; i++) {
  107102. s = arguments[i];
  107103. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  107104. t[p] = s[p];
  107105. }
  107106. return t;
  107107. };
  107108. return __assign.apply(this, arguments);
  107109. };
  107110. var BABYLON;
  107111. (function (BABYLON) {
  107112. /**
  107113. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  107114. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  107115. * It also helps with the default setup of your imageProcessing configuration.
  107116. */
  107117. var EnvironmentHelper = /** @class */ (function () {
  107118. /**
  107119. * constructor
  107120. * @param options
  107121. * @param scene The scene to add the material to
  107122. */
  107123. function EnvironmentHelper(options, scene) {
  107124. var _this = this;
  107125. this._errorHandler = function (message, exception) {
  107126. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  107127. };
  107128. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  107129. this._scene = scene;
  107130. this.onErrorObservable = new BABYLON.Observable();
  107131. this._setupBackground();
  107132. this._setupImageProcessing();
  107133. }
  107134. /**
  107135. * Creates the default options for the helper.
  107136. */
  107137. EnvironmentHelper._getDefaultOptions = function () {
  107138. return {
  107139. createGround: true,
  107140. groundSize: 15,
  107141. groundTexture: this._groundTextureCDNUrl,
  107142. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  107143. groundOpacity: 0.9,
  107144. enableGroundShadow: true,
  107145. groundShadowLevel: 0.5,
  107146. enableGroundMirror: false,
  107147. groundMirrorSizeRatio: 0.3,
  107148. groundMirrorBlurKernel: 64,
  107149. groundMirrorAmount: 1,
  107150. groundMirrorFresnelWeight: 1,
  107151. groundMirrorFallOffDistance: 0,
  107152. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  107153. groundYBias: 0.00001,
  107154. createSkybox: true,
  107155. skyboxSize: 20,
  107156. skyboxTexture: this._skyboxTextureCDNUrl,
  107157. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  107158. backgroundYRotation: 0,
  107159. sizeAuto: true,
  107160. rootPosition: BABYLON.Vector3.Zero(),
  107161. setupImageProcessing: true,
  107162. environmentTexture: this._environmentTextureCDNUrl,
  107163. cameraExposure: 0.8,
  107164. cameraContrast: 1.2,
  107165. toneMappingEnabled: true,
  107166. };
  107167. };
  107168. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  107169. /**
  107170. * Gets the root mesh created by the helper.
  107171. */
  107172. get: function () {
  107173. return this._rootMesh;
  107174. },
  107175. enumerable: true,
  107176. configurable: true
  107177. });
  107178. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  107179. /**
  107180. * Gets the skybox created by the helper.
  107181. */
  107182. get: function () {
  107183. return this._skybox;
  107184. },
  107185. enumerable: true,
  107186. configurable: true
  107187. });
  107188. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  107189. /**
  107190. * Gets the skybox texture created by the helper.
  107191. */
  107192. get: function () {
  107193. return this._skyboxTexture;
  107194. },
  107195. enumerable: true,
  107196. configurable: true
  107197. });
  107198. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  107199. /**
  107200. * Gets the skybox material created by the helper.
  107201. */
  107202. get: function () {
  107203. return this._skyboxMaterial;
  107204. },
  107205. enumerable: true,
  107206. configurable: true
  107207. });
  107208. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  107209. /**
  107210. * Gets the ground mesh created by the helper.
  107211. */
  107212. get: function () {
  107213. return this._ground;
  107214. },
  107215. enumerable: true,
  107216. configurable: true
  107217. });
  107218. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  107219. /**
  107220. * Gets the ground texture created by the helper.
  107221. */
  107222. get: function () {
  107223. return this._groundTexture;
  107224. },
  107225. enumerable: true,
  107226. configurable: true
  107227. });
  107228. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  107229. /**
  107230. * Gets the ground mirror created by the helper.
  107231. */
  107232. get: function () {
  107233. return this._groundMirror;
  107234. },
  107235. enumerable: true,
  107236. configurable: true
  107237. });
  107238. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  107239. /**
  107240. * Gets the ground mirror render list to helps pushing the meshes
  107241. * you wish in the ground reflection.
  107242. */
  107243. get: function () {
  107244. if (this._groundMirror) {
  107245. return this._groundMirror.renderList;
  107246. }
  107247. return null;
  107248. },
  107249. enumerable: true,
  107250. configurable: true
  107251. });
  107252. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  107253. /**
  107254. * Gets the ground material created by the helper.
  107255. */
  107256. get: function () {
  107257. return this._groundMaterial;
  107258. },
  107259. enumerable: true,
  107260. configurable: true
  107261. });
  107262. /**
  107263. * Updates the background according to the new options
  107264. * @param options
  107265. */
  107266. EnvironmentHelper.prototype.updateOptions = function (options) {
  107267. var newOptions = __assign({}, this._options, options);
  107268. if (this._ground && !newOptions.createGround) {
  107269. this._ground.dispose();
  107270. this._ground = null;
  107271. }
  107272. if (this._groundMaterial && !newOptions.createGround) {
  107273. this._groundMaterial.dispose();
  107274. this._groundMaterial = null;
  107275. }
  107276. if (this._groundTexture) {
  107277. if (this._options.groundTexture != newOptions.groundTexture) {
  107278. this._groundTexture.dispose();
  107279. this._groundTexture = null;
  107280. }
  107281. }
  107282. if (this._skybox && !newOptions.createSkybox) {
  107283. this._skybox.dispose();
  107284. this._skybox = null;
  107285. }
  107286. if (this._skyboxMaterial && !newOptions.createSkybox) {
  107287. this._skyboxMaterial.dispose();
  107288. this._skyboxMaterial = null;
  107289. }
  107290. if (this._skyboxTexture) {
  107291. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  107292. this._skyboxTexture.dispose();
  107293. this._skyboxTexture = null;
  107294. }
  107295. }
  107296. if (this._groundMirror && !newOptions.enableGroundMirror) {
  107297. this._groundMirror.dispose();
  107298. this._groundMirror = null;
  107299. }
  107300. if (this._scene.environmentTexture) {
  107301. if (this._options.environmentTexture != newOptions.environmentTexture) {
  107302. this._scene.environmentTexture.dispose();
  107303. }
  107304. }
  107305. this._options = newOptions;
  107306. this._setupBackground();
  107307. this._setupImageProcessing();
  107308. };
  107309. /**
  107310. * Sets the primary color of all the available elements.
  107311. * @param color the main color to affect to the ground and the background
  107312. */
  107313. EnvironmentHelper.prototype.setMainColor = function (color) {
  107314. if (this.groundMaterial) {
  107315. this.groundMaterial.primaryColor = color;
  107316. }
  107317. if (this.skyboxMaterial) {
  107318. this.skyboxMaterial.primaryColor = color;
  107319. }
  107320. if (this.groundMirror) {
  107321. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  107322. }
  107323. };
  107324. /**
  107325. * Setup the image processing according to the specified options.
  107326. */
  107327. EnvironmentHelper.prototype._setupImageProcessing = function () {
  107328. if (this._options.setupImageProcessing) {
  107329. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  107330. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  107331. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  107332. this._setupEnvironmentTexture();
  107333. }
  107334. };
  107335. /**
  107336. * Setup the environment texture according to the specified options.
  107337. */
  107338. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  107339. if (this._scene.environmentTexture) {
  107340. return;
  107341. }
  107342. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  107343. this._scene.environmentTexture = this._options.environmentTexture;
  107344. return;
  107345. }
  107346. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  107347. this._scene.environmentTexture = environmentTexture;
  107348. };
  107349. /**
  107350. * Setup the background according to the specified options.
  107351. */
  107352. EnvironmentHelper.prototype._setupBackground = function () {
  107353. if (!this._rootMesh) {
  107354. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  107355. }
  107356. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  107357. var sceneSize = this._getSceneSize();
  107358. if (this._options.createGround) {
  107359. this._setupGround(sceneSize);
  107360. this._setupGroundMaterial();
  107361. this._setupGroundDiffuseTexture();
  107362. if (this._options.enableGroundMirror) {
  107363. this._setupGroundMirrorTexture(sceneSize);
  107364. }
  107365. this._setupMirrorInGroundMaterial();
  107366. }
  107367. if (this._options.createSkybox) {
  107368. this._setupSkybox(sceneSize);
  107369. this._setupSkyboxMaterial();
  107370. this._setupSkyboxReflectionTexture();
  107371. }
  107372. this._rootMesh.position.x = sceneSize.rootPosition.x;
  107373. this._rootMesh.position.z = sceneSize.rootPosition.z;
  107374. this._rootMesh.position.y = sceneSize.rootPosition.y;
  107375. };
  107376. /**
  107377. * Get the scene sizes according to the setup.
  107378. */
  107379. EnvironmentHelper.prototype._getSceneSize = function () {
  107380. var _this = this;
  107381. var groundSize = this._options.groundSize;
  107382. var skyboxSize = this._options.skyboxSize;
  107383. var rootPosition = this._options.rootPosition;
  107384. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  107385. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  107386. }
  107387. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  107388. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  107389. });
  107390. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  107391. if (this._options.sizeAuto) {
  107392. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  107393. this._scene.activeCamera.upperRadiusLimit) {
  107394. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  107395. skyboxSize = groundSize;
  107396. }
  107397. var sceneDiagonalLenght = sceneDiagonal.length();
  107398. if (sceneDiagonalLenght > groundSize) {
  107399. groundSize = sceneDiagonalLenght * 2;
  107400. skyboxSize = groundSize;
  107401. }
  107402. // 10 % bigger.
  107403. groundSize *= 1.1;
  107404. skyboxSize *= 1.5;
  107405. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  107406. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  107407. }
  107408. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  107409. };
  107410. /**
  107411. * Setup the ground according to the specified options.
  107412. */
  107413. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  107414. var _this = this;
  107415. if (!this._ground || this._ground.isDisposed()) {
  107416. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  107417. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  107418. this._ground.parent = this._rootMesh;
  107419. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  107420. }
  107421. this._ground.receiveShadows = this._options.enableGroundShadow;
  107422. };
  107423. /**
  107424. * Setup the ground material according to the specified options.
  107425. */
  107426. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  107427. if (!this._groundMaterial) {
  107428. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  107429. }
  107430. this._groundMaterial.alpha = this._options.groundOpacity;
  107431. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  107432. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  107433. this._groundMaterial.primaryColor = this._options.groundColor;
  107434. this._groundMaterial.useRGBColor = false;
  107435. this._groundMaterial.enableNoise = true;
  107436. if (this._ground) {
  107437. this._ground.material = this._groundMaterial;
  107438. }
  107439. };
  107440. /**
  107441. * Setup the ground diffuse texture according to the specified options.
  107442. */
  107443. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  107444. if (!this._groundMaterial) {
  107445. return;
  107446. }
  107447. if (this._groundTexture) {
  107448. return;
  107449. }
  107450. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  107451. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  107452. return;
  107453. }
  107454. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  107455. diffuseTexture.gammaSpace = false;
  107456. diffuseTexture.hasAlpha = true;
  107457. this._groundMaterial.diffuseTexture = diffuseTexture;
  107458. };
  107459. /**
  107460. * Setup the ground mirror texture according to the specified options.
  107461. */
  107462. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  107463. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107464. if (!this._groundMirror) {
  107465. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  107466. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  107467. this._groundMirror.anisotropicFilteringLevel = 1;
  107468. this._groundMirror.wrapU = wrapping;
  107469. this._groundMirror.wrapV = wrapping;
  107470. this._groundMirror.gammaSpace = false;
  107471. if (this._groundMirror.renderList) {
  107472. for (var i = 0; i < this._scene.meshes.length; i++) {
  107473. var mesh = this._scene.meshes[i];
  107474. if (mesh !== this._ground &&
  107475. mesh !== this._skybox &&
  107476. mesh !== this._rootMesh) {
  107477. this._groundMirror.renderList.push(mesh);
  107478. }
  107479. }
  107480. }
  107481. }
  107482. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  107483. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  107484. };
  107485. /**
  107486. * Setup the ground to receive the mirror texture.
  107487. */
  107488. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  107489. if (this._groundMaterial) {
  107490. this._groundMaterial.reflectionTexture = this._groundMirror;
  107491. this._groundMaterial.reflectionFresnel = true;
  107492. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  107493. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  107494. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  107495. }
  107496. };
  107497. /**
  107498. * Setup the skybox according to the specified options.
  107499. */
  107500. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  107501. var _this = this;
  107502. if (!this._skybox || this._skybox.isDisposed()) {
  107503. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  107504. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  107505. }
  107506. this._skybox.parent = this._rootMesh;
  107507. };
  107508. /**
  107509. * Setup the skybox material according to the specified options.
  107510. */
  107511. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  107512. if (!this._skybox) {
  107513. return;
  107514. }
  107515. if (!this._skyboxMaterial) {
  107516. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  107517. }
  107518. this._skyboxMaterial.useRGBColor = false;
  107519. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  107520. this._skyboxMaterial.enableNoise = true;
  107521. this._skybox.material = this._skyboxMaterial;
  107522. };
  107523. /**
  107524. * Setup the skybox reflection texture according to the specified options.
  107525. */
  107526. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  107527. if (!this._skyboxMaterial) {
  107528. return;
  107529. }
  107530. if (this._skyboxTexture) {
  107531. return;
  107532. }
  107533. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  107534. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  107535. return;
  107536. }
  107537. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  107538. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  107539. this._skyboxTexture.gammaSpace = false;
  107540. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  107541. };
  107542. /**
  107543. * Dispose all the elements created by the Helper.
  107544. */
  107545. EnvironmentHelper.prototype.dispose = function () {
  107546. if (this._groundMaterial) {
  107547. this._groundMaterial.dispose(true, true);
  107548. }
  107549. if (this._skyboxMaterial) {
  107550. this._skyboxMaterial.dispose(true, true);
  107551. }
  107552. this._rootMesh.dispose(false);
  107553. };
  107554. /**
  107555. * Default ground texture URL.
  107556. */
  107557. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  107558. /**
  107559. * Default skybox texture URL.
  107560. */
  107561. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  107562. /**
  107563. * Default environment texture URL.
  107564. */
  107565. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  107566. return EnvironmentHelper;
  107567. }());
  107568. BABYLON.EnvironmentHelper = EnvironmentHelper;
  107569. })(BABYLON || (BABYLON = {}));
  107570. //# sourceMappingURL=babylon.environmentHelper.js.map
  107571. var BABYLON;
  107572. (function (BABYLON) {
  107573. /** Internal class used to store shapes for emitters */
  107574. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  107575. function ParticleSystemSetEmitterCreationOptions() {
  107576. }
  107577. return ParticleSystemSetEmitterCreationOptions;
  107578. }());
  107579. /**
  107580. * Represents a set of particle systems working together to create a specific effect
  107581. */
  107582. var ParticleSystemSet = /** @class */ (function () {
  107583. function ParticleSystemSet() {
  107584. /**
  107585. * Gets the particle system list
  107586. */
  107587. this.systems = new Array();
  107588. }
  107589. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  107590. /**
  107591. * Gets the emitter node used with this set
  107592. */
  107593. get: function () {
  107594. return this._emitterNode;
  107595. },
  107596. enumerable: true,
  107597. configurable: true
  107598. });
  107599. /**
  107600. * Creates a new emitter mesh as a sphere
  107601. * @param options defines the options used to create the sphere
  107602. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  107603. * @param scene defines the hosting scene
  107604. */
  107605. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  107606. if (this._emitterNode) {
  107607. this._emitterNode.dispose();
  107608. }
  107609. this._emitterCreationOptions = {
  107610. kind: "Sphere",
  107611. options: options,
  107612. renderingGroupId: renderingGroupId
  107613. };
  107614. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  107615. emitterMesh.renderingGroupId = renderingGroupId;
  107616. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  107617. material.emissiveColor = options.color;
  107618. emitterMesh.material = material;
  107619. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  107620. var system = _a[_i];
  107621. system.emitter = emitterMesh;
  107622. }
  107623. this._emitterNode = emitterMesh;
  107624. };
  107625. /**
  107626. * Starts all particle systems of the set
  107627. * @param emitter defines an optional mesh to use as emitter for the particle systems
  107628. */
  107629. ParticleSystemSet.prototype.start = function (emitter) {
  107630. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  107631. var system = _a[_i];
  107632. if (emitter) {
  107633. system.emitter = emitter;
  107634. }
  107635. system.start();
  107636. }
  107637. };
  107638. /**
  107639. * Release all associated resources
  107640. */
  107641. ParticleSystemSet.prototype.dispose = function () {
  107642. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  107643. var system = _a[_i];
  107644. system.dispose();
  107645. }
  107646. this.systems = [];
  107647. if (this._emitterNode) {
  107648. this._emitterNode.dispose();
  107649. this._emitterNode = null;
  107650. }
  107651. };
  107652. /**
  107653. * Serialize the set into a JSON compatible object
  107654. * @returns a JSON compatible representation of the set
  107655. */
  107656. ParticleSystemSet.prototype.serialize = function () {
  107657. var result = {};
  107658. result.systems = [];
  107659. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  107660. var system = _a[_i];
  107661. result.systems.push(system.serialize());
  107662. }
  107663. if (this._emitterNode) {
  107664. result.emitter = this._emitterCreationOptions;
  107665. }
  107666. return result;
  107667. };
  107668. /**
  107669. * Parse a new ParticleSystemSet from a serialized source
  107670. * @param data defines a JSON compatible representation of the set
  107671. * @param scene defines the hosting scene
  107672. * @param gpu defines if we want GPU particles or CPU particles
  107673. * @returns a new ParticleSystemSet
  107674. */
  107675. ParticleSystemSet.Parse = function (data, scene, gpu) {
  107676. if (gpu === void 0) { gpu = false; }
  107677. var result = new ParticleSystemSet();
  107678. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  107679. scene = scene || BABYLON.Engine.LastCreatedScene;
  107680. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  107681. var system = _a[_i];
  107682. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  107683. }
  107684. if (data.emitter) {
  107685. var options = data.emitter.options;
  107686. switch (data.emitter.kind) {
  107687. case "Sphere":
  107688. result.setEmitterAsSphere({
  107689. diameter: options.diameter,
  107690. segments: options.segments,
  107691. color: BABYLON.Color3.FromArray(options.color)
  107692. }, data.emitter.renderingGroupId, scene);
  107693. break;
  107694. }
  107695. }
  107696. return result;
  107697. };
  107698. return ParticleSystemSet;
  107699. }());
  107700. BABYLON.ParticleSystemSet = ParticleSystemSet;
  107701. })(BABYLON || (BABYLON = {}));
  107702. //# sourceMappingURL=babylon.particleSystemSet.js.map
  107703. var BABYLON;
  107704. (function (BABYLON) {
  107705. /**
  107706. * This class is made for on one-liner static method to help creating particle system set.
  107707. */
  107708. var ParticleHelper = /** @class */ (function () {
  107709. function ParticleHelper() {
  107710. }
  107711. /**
  107712. * Create a default particle system that you can tweak
  107713. * @param emitter defines the emitter to use
  107714. * @param capacity defines the system capacity (default is 500 particles)
  107715. * @param scene defines the hosting scene
  107716. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  107717. * @returns the new Particle system
  107718. */
  107719. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  107720. if (capacity === void 0) { capacity = 500; }
  107721. if (useGPU === void 0) { useGPU = false; }
  107722. var system;
  107723. if (useGPU) {
  107724. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  107725. }
  107726. else {
  107727. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  107728. }
  107729. system.emitter = emitter;
  107730. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  107731. system.createConeEmitter(0.1, Math.PI / 4);
  107732. // Particle color
  107733. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  107734. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  107735. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  107736. // Particle Size
  107737. system.minSize = 0.1;
  107738. system.maxSize = 0.1;
  107739. // Emission speed
  107740. system.minEmitPower = 2;
  107741. system.maxEmitPower = 2;
  107742. // Update speed
  107743. system.updateSpeed = 1 / 60;
  107744. system.emitRate = 30;
  107745. return system;
  107746. };
  107747. /**
  107748. * This is the main static method (one-liner) of this helper to create different particle systems
  107749. * @param type This string represents the type to the particle system to create
  107750. * @param scene The scene where the particle system should live
  107751. * @param gpu If the system will use gpu
  107752. * @returns the ParticleSystemSet created
  107753. */
  107754. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  107755. if (gpu === void 0) { gpu = false; }
  107756. if (!scene) {
  107757. scene = BABYLON.Engine.LastCreatedScene;
  107758. ;
  107759. }
  107760. var token = {};
  107761. scene._addPendingData(token);
  107762. return new Promise(function (resolve, reject) {
  107763. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  107764. scene._removePendingData(token);
  107765. return reject("Particle system with GPU is not supported.");
  107766. }
  107767. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  107768. scene._removePendingData(token);
  107769. var newData = JSON.parse(data.toString());
  107770. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  107771. }, undefined, undefined, undefined, function (req, exception) {
  107772. scene._removePendingData(token);
  107773. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  107774. });
  107775. });
  107776. };
  107777. /**
  107778. * Static function used to export a particle system to a ParticleSystemSet variable.
  107779. * Please note that the emitter shape is not exported
  107780. * @param system defines the particle systems to export
  107781. */
  107782. ParticleHelper.ExportSet = function (systems) {
  107783. var set = new BABYLON.ParticleSystemSet();
  107784. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  107785. var system = systems_1[_i];
  107786. set.systems.push(system);
  107787. }
  107788. return set;
  107789. };
  107790. /**
  107791. * Gets or sets base Assets URL
  107792. */
  107793. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  107794. return ParticleHelper;
  107795. }());
  107796. BABYLON.ParticleHelper = ParticleHelper;
  107797. })(BABYLON || (BABYLON = {}));
  107798. //# sourceMappingURL=babylon.particleHelper.js.map
  107799. var BABYLON;
  107800. (function (BABYLON) {
  107801. /**
  107802. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  107803. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  107804. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  107805. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  107806. */
  107807. var VideoDome = /** @class */ (function (_super) {
  107808. __extends(VideoDome, _super);
  107809. /**
  107810. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  107811. * @param name Element's name, child elements will append suffixes for their own names.
  107812. * @param urlsOrVideo defines the url(s) or the video element to use
  107813. * @param options An object containing optional or exposed sub element properties
  107814. */
  107815. function VideoDome(name, urlsOrVideo, options, scene) {
  107816. var _this = _super.call(this, name, scene) || this;
  107817. _this._useDirectMapping = false;
  107818. // set defaults and manage values
  107819. name = name || "videoDome";
  107820. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  107821. options.clickToPlay = Boolean(options.clickToPlay);
  107822. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  107823. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  107824. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  107825. if (options.useDirectMapping === undefined) {
  107826. _this._useDirectMapping = true;
  107827. }
  107828. else {
  107829. _this._useDirectMapping = options.useDirectMapping;
  107830. }
  107831. _this._setReady(false);
  107832. // create
  107833. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  107834. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  107835. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  107836. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  107837. texture.onLoadObservable.addOnce(function () {
  107838. _this._setReady(true);
  107839. });
  107840. // configure material
  107841. material.useEquirectangularFOV = true;
  107842. material.fovMultiplier = 1.0;
  107843. material.opacityFresnel = false;
  107844. if (_this._useDirectMapping) {
  107845. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107846. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107847. material.diffuseTexture = texture;
  107848. }
  107849. else {
  107850. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  107851. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107852. material.reflectionTexture = texture;
  107853. }
  107854. // configure mesh
  107855. _this._mesh.material = material;
  107856. _this._mesh.parent = _this;
  107857. // optional configuration
  107858. if (options.clickToPlay) {
  107859. scene.onPointerUp = function () {
  107860. _this._videoTexture.video.play();
  107861. };
  107862. }
  107863. return _this;
  107864. }
  107865. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  107866. /**
  107867. * Gets the video texture being displayed on the sphere
  107868. */
  107869. get: function () {
  107870. return this._videoTexture;
  107871. },
  107872. enumerable: true,
  107873. configurable: true
  107874. });
  107875. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  107876. /**
  107877. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  107878. * Also see the options.resolution property.
  107879. */
  107880. get: function () {
  107881. return this._material.fovMultiplier;
  107882. },
  107883. set: function (value) {
  107884. this._material.fovMultiplier = value;
  107885. },
  107886. enumerable: true,
  107887. configurable: true
  107888. });
  107889. /**
  107890. * Releases resources associated with this node.
  107891. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  107892. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  107893. */
  107894. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  107895. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  107896. this._videoTexture.dispose();
  107897. this._mesh.dispose();
  107898. this._material.dispose();
  107899. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  107900. };
  107901. return VideoDome;
  107902. }(BABYLON.TransformNode));
  107903. BABYLON.VideoDome = VideoDome;
  107904. })(BABYLON || (BABYLON = {}));
  107905. //# sourceMappingURL=babylon.videoDome.js.map
  107906. var BABYLON;
  107907. (function (BABYLON) {
  107908. /**
  107909. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  107910. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  107911. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  107912. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  107913. */
  107914. var PhotoDome = /** @class */ (function (_super) {
  107915. __extends(PhotoDome, _super);
  107916. /**
  107917. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  107918. * @param name Element's name, child elements will append suffixes for their own names.
  107919. * @param urlsOfPhoto defines the url of the photo to display
  107920. * @param options defines an object containing optional or exposed sub element properties
  107921. * @param onError defines a callback called when an error occured while loading the texture
  107922. */
  107923. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  107924. if (onError === void 0) { onError = null; }
  107925. var _this = _super.call(this, name, scene) || this;
  107926. _this._useDirectMapping = false;
  107927. /**
  107928. * Observable raised when an error occured while loading the 360 image
  107929. */
  107930. _this.onLoadErrorObservable = new BABYLON.Observable();
  107931. // set defaults and manage values
  107932. name = name || "photoDome";
  107933. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  107934. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  107935. if (options.useDirectMapping === undefined) {
  107936. _this._useDirectMapping = true;
  107937. }
  107938. else {
  107939. _this._useDirectMapping = options.useDirectMapping;
  107940. }
  107941. _this._setReady(false);
  107942. // create
  107943. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  107944. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  107945. // configure material
  107946. material.opacityFresnel = false;
  107947. material.useEquirectangularFOV = true;
  107948. material.fovMultiplier = 1.0;
  107949. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  107950. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  107951. if (onError) {
  107952. onError(message, exception);
  107953. }
  107954. });
  107955. _this.photoTexture.onLoadObservable.addOnce(function () {
  107956. _this._setReady(true);
  107957. });
  107958. // configure mesh
  107959. _this._mesh.material = material;
  107960. _this._mesh.parent = _this;
  107961. return _this;
  107962. }
  107963. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  107964. /**
  107965. * Gets or sets the texture being displayed on the sphere
  107966. */
  107967. get: function () {
  107968. return this._photoTexture;
  107969. },
  107970. set: function (value) {
  107971. if (this._photoTexture === value) {
  107972. return;
  107973. }
  107974. this._photoTexture = value;
  107975. if (this._useDirectMapping) {
  107976. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107977. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107978. this._material.diffuseTexture = this._photoTexture;
  107979. }
  107980. else {
  107981. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  107982. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107983. this._material.reflectionTexture = this._photoTexture;
  107984. }
  107985. },
  107986. enumerable: true,
  107987. configurable: true
  107988. });
  107989. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  107990. /**
  107991. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  107992. * Also see the options.resolution property.
  107993. */
  107994. get: function () {
  107995. return this._material.fovMultiplier;
  107996. },
  107997. set: function (value) {
  107998. this._material.fovMultiplier = value;
  107999. },
  108000. enumerable: true,
  108001. configurable: true
  108002. });
  108003. /**
  108004. * Releases resources associated with this node.
  108005. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  108006. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  108007. */
  108008. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  108009. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  108010. this._photoTexture.dispose();
  108011. this._mesh.dispose();
  108012. this._material.dispose();
  108013. this.onLoadErrorObservable.clear();
  108014. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  108015. };
  108016. return PhotoDome;
  108017. }(BABYLON.TransformNode));
  108018. BABYLON.PhotoDome = PhotoDome;
  108019. })(BABYLON || (BABYLON = {}));
  108020. //# sourceMappingURL=babylon.photoDome.js.map
  108021. var BABYLON;
  108022. (function (BABYLON) {
  108023. BABYLON.Engine.prototype.createQuery = function () {
  108024. return this._gl.createQuery();
  108025. };
  108026. BABYLON.Engine.prototype.deleteQuery = function (query) {
  108027. this._gl.deleteQuery(query);
  108028. return this;
  108029. };
  108030. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  108031. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  108032. };
  108033. BABYLON.Engine.prototype.getQueryResult = function (query) {
  108034. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  108035. };
  108036. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  108037. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  108038. this._gl.beginQuery(glAlgorithm, query);
  108039. return this;
  108040. };
  108041. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  108042. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  108043. this._gl.endQuery(glAlgorithm);
  108044. return this;
  108045. };
  108046. BABYLON.Engine.prototype._createTimeQuery = function () {
  108047. var timerQuery = this.getCaps().timerQuery;
  108048. if (timerQuery.createQueryEXT) {
  108049. return timerQuery.createQueryEXT();
  108050. }
  108051. return this.createQuery();
  108052. };
  108053. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  108054. var timerQuery = this.getCaps().timerQuery;
  108055. if (timerQuery.deleteQueryEXT) {
  108056. timerQuery.deleteQueryEXT(query);
  108057. return;
  108058. }
  108059. this.deleteQuery(query);
  108060. };
  108061. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  108062. var timerQuery = this.getCaps().timerQuery;
  108063. if (timerQuery.getQueryObjectEXT) {
  108064. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  108065. }
  108066. return this.getQueryResult(query);
  108067. };
  108068. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  108069. var timerQuery = this.getCaps().timerQuery;
  108070. if (timerQuery.getQueryObjectEXT) {
  108071. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  108072. }
  108073. return this.isQueryResultAvailable(query);
  108074. };
  108075. BABYLON.Engine.prototype.startTimeQuery = function () {
  108076. var caps = this.getCaps();
  108077. var timerQuery = caps.timerQuery;
  108078. if (!timerQuery) {
  108079. return null;
  108080. }
  108081. var token = new BABYLON._TimeToken();
  108082. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  108083. if (caps.canUseTimestampForTimerQuery) {
  108084. token._startTimeQuery = this._createTimeQuery();
  108085. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  108086. }
  108087. else {
  108088. if (this._currentNonTimestampToken) {
  108089. return this._currentNonTimestampToken;
  108090. }
  108091. token._timeElapsedQuery = this._createTimeQuery();
  108092. if (timerQuery.beginQueryEXT) {
  108093. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  108094. }
  108095. else {
  108096. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  108097. }
  108098. this._currentNonTimestampToken = token;
  108099. }
  108100. return token;
  108101. };
  108102. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  108103. var caps = this.getCaps();
  108104. var timerQuery = caps.timerQuery;
  108105. if (!timerQuery || !token) {
  108106. return -1;
  108107. }
  108108. if (caps.canUseTimestampForTimerQuery) {
  108109. if (!token._startTimeQuery) {
  108110. return -1;
  108111. }
  108112. if (!token._endTimeQuery) {
  108113. token._endTimeQuery = this._createTimeQuery();
  108114. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  108115. }
  108116. }
  108117. else if (!token._timeElapsedQueryEnded) {
  108118. if (!token._timeElapsedQuery) {
  108119. return -1;
  108120. }
  108121. if (timerQuery.endQueryEXT) {
  108122. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  108123. }
  108124. else {
  108125. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  108126. }
  108127. token._timeElapsedQueryEnded = true;
  108128. }
  108129. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  108130. var available = false;
  108131. if (token._endTimeQuery) {
  108132. available = this._getTimeQueryAvailability(token._endTimeQuery);
  108133. }
  108134. else if (token._timeElapsedQuery) {
  108135. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  108136. }
  108137. if (available && !disjoint) {
  108138. var result = 0;
  108139. if (caps.canUseTimestampForTimerQuery) {
  108140. if (!token._startTimeQuery || !token._endTimeQuery) {
  108141. return -1;
  108142. }
  108143. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  108144. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  108145. result = timeEnd - timeStart;
  108146. this._deleteTimeQuery(token._startTimeQuery);
  108147. this._deleteTimeQuery(token._endTimeQuery);
  108148. token._startTimeQuery = null;
  108149. token._endTimeQuery = null;
  108150. }
  108151. else {
  108152. if (!token._timeElapsedQuery) {
  108153. return -1;
  108154. }
  108155. result = this._getTimeQueryResult(token._timeElapsedQuery);
  108156. this._deleteTimeQuery(token._timeElapsedQuery);
  108157. token._timeElapsedQuery = null;
  108158. token._timeElapsedQueryEnded = false;
  108159. this._currentNonTimestampToken = null;
  108160. }
  108161. return result;
  108162. }
  108163. return -1;
  108164. };
  108165. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  108166. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  108167. };
  108168. // We also need to update AbstractMesh as there is a portion of the code there
  108169. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  108170. var engine = this.getEngine();
  108171. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  108172. this._isOccluded = false;
  108173. return;
  108174. }
  108175. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  108176. this._isOccluded = false;
  108177. return;
  108178. }
  108179. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  108180. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  108181. if (isOcclusionQueryAvailable) {
  108182. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  108183. this._isOcclusionQueryInProgress = false;
  108184. this._occlusionInternalRetryCounter = 0;
  108185. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  108186. }
  108187. else {
  108188. this._occlusionInternalRetryCounter++;
  108189. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  108190. this._isOcclusionQueryInProgress = false;
  108191. this._occlusionInternalRetryCounter = 0;
  108192. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  108193. // if strict continue the last state of the object.
  108194. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  108195. }
  108196. else {
  108197. return;
  108198. }
  108199. }
  108200. }
  108201. var scene = this.getScene();
  108202. if (scene.getBoundingBoxRenderer) {
  108203. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  108204. if (!this._occlusionQuery) {
  108205. this._occlusionQuery = engine.createQuery();
  108206. }
  108207. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  108208. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  108209. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  108210. this._isOcclusionQueryInProgress = true;
  108211. }
  108212. };
  108213. })(BABYLON || (BABYLON = {}));
  108214. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  108215. var BABYLON;
  108216. (function (BABYLON) {
  108217. /**
  108218. * Class used to generate noise procedural textures
  108219. */
  108220. var NoiseProceduralTexture = /** @class */ (function (_super) {
  108221. __extends(NoiseProceduralTexture, _super);
  108222. /**
  108223. * Creates a new NoiseProceduralTexture
  108224. * @param name defines the name fo the texture
  108225. * @param size defines the size of the texture (default is 256)
  108226. * @param scene defines the hosting scene
  108227. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  108228. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  108229. */
  108230. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  108231. if (size === void 0) { size = 256; }
  108232. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  108233. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  108234. _this._time = 0;
  108235. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  108236. _this.brightness = 0.2;
  108237. /** Defines the number of octaves to process */
  108238. _this.octaves = 3;
  108239. /** Defines the level of persistence (0.8 by default) */
  108240. _this.persistence = 0.8;
  108241. /** Gets or sets animation speed factor (default is 1) */
  108242. _this.animationSpeedFactor = 1;
  108243. _this._updateShaderUniforms();
  108244. return _this;
  108245. }
  108246. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  108247. var scene = this.getScene();
  108248. if (!scene) {
  108249. return;
  108250. }
  108251. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  108252. this.setFloat("brightness", this.brightness);
  108253. this.setFloat("persistence", this.persistence);
  108254. this.setFloat("timeScale", this._time);
  108255. };
  108256. NoiseProceduralTexture.prototype._getDefines = function () {
  108257. return "#define OCTAVES " + this.octaves;
  108258. };
  108259. /** Generate the current state of the procedural texture */
  108260. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  108261. this._updateShaderUniforms();
  108262. _super.prototype.render.call(this, useCameraPostProcess);
  108263. };
  108264. /**
  108265. * Serializes this noise procedural texture
  108266. * @returns a serialized noise procedural texture object
  108267. */
  108268. NoiseProceduralTexture.prototype.serialize = function () {
  108269. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  108270. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  108271. return serializationObject;
  108272. };
  108273. /**
  108274. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  108275. * @param parsedTexture defines parsed texture data
  108276. * @param scene defines the current scene
  108277. * @param rootUrl defines the root URL containing noise procedural texture information
  108278. * @returns a parsed NoiseProceduralTexture
  108279. */
  108280. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  108281. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  108282. return texture;
  108283. };
  108284. return NoiseProceduralTexture;
  108285. }(BABYLON.ProceduralTexture));
  108286. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  108287. })(BABYLON || (BABYLON = {}));
  108288. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  108289. var __assign = (this && this.__assign) || function () {
  108290. __assign = Object.assign || function(t) {
  108291. for (var s, i = 1, n = arguments.length; i < n; i++) {
  108292. s = arguments[i];
  108293. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  108294. t[p] = s[p];
  108295. }
  108296. return t;
  108297. };
  108298. return __assign.apply(this, arguments);
  108299. };
  108300. var BABYLON;
  108301. (function (BABYLON) {
  108302. /**
  108303. * This can helps recording videos from BabylonJS.
  108304. * This is based on the available WebRTC functionalities of the browser.
  108305. *
  108306. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  108307. */
  108308. var VideoRecorder = /** @class */ (function () {
  108309. /**
  108310. * Create a new VideoCapture object which can help converting what you see in Babylon to
  108311. * a video file.
  108312. * @param engine Defines the BabylonJS Engine you wish to record
  108313. * @param options Defines options that can be used to customized the capture
  108314. */
  108315. function VideoRecorder(engine, options) {
  108316. if (options === void 0) { options = null; }
  108317. if (!VideoRecorder.IsSupported(engine)) {
  108318. throw "Your browser does not support recording so far.";
  108319. }
  108320. var canvas = engine.getRenderingCanvas();
  108321. if (!canvas) {
  108322. throw "The babylon engine must have a canvas to be recorded";
  108323. }
  108324. this._canvas = canvas;
  108325. this._canvas.isRecording = false;
  108326. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  108327. var stream = this._canvas.captureStream(this._options.fps);
  108328. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  108329. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  108330. this._mediaRecorder.onerror = this._handleError.bind(this);
  108331. this._mediaRecorder.onstop = this._handleStop.bind(this);
  108332. }
  108333. /**
  108334. * Returns wehther or not the VideoRecorder is available in your browser.
  108335. * @param engine Defines the Babylon Engine to check the support for
  108336. * @returns true if supported otherwise false
  108337. */
  108338. VideoRecorder.IsSupported = function (engine) {
  108339. var canvas = engine.getRenderingCanvas();
  108340. return (!!canvas && typeof canvas.captureStream === "function");
  108341. };
  108342. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  108343. /**
  108344. * True wether a recording is already in progress.
  108345. */
  108346. get: function () {
  108347. return !!this._canvas && this._canvas.isRecording;
  108348. },
  108349. enumerable: true,
  108350. configurable: true
  108351. });
  108352. /**
  108353. * Stops the current recording before the default capture timeout passed in the startRecording
  108354. * functions.
  108355. */
  108356. VideoRecorder.prototype.stopRecording = function () {
  108357. if (!this._canvas || !this._mediaRecorder) {
  108358. return;
  108359. }
  108360. if (!this.isRecording) {
  108361. return;
  108362. }
  108363. this._canvas.isRecording = false;
  108364. this._mediaRecorder.stop();
  108365. };
  108366. /**
  108367. * Starts recording the canvas for a max duration specified in parameters.
  108368. * @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.
  108369. * @param maxDuration Defines the maximum recording time in seconds.
  108370. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  108371. * @return a promise callback at the end of the recording with the video data in Blob.
  108372. */
  108373. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  108374. var _this = this;
  108375. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  108376. if (maxDuration === void 0) { maxDuration = 7; }
  108377. if (!this._canvas || !this._mediaRecorder) {
  108378. throw "Recorder has already been disposed";
  108379. }
  108380. if (this.isRecording) {
  108381. throw "Recording already in progress";
  108382. }
  108383. if (maxDuration > 0) {
  108384. setTimeout(function () {
  108385. _this.stopRecording();
  108386. }, maxDuration * 1000);
  108387. }
  108388. this._fileName = fileName;
  108389. this._recordedChunks = [];
  108390. this._resolve = null;
  108391. this._reject = null;
  108392. this._canvas.isRecording = true;
  108393. this._mediaRecorder.start(this._options.recordChunckSize);
  108394. return new Promise(function (resolve, reject) {
  108395. _this._resolve = resolve;
  108396. _this._reject = reject;
  108397. });
  108398. };
  108399. /**
  108400. * Releases internal resources used during the recording.
  108401. */
  108402. VideoRecorder.prototype.dispose = function () {
  108403. this._canvas = null;
  108404. this._mediaRecorder = null;
  108405. this._recordedChunks = [];
  108406. this._fileName = null;
  108407. this._resolve = null;
  108408. this._reject = null;
  108409. };
  108410. VideoRecorder.prototype._handleDataAvailable = function (event) {
  108411. if (event.data.size > 0) {
  108412. this._recordedChunks.push(event.data);
  108413. }
  108414. };
  108415. VideoRecorder.prototype._handleError = function (event) {
  108416. this.stopRecording();
  108417. if (this._reject) {
  108418. this._reject(event.error);
  108419. }
  108420. else {
  108421. throw new event.error;
  108422. }
  108423. };
  108424. VideoRecorder.prototype._handleStop = function () {
  108425. this.stopRecording();
  108426. var superBuffer = new Blob(this._recordedChunks);
  108427. if (this._resolve) {
  108428. this._resolve(superBuffer);
  108429. }
  108430. window.URL.createObjectURL(superBuffer);
  108431. if (this._fileName) {
  108432. BABYLON.Tools.Download(superBuffer, this._fileName);
  108433. }
  108434. };
  108435. VideoRecorder._defaultOptions = {
  108436. mimeType: "video/webm",
  108437. fps: 25,
  108438. recordChunckSize: 3000
  108439. };
  108440. return VideoRecorder;
  108441. }());
  108442. BABYLON.VideoRecorder = VideoRecorder;
  108443. })(BABYLON || (BABYLON = {}));
  108444. //# sourceMappingURL=babylon.videoRecorder.js.map
  108445. 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\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#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}\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#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\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>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*alpha+vec3(1.0)*(1.0-alpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\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}\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#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\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 SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta;\n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n} 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(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\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"};
  108446. 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};"};